????

Your IP : 18.224.202.121


Current Path : C:/Windows/Microsoft.NET/Framework64/v4.0.30319/
Upload File :
Current File : C:/Windows/Microsoft.NET/Framework64/v4.0.30319/System.Data.Entity.Design.dll

MZ����@���	�!�L�!This program cannot be run in DOS mode.

$PEL.�^^�" 0�N�  �` ��`��O �KF A�P  H.text� � `.rsrc�K L�@@.reloc�D@B�H����	�n��P"(0
*�{-}(1
(
(2
(1
*"(3
*(
*�(4
rp(5
o6
s7
}w*0 ~v-s
v(+&~v*
*.({w*0s(
-*{w(o9
,Q�,M+6�u�
	,&	o:
 1	 �o;
r5p(<
�X�i2�(=
(>
**0(
-*{w(o9
**R(
*0(
-*{w(o?
**0G}zs}�(4
}{}|}}�{�s5}~*0

(,.+s@
+sA
oB
_�}z{xo�s�(�( ,ݛ()oC
,
((�-o�r=psD

+c(E
sF
oG
rAp(H
		�/oI
rcp(J
(K
oL
sM
sN
r=psD

sO
rmpoP
oQ
oR
(oS
,?oT
joU
&sV
()o�(('~W
(X
o�ݑ
 �
(� �(�m �(�[
 �
(�I �(�7,oY
,oZ
,o[
o
,o\
	,	oY
�*A�fq0f�1f�2f�3f�4��70T{z,*{{o]
o+&�4&o_

�6oI
o]
( �o]
(�*
470�{z,*o`
oa

(b
sc
od
+a(e

	o]
of
,>o]
	o]
og
,*o]
(} �o`
oh
o]
(+
	o]
oi
&(j
-���o
�*'n�0�{z,*(b
sc

ok
ol
+V(m
(�,Ft>
	o]
of
,$ �	o]
(~sn
oo
(+
	o]
oi
&(p
-���o
�* c�0*s
}�{{o+�sr
(+*0?s
}�ot
�su
(+(+,ow
1(+**0%	(
,oy
Toz
T*%TT*0f
%TT(
uC,6o{
o|
,(o{
o}
oy
To{
o}
oz
T*,oy
Toz
T*2{o�*{�*j{y-s~
}y{y*R{�s
o�
*j{�o�
s�
o�
*Z{�s�
o�
*08{|({�o�
{|o�
s�
o�
*02{|({�{|o�
s�
o�
*04{|({�{|o�
s�
o�
*0?{�o�

+(�
o�
,�(�
-���o
�**!->�s%}�*0&
o�
((o�
($
(o*0'
o�
((o�
($
(o*^(�
,*rqp(J
*0}
o_
31o�
o�
-(o�
o*(o�
o)*o�
(&(�
,	o�

+o�
((o�
($
(o*2{|o�
*6(&((*0
{o�o�,**j{}-s�}}{}*{~*{z*2(+,**6{o�*6{o�*&(*0�(3o�
o�

(3o�
o�
(]oo�
(`rup(E�%(3o�
�%(3o�
�%o�
�%o�
(2�%(1�%o�
�%o�
(2�%(1�oAo�
&s�
*�(]o�
o�
t�o�
o"s�
*0'�VoI

(_r�po#([*2(
uQ*{�*:(4
}�*0�r�p(@(:rp�(A
�%rmp�%��(Co�
o�
&r�p�(Ao�
o�
&o{o](7*0roo�

+No�
o-o#+o%r�p�%s�
�(A
o�
	o�
&o
-��
,o
�*
Zg
0o
u@
(;*0J�(A
�%r
p�%o�
�%r)p�%o�
�(Co�
o�
&*0�r3p(@�%o`
o�
�%o`
o�
�%o�
�(A
o�
o�
&(=,9o�
1/o�
o�
o�
�o�
(z �o�*^r\0[{�-@r�p�%r�p�%�(�
o6
o�
o�
oI
�(A}�o�
{�o�
&*0�o�o�
o�
(�-o�o�
o�
(�,xr3p(@�(A
o�,�%rip�%��(Co�o�
-�%r�p�%��(Co�
o�
&8r�p(@�(Ao�
o�
&r�p�(A�%(4�(�
os�
rGps�
�(Bo�
o�
&o�o�
o�
(�-xrWp�(A�%r�p�%��(Co�
o�
&r�p�(A�%r�p�%��(Co�
o�
&(F,Ao�
18o�
o�
o�
�%o]o�o�
(z �o�(=*��%\0�r�p(@(:rp�(A
�%rmp�%��(Co�
o�
&r�p�(Ao�
o�
&oWo](7*F~�rqp(J
*0(4os�

(B*08
++�uU
	-s�

o�
	s�
o�
&X�i2�*0@
+5�uU-	�s�
o�
Y�oI
s�
o�
&X
�i2�*0S�(�
o�
�(A
�(�
o�
�(Ao�
o�
&o�
o�
&*03�(�
o�
�%��(A
o�
o�
&*0 rp�(A
o�
o�
&*.r{p��*0�(I
,o�
(�-o�
(M8�o_

	.	3&teo�
(�+rtdoh
(�+_o5
r�po�
(�
,o5
r)po�
(�
,o�
,oI
(�+(���%�(O(N*Zu`,t`*o�
*�(�
-�o�
%(�
,*(Q(O*0#
+�s�
o�
&X�i2�*02
(=
r�p�%o�
�%�(>

s�
o�
&*0(�
,��%r	p�*rpr	po�


o�
2X(�,X
+
o�
Y1(�,Y
+	o:
Y,YXo;
,(�(Q
	�i3
		�o�
�	*	8��(�:�~�o�
		o�
-r	p8�-	o�
rpo�
o�
8�	o�
rpo�
o�


(�
-|
o�
-p
o�
,
+^o:

o:
(�
+5o�

o�
.-	r	p+o;
+X2�(�
-X�i?����o:

+5	
�o:
2	
	
�o�
�	
	
��o�
�
X

	�i2�	*�-*o�
(�
-r+po�
(M(P*6rKp(P*0U(�
r[p�%�(>
s�
o�
&(K(�
rgp�%�(>
s�
o�
&*�(�
,��%r	p�*rpr	po�
�%
�o�
*Jrups�
��*&(*j(]o*o?(*0(
-(_o1
*2(Wo�
*2(ud*:(4
(^*6(as�
*6(as�
*0s�

s�
*^~�-
s�
��~�*{�*"}�*2{�o*2{�o**b~�-s�
��~�*Rr�p}�(*0+o�(too
s�

o�
(_o0(ts�(]o-o,"oo�
-o�
oo�
&+o�
(_o0o�
&(too
o((to�
(H(too
o(
(j(k(tok
ol
+K(m
(�,9t>(mo�
o�
&(lo�
o�
&(p
-���o
�(tok
ol
	+3	(m


(�,!
t>(no�
o�
&	(p
-��	�o
�(to�
o�

++
(�
(e,(oo�
o�
&
(�
-��
�o
�(too
o(s�

	o�
&	*(�X=]@��8�0(f
uko�
,**06
o�
,*o�
o�
o�

(�
,t�o�
o�

*z(	(](to(h*0�(tok
ol

+r(m
(�,bt>o�
(�(�(i-B(]o�
o�
o�
(�(�o�
(�(�(� �o(p
-���o
�*�� 3 `. 0��***0� s�

 `o�
o�
r�p(too
(<
s�
o�
&o�
(too
s�
o�
&(too
(too
(�o�
(Jo�
(so�
&o�
o�
&s�
 `o�
(_o4r�ps�
o�
o�
&o�
o�
s�
o�
&o�
(too
s�
o�
&(too
(�o�
(Jo�
(so�
&o�
o�
&s�

	 `o�
(_r�po$rps�
	o�
o�
&	o�
o�
s�
o�
&	o�
(too
s�
o�
&(too
(�	o�
(J	o�
(so�
&o�
	o�
&*0r!s�

{�o�
�#(�
s�
o�
 `o�
o�
o�
&(]o)(too
rqp{�(J
	s|o�
*0^"s�

(]o*o= Po�
o�
(Ao�
(]o�
o%(_r5po%o�
*0 #s�

(]o*o=(�`o�
o�
o�
o�
o�
r5prMprepo�
rip(J

(]o�
o%(_o%o�
o�
(Ao�
s�(]o.o�,o�o�
o�
-o�
(too
(t(�zo�,Eo�
1;o�
o�
o�
�'	(](too
(z �	o�o�,Eo�
1;o�
o�
o�
�'
(](too
({ �
o�o�
(\s�
(Y�n%(\s�
s�
�I%�s�
�U%	s�
�s
s
�s
o
&o�
(\s�
s
o
&o�
(H*'\Th'\0�$s�

(]o*o=o�
(�`o�
rmpo�
(<
o�
s
(]o�
o%o
o�
o�
(@o
o�
o�
&�#(�
s�
o�
o�
s�
ryp�U%o�
s�
�%o�
s�
�s
o�
&o�
(H*0�%s�

(]o*o=o�
o�
(�`o�
(]o+~%-&~�� s	
%�s�(f(�
,t�o�
o�
(]o%
(_	o+o�
o�
(Hs

o�
s�
o
o
o

+(
(q(
-���!o
�o
o

+B(
		o
-	(p

o
+	o�&s
o
(
-���!o
�s�
r�p�I%	�s�
o�
o
s
s
o
&*� �O]05&o�&(ro
r�p(<
o�o�
(_�%(�
os
o
&s

s
	(_�%(�
o�U%o
s�
�%(_os�
�s
s
	(_�%(�
o�U%o
s�
�%�s
s
o�
,r�ps�
+(as�
o�
�n%��n%�s
o
&	*0N'(r
o�
-(_o+(_o)o
o�s�

o�
	o�
&*0-(o
,�%(�
*o�
o�
tq
o�
*^s�
{��Us
*2(
u<*0V)(({o+o

+"(
(](s�o(
-���#o
�*/G0�*(
({o
o
>�o
@�o
o�
r�ps�
o�
&({o
od
+$(e

	o�
o�
s�
o�
&(j
-���o
�o�
r�ps�
o�
&*Y1�j(]o*o6(*0(
-(_o2
*2({o
*2(ut*0�+(4
(�(I
3�iY�(*�iY�(�iY�YE								*(�*(�*03,
-~�(��
+3
~�(��
,	o"*{�*"}�*{�*"}�*{�*"}�*{�*"}�*Rrpr5p(�*�rEprmp(�( 
r�p(J
*0(-o!

2o:
o"
o#
*Fr�pr�p(�*Fr�pr�p(�*Fr�pr	p(�*Fr	pr!	p(�*Fr/	pr7	p(�*FrG	prO	p(�*Fr/	pr	p(�*FrG	pr!	p(�*Fr�pr_	p(�*Fr	prs	p(�*Fr/	pr_	p(�*FrG	prs	p(�*Fr/	pr�	p(�*FrG	pr�	p(�*Fr�pr7	p(�*Fr	prO	p(�*Fr�pr�	p(�*Fr	pr�	p(�*0Ar�	p(�2*r�	p(�
/*r5p(�2
r�	po#
*0--(�2*(�
/*r�	p(<
o#
*0<o!

/*o:
X,Y($
,o:
.	($
,**0Z�P%��s!�%��s!�%��s!�%��s!�%��s!�%��s!�%��s!�%��s!�%	��s!�%
��s!�%��s!����P%��s!�%��s!�%��s!�%��s!�%��s!�%��s!�%��s!�%	��s!�%
��s!�%��s!���*(%
*"5**0�.(�(&

+P('
(�o~o(
,(�o~o)
+s%
(�o~o*
o�
(+
-���%o
�(�
	,
	3(�*(�*(�*]k0
+o,
o-
%
-�*0^/

-+85o�
r�	p(�
,	X
8r�	p(�
,%Y
X<�X<�
8�(�
:�r�	po�
:�(�,,@�
	(�9�	(�8�9�X3:	(�

,
.+j		(�+]		(�		(�+EX3>r�p(�
,,o}+r/	p(�
,,
o}o,
o-
%:����*010(�s.

89�o:
9�o�
';�(�E	2=ai���z8�X@�
(�9�	(�
+vY-o
+k,	(�	(�+O+G+?,;	(�
+.,(�o}
+,(�o}
o,
o-
%
:��*6(�o(
*0fr�	po!

/Q*r�	p(:
X
~�o/
/o�
Q+Yo;
QPr�	po�
,
Po�
Q*0N1(�o)

o0
+ o1
o�3(�o}
�o
-��
,o
�*	*,@
0�2Qo�
[3*(o�

)o�
=o�
3,2(1$o;
o�
 o�
Xo�
Q*~�o/
2*
 o�
Xo�
Q	*0f1(�o)

o0
+8o1
o�(�
,#o�.
o�	3(�o}
�o
-��
,o
�*	*DX
0l3(�o)

o0
+>o1
o�(�
,)o�.o�.o�.
o�3
�o
-��
,o
�*	*J^
0l3(�o)

o0
+>o1
o�(�
,)o�.o�.o�.
o�
3
�o
-��
,o
�*	*J^
0�4Q

~�o2
2*(�o3
0r�	p(�9x
o4
8jo5
E	9�9�9
9"84r�	p(�
,
o6
&8r�	p(�,
o4
8�r
p(�,
8�r5
p(�-rG
p(�,
o4
8�rO
p(�9�
o4
8�ra
p(�
,
o6
&8�rG	p(�,
o4
+lr	p(�,_
o4
+Tr{
p(�
-
r�
p(�
,:
o6
&+/r�
p(�
,"
o6
&+r�
p(�
,
	
o6
&*�	 o7
o�
+r�
pr�	po�
r�
po8
/�*:(���*0H5o!

/*o:
X,Y($
, o:
.o�
%(.(9
,**0�(�
/*o:
X
o:
/	($
-*X
o:
2*~�o/
/o:
Yo;
o�
QPrepo�
,"Pripo:
,PPo:
Yo;
Q*{�*"}�*j{�-s;
}�{�*0V�% �%:����%=�%;����% �%(����%�(<
��*>(X}�*{�*0,6 P
(�(�,
(�(�,
*2r�
p(�*2r�
p(�*2r�
p(�*2rp(�*� . 0. `3****0/7
o=
rp(Jo>
,o?
oI
(�
*0/8 `
o=
(Jo>
,o?
oI
(�
*0Ar/p(�
-rO	p(�
-rs	p(�
-+ * P* 0* `*� . 0. P.+r/p*rO	p*rs	p*r�	p*>(�(��*zr/p(�
-
rs	p(�
,**�(X}�-~W
+}�*0:9(]o'
s@
{�(A
(B
(=
(C
(�(MoD
(K(�oE
oF
&(]o30(`rAp�%(H
�/oI
�oA
+(`rAp�oA
(�o�
	o�
&(G
sH
(]o!o!
+?o
(�,*(�		o

o
1
oI

oJ
o
-��,o
�*�L-2(]o*0vo_
3'u<oo
o_

�6oI
(�*o_
.o_
.	o_
3'uko�
o_

�6oI
(�**�oK
-
oL
+"(]oM
(� �o**0B:o5

~�+)�
	{N
oO
,	{P
(]o&*X�i2�*0��,%�t(�
~�,s%sQ
�%�d(�
~�-s%sQ
�%�<(�
~�.s%sQ
�%�Q(�
~�/s%sQ
���**(�*"(�*0T;(�oR
(�
o�
o�
&(�oR
o�
. (�oR
(�
o�
o�
&*0
k<(�
(�s�(]o.s�
,(`oE(]o*o=+*(]o*(]o�o<(`oD(`oF(�o�
(H(�o�
o�
9�%o�
r�p(<
o�
(�o`
o�
(]o,(�,M(](�o�
(�o`
o�
o�
(� �(�o`
oh
o�
oo�,o�o�
-o�o�
+o�
o�
(�
%oS
(�(�`o�
oS
 �_(]o)o�
(�(�(�(�(]o)o�
(�(�(�(�o�
;Xo�,Eo�
1;oT
o�
o�
�'	(](�o�
(| �	o�sU
o�.
sV
9�	sW


r�poX

oY
(](�o%o�
&
(_o3(\sV
r�ps�
oZ
o`
oh
oT
(Z�n%
�U%s�
�%o�
s�
�%�s
s[
�s
o
&8�	rps�
oT
s
o
&8�	sU

sW
r%poX
oY
(](�o%o�
&(_o3(\sV
r�ps�
oZ
o`
oh
oT

(Z�n%�U%s�
�%o�
s�
�%
�s
s[
�s
o
&o�,Eo�
1;o�
o�
o�
�'(](�o�
({ �o�o�
s
o
&*'\/'\0O=oa
od

+$(e
o`
3o�
og
,�(j
-���o
�**1=r(�o`
oh
rqp(J
*2(uu*0F(](�o%
,(_r]po&
+o�
3(_r}po&
*0>o�
o�
t�o�

*0�?sW

o�
.
r�poX
+r�poX
oY
(](�o%o�
&(_o3(\sV
r�ps�
oZ
o`
oh
�U%s�
�%o�
s�
�s
*01@(�(�
(�(�(�o�
o�
*0�A(�
(�(�s�(]o.o�(�o�(�-*o�(�o�(�o�(�o�
o�
&o�(�o�(�*0*Bs�

(]o*o=(�(�o�
�#(�
s�
o�
 `o�
o�
r�ps�
o�
&o�
o�
&s�
(]o*o=(�(�o�
�#(�
s�
o�
 `o�
o�
o�
&(]o)(�rqp(�(�(J
	s|o�
(]o)(�rqp(�(�(J
	s|o�
*0�C(�s\

(]o*o= Po�
(�(�,(�(�o]
o�
o�
&(�o�
o�
(�,J(_�(�
o(�s\
(]o*o= Po�
o�
o�
&*Z�.(�
os�
*0(�(�
*2(ue*2(�o�
*R(]o*o>*0�Do�

,bo�
1Ys^
o�
o�
,o
1o_
o`
o_
�%
(](�o�
({ �	o�oS
 �_(]o)(�(�(�(�(�*4G%\0	8E(�o�
o�
(�9�(�o�
(�:�(�(\r�p�U%(�sa
�%(�s�
�%(�o�
�s�
�%(��s
s
o
&(��s�
s
o
&(�s
o
&*(�o�
o�
uq
,Hob
�-(�
(c
,1(_(�r�p�U%(��s
s
o
&*(�s
o
&*0@FoT

oS
 �_(]o)(�(�(�(�(�*0�G(\(�(��U%sU
�s
o�
&(\r
p�U%(�s�
�s
o�
&,<o�
13o�
o�
�%
(](�o�
(| �o�(�o�
o�
(�,
(�8�(�o�
o�
(�,
(�8�(�o�
o�
(�,X(�o�
o�
t�o�
o�
(�,(�o�
(�(�+G(�o�
(�(�+.(�o�
o�
(�,(�sU
s
o
&(\rG
p�U%(�s�
�s
o�
&(\(�(��Us
o�
&*ao%\0� P3( P. ,s|o�
+
s|o�
 3( . ,s|o�
+
s|o�
 `3( `. ,s|o�
+
s|o�
 03) 0.!,
s|o�
*s|o�
*0�HsU

-y(�o�
o�
tqs

o
ob
od
,(�o�
�s�
o
(�(_(�rs
po
s
s
o
&*(�s
o
&*0.I�.(�

(_os�
�.(e
s�
*0}JsU

-`(�(\rs
p�U%(��%�%(�s�
�s
s
o
&(��s�
s
o
&*(�s
o
&*00K(�o`
of
uk
,oa
(�og
,**0�L�Vo�
o�
(�,(_tq(08�(�,(_td(](4+o(�
,gt�o�
o�
(�,%(_o�
tqo�
(�(1+)(_o�
tdo�
(�(](2(�
&o�
,(8*(7*0#Moh
r�
poi
,oj
��**Fr�
pr�
p(J
*Fr�
pr�
p(J
*�{�-(\(�s�
}�{�*�{�-(\(�s�
}�{�*2(�(A*2(�(B*0-N(�o`
ut
,o
(�o�
og
***ok
�*0�Ook
9�o�
o�
(H9�o�
-o5
(l
o�
,*E,	4#+2s�
*(�*(�*(�*(�*(�***0@Pt-
�i�U+��2s�
�X�i2�(_o,sm
*07Q�/
(_o/�U%r�
p(�
(n
s�
�s
*0DR��
(o
(_o-�U%(p
�5s�
�%(	+�s
*0	gS��
(_o.�U%(q
�5s�
�%(_o5�U%(r
(s
�5s�
�s
�s
*02T��
(_o5�U%(s
�5s�
�s
*
*�(�o`
oh
rqp(�o�
(J
*(�*F(�o`
o�
*0e;s�

(�o�
(�o�
(Ho�
-%oS
`o�
-o�
(,%oS
`o�
o�
*0�(�o�
o�
(�
,<(�o�
(�,*-&(�o�
(�o`
o�
(u(�z*-,>,	o�
,,/o�
-&(�o�
(�o`
o�
(t(�z*B(�}�*b((](o*0�((� 3Y((� 03G(](o�
r/prs	p(� �(o`
oh
(o�
o*((� 03X((� 3F(](o�
rs	pr/p(� �(o`
oh
(o�
o*:o�o*0SK{�, (o`
(]o,(K,*(o`
of
uk
,oa
og
,**2(�u8*&(�*N(]o*o9*J(](
o*0BG,7o�
1.o�
o�
o�
�
(](w �o�o*\0]U,Yot

+(u
o�
s�
o�
&(v
-���1o
��(](y �o�*
'1>A\0;G,7ow
1.o�
ox
oy
�
(](x �o�*\2(�u5*�%oz
�_o{
%oz
(
(�`o{
*0�Vo�o
(s�(]o-(o�
s�
o�
o{
(o|
,%oz
 �`o{
((o�
o(
o((o�
o((o�
(Hoz
 �_-oo(o�
o(s�

	o�
&	*�(of
-*(](of
o%*B}�(*j(]o*o8(*0OW(o
+o}

+"(~
(]{�s�o(
-���4o
�*/@0�Xo
o�
s�
o}
+(~
		(

,	o�
(
-���4o
�o�
/*s�
(]o*o=(_(o�
o
(]o+~%-&~�;s	
%�s�(o�
o� `o�
r�
p(o�
(<
o�
(o�
(]o,(�,2(]o�
(o�
(� �(oh
o	o�
(o�
(�o�
(J		�Us
s�
o�
o
&s
o�
8�(�
(](s�

o�
o�o�s�
o�
s�
o�
o�
&
o�(�o�
(L
o�o�
o�
(�,Cs

o

o�s�
o
(_(�r�
po
s
+o�

o�s�
s
o
&(�
:������7o
�o�
s
o
&o�
o�
&*A4,G�
�2(
uk*{�*0Mo�
,*(�,*(� `.
(� `3(o`
.(� P3**�,o�
-}�o�
o�
&*,
o�
o�
&*0g(4
�s�
s�
}�� s�
s�
}��*s�
s�
}��(s�
s�
}�*6{�o�
*0
s�

*0s�

o�
o�
&*&(*N{�s�
o�
*0&Y(�

(�
,
s�
+s�
*:(D(*:(E(*:(F(*:(G(*:r!p('*:r{p('*z{�rqp(J
s�
o�
*0-Z(�

(�
s�
( o�
o�
&*6{�o�
*0&��(�
s�

o�
(o�
&*6rIp(%*�~�-�-(�
(��~�*�~�-Ђ(�
(��~�*�~�-Ќ(�
(��~�*�~�-�/(�
(��~�*v~�-rcp(!��~�*2~�(*2~�(*2rp("*�~�-�(�
(��~�*�~�-Ѝ(�
(��~�*~�7(�
���8(�
��*0![(G
s�

|~�o�

+;	�(8,&o�
o�
-o�
�d(�
o�
X	�i2�~�o�
+j�(8,To�
o�
,.o�
o�
�d(�
(c
,'o�
o�
+o�
�t(�
o�
X�i2�s�
o�
	+	(�


o�
	(�
-��	�Bo
�*�0\u�,t�(9*u�,t�(;*u�,t�(=*ua,ta(:*tG(>*08\
o�
(�
,
(<`
o�
(�
,
(<`
*08\
o�
(�
,
(<`
o�
(�
,
(<`
*ro�
-o�
-
o�
�**�o�
-o�
-,
o�
�***"(<*0S](�
,*o:
3o�

(�
(�
o�
*o�

(�
(�
o�
o�
(<
*~(b
r�po�
,r�p*(?*6(C(<
*F(A~�(<
*"~��*2r�p(<
*2r�p(<
*2r#p(<
*2rWp(<
*r(�-T*tqo�
T*�o:
1#o�
.3o�
�%.�o�
*�%.�o�
*2r�p(<
*0'I
(L-*(c
,*o5
(c
*0R^Q~�o�

+%(�
(�
og
,
(�
Q�(�
-���Co
�**2@0@��%r�p�%rp�%rp�%r5p���r=p��(7��*.rUp(
*.r�p(
*fr�p�%�%�(	*Vr!p�%�(	*vrIp�%�%�%�(	*Vr{p�%�(	*Vr�p�%�(	*Vrp�%�(	*vr_p�%�%�%�(	*fr�p�%�%�(	*fr�p�%�%�(	*�r	p�%�%�%�%�(	*vrSp�%�%�%�(	*fr�p�%�%�(	*�r�p�%�%�%�%�(	*Vr?p�%�(	*vrsp�%�%�%�(	*Vr�p�%�(	*Vr�p�%�(	*Vrp�%�(	*�r9p�%�%�%�%�%�%�(	*vrop�%�%�%�(	*.r�p(
*Vr�p�%�(	*fr+p�%�%�(	*fr�p�%�%�(	*Vr�p�%�(	*frp�%�%�(	*VrWp�%�(	*.r�p(
*Vr�p�%�(	*Vrp�%�(	*VrGp�%�(	*fr�p�%�%�(	*�r�p�%�%�%�%�(	*Vrp�%�(	*vrsp�%�%�%�(	*Vr�p�%�(	*fr�p�%�%�(	*frp�%�%�(	*.rKp(
*Vr�p�%�(	*Vr�p�%�(	*Vrp�%�(	*VrEp�%�(	*Vr�p�%�(	*Vr�p�%�(	*Vr)p�%�(	*Vrip�%�(	*fr�p�%�%�(	*fr�p�%�%�(	*vr
p�%�%�%�(	*.r3p(
*Vr�p�%�(	*Vr�p�%�(	*Vrp�%�(	*.rIp(
*frp�%�%�(	*Vr�p�%�(	*Vr�p�%�(	*Vrp�%�(	*fr7p�%�%�(	*vrgp�%�%�%�(	*vr�p�%�%�%�(	*�r p�%�%�%�%�(	*frQ p�%�%�(	*.r� p(
*.r� p(
*fr;!p�%�%�(	*.r�!p(
*.r�!p(
*.r�!p(
*Vr"p�%�(	*fr3"p�%�%�(	*fry"p�%�%�(	*Vr�"p�%�(	*Vr#p�%�(	*vrI#p�%�%�%�(	*fr�#p�%�%�(	*Vr�#p�%�(	*fr+$p�%�%�(	*fr$p�%�%�(	*Vr�$p�%�(	*Vr%p�%�(	*.rQ%p(
*Vr�%p�%�(	*.r�%p(
*.r&p(
*.rc&p(
*fr�&p�%�%�(	*Vr�&p�%�(	*Vr3'p�%�(	*.ro'p(
*.r�'p(
*.r�'p(
*.r(p(
*.rW(p(
*.r�(p(
*.r�(p(
*.r
)p(
*.rE)p(
*.r)p(
*.r�)p(
*.r*p(
*.rG*p(
*.ry*p(
*.r�*p(
*.r�*p(
*.r5+p(
*.ry+p(
*.r�+p(
*Vr�+p�%�(	*.r�+p(
*fr3,p�%�%�(	*Vri,p�%�(	*fr�,p�%�%�(	*s�
*s�
*s�
*s�
*Js�
}�(4
*�r-p(�r3-p(+&{�oL
*6{�oK
*2{�o�
*6{�o�
*:{�o�
*6{�oM
*:{�o�
*2{�o�
*2{�o�
*{�*0)_{�
(�
t|�(+
3�*0)_{�
(�
t|�(+
3�*0)`{�
(�
t|�(
+
3�*0)`{�
(�
t|�(
+
3�*Js�}�(4
*�s�}�(4
rS-p(�}�*{�*Jr�p(�}�*{�*�rq-p(+&r�-p(+&��(�*0�arq-p(+&r�-p(+&r�-p(+&s�

s�
s�
o�

o�
+do�
-r�-p	�=(�(�zs�
o�
�)(�,o�
 �s
o�
+��	X
o
-��,o
�(�s�(��&�*(n�)EHq�*��#>��(�*0[br�-p(�r!.p(+&r[.p(�s�

s�
rq.p(�
� (�o�
�o�
,(vr}.ps�
zs�

	o�
o(
+jo'
-r!.p�=(�(�zrq.p(�
			o�
�%

(�, �
(�o�
+��Xo
-��,o
�(�s�	(��,o
��(�o�
��&�**A�.>���%E�w-&;4(+S#0�cs�

s�
o�

	o�
(�
(�
		o�
�,	(��(�o�
	o�
o�
s�
o�
(	~1(�
,(�(�zso*!6Jo�
s�
*Jo�
s�
*09do�

+(�
o�
,s�z(�
-���o
�*#*Z{�,
{�o�*Z{�,
{�o�*V(4
}�}�*V(4
}�}�*�{�-{�s�
}�{�*{�**{��*�(�
{�,{�,{�o�
*�s�
}�s�
}�s�
}�(�
*�s�
}�s�
}�s�
}�(�
}�}�}�*{�*{�*{�*"}�*{�*{�*{�*(�
*�s�
}�s�
}�s�
}�(�
*�s�
}�s�
}�s�
}�(�
}�}�*{�*{�*"}�*{�*{�*{�*0es�

(�
o�
�,o
�~�o�
o�
~�{(�
,~�+"o�
o�
~�{(�
,~�o�
s�
r�.p{o�
r�.p{o�
r�.p{o�
r�.p{o�
r�.po�
t�Qr;/po�
t�Qr�/po�
t�Q~W
Qr
0po�

	9	o�
8�o 
t�o�
o�
8�o 
t�o�
r)pog
,ro�
r�0pog
,^o�
o�
	+.	o 
t�

o�
rpog
,
o�
Q� 	o
-��	uL,o
�o
:`����uL,o
�o
:����uL,o
�*4
�;�=���0Mfs�

(�
o�
o�
s�
o�
o�
&
(�

	o�
�
	,	o�
�*1B
0�g�Xr�0p}rX1p}r�1p}r2p}���Xr�2p}r�2p}r63p}r�3p}���Xr4p}r^4p}r�4p}r 5p}��r�5p��**s
*0H#�?.#3~�*#�������?3(*#@3~�*~�*�s
��s
��s
��*F(4
(*�(4
r�5p(+&r�5p(+&(*0}h(4
r�5p(+&r�5p(+&r�5p(+&o+(+
�i.r�5p(�z�o+~$%-&~#�@s
%�$(+(*0�ir6p(+&(�-oo
r6p(�z,"r�5p(�(9
(X
,(�z,Cr�5p(�(;(X
,(�zoo
(�
,oo
(�z}�-+(+}�}}s�}(%*{�*{*2{o�*6s�}*{*"}*J~4}(*fr06p(�}(*0:jrj6p(�(&s�

o�
(
(�
,o
�*&	/
jr�6p(+&(&(*0:jrj6p(�(&s�

o�
(
(�
,o
�*&	/
jr�6p(+&(&(*0\k{�,}�}�}s=
��s
}(,1{~1(
,(� �o<{��s
(${s
{�ok
ol
8�(m
o_
.
.?+\(-t�o
	(�-t�o	
+=	 �o<+,t>
{!

so

+
o_
(�z(p
:l�����o
�o
+(
(#(

-���No
�s

(!o

+A
o
{!oo
&o('o
	o
o

o
-��
,
o
�	o
+'o
("-(,o
o
-��,o
�{"{�{!o
o
{"{�o
+(
(+o
(
-���Uo
�{~1(�
,:r�6p(
(
�s
s
%o
o 
}({(�:-{"{�o!
o"
+(#
o$
{o%
(&
-���Yo
�{"{�o'
o(
+()
o$
{o%
(*
-���\o
�{"{�o
+1(
o	o
o$
{o	o
o%
(
-���Uo
�o$
{o%
}�{"}�{}�*(�,(� so<+��{**A���4Ji�N��4%^)�*:_*��>�#(*E0_l{,8r-7prC7p(+
{{{�]%�](�*{{{�](�*0&m{�{�{�{s�
o�*0
,n{�,{��,{~2(
,*{�~&%-&~#�As
%�&(+
o,
8�o-
sG
	},(.
9�o�
{(8	s�}+o
	�Hs/
(+(+o
~'%-&~#�Cs1
%�'(+~(%-&~#�Ds1
%�((+(+(+,o]
(� �o<8�( o$
{o%
o4
		o$
	(5

{��}6
{}7
�p%r�7p
s8
�}9
}:
};
s<
}=
s<
}>
s?
o$
o@
{"{�(+oB
o
:<����
,o
�*AV�!
0*oo
(8
o�
oC
o
s8
*0�psD

s�r�7p(<
{(8o�oE
o}
+(~
()oF
(
-���4o
�{sG

oH
+(I
	oJ
(K
-���eo
�	*9*c��03qsL

sM
{!o
oN
+&(O

	o-		oP
+
	o	o

(Q
-���ho
�o
oN
8�(O
o
o
+s(
oR
oS
oT
oR
oS
oT
	oU
,8	oU
,.{!oV

{!	oV

oP
oP
(

-���No
�(Q
:O�����ho
�*(3P��k�#0JroR
oW

+(X
{!oT
oU
,�(Y
-���ko
�**,80QsoR
oW

+)(X
{!oT
oZ
,o
o	
(Y
-���ko
�*6B0�t{�ok
ol

+t(m
o_
3ct�(�o[
o}

+0(~
{ o\
-{ t�o
o]
(
-���4o
�(p
-���o
�*<=y��05u{,	{,*
{�ok
ol
+(m
o^
o�

�(p
-���o
�(�
,r�7p
{-Fr�7po!

	1	o;
r�7p(<
(9}+r�7p(<
(9}{-{.o�
1 o;
r8p(<
(;}+r8p(<
(;}{r�7po!
1o;
r8p(<
(;}*$#G>{�-(�z*0Kvo�
((
{o�
o�{(8s_
{"{�o`
*0w{"{�oa
,*sD
sb
s�
{o�
o�{(8	o�o
o}
+b(~
o
o�
oc
		-(-{ 
od
-%	()oF
	,
o�
oe
(
-���4o
�{sf
{"{�og
*^o�0Cxo�
(8
o�
oC
sh
o�
(*{"{�oi
*0[yoh
r8poj
,Hs

rG8p(
(
oh
r8pok
oj
s
o
o 
}*0�zoo�
{(8
{sl
oo�
{(8sm

s�+soon
(7		oJ
{"{�oT
oo


		sp
	oq
{"{�or
Xo
os
?{���(3	o
	*0�{{"{�o
ot
-%o
(.
{"{�o
ou
o�
{(8sm
oR
oW

+1(X
(-{"{�or
oq
(Y
-���ko
�{"{�ov
*f>�0@|{"{�on
ow

{"{�oT
oo
o�
sp

	*0�}s�
o�
{(8{~0(x
,(-(1+{sl

	(/oy
oz
+8({
tS(6{"{�o|
	oJ
(}
-���to
�(0,	o~
	(3	*gE�0�~o
o�
-
�v*o
o�

(,-o[
~)%-&~#�Es�
%�)( +++o[
~*%-&~#�Fs�
%�*(!+o�
o�
-o�
o�
�+_,o�
o�
s�
*�v*0�o
o�
-*o
o�

o[
o�
o`
tt(-(2-*o�
o�
�e
�e{"{�o�
tSow
{"{�o�
tSow
+I	{"{�o�
o�
o�
�{"{�o[
o�
o�
�X2�	s�
*0;�o
o�
-*o
o�

o[
o�
o`
tt(2*bo
o[
o�
o�
*07oa
o�
tS
oa
o�
tS(4(4*0x�o�
o�
t�o�
tt
s�(5{o�
o�(8o�
s�

	o`
tQo�
	o�
	o�
	oJ
*0H�o�
o�oa
od

+(e
o�
o�(j
-���o
�*!90>�o�

(�
,(�
o�
(�
,(�

o�
(7*0T�o�
o�
t�o�
tt
{"{�o�
o�
(8o�
s�

	o�
	*0
(;
o�
*&C(:*0��sb

�%.�o�

+	�(<oe
	X
	�i2�r	p+o�
rqp(J
Xo�
Y2�o�
Yo�
(<
*&C(<*0Q�o�

+�(�
-_�X�i2�s�
(�
-o�
(�
-(�
(<
*�(4
-r�8p(�z}
}}}
}*2(=*{
*{*{*{
*{*0�r�8p�r09p�r�9p�r�9p�r:p�r@:p�rr:p�r�:p�r�:p�r�:p�r�:p�r
;p� .�!*b(4
rS-p(�}"*"(E*{"*Jr�p(�}"*0O�sI
}-r ;p("+&{-rD;p(��Js�
(M�
,o�
�*+C
0*�r ;p("+&(T(K(#+($+*0R�sK
}.r ;p("+&{.rZ;p(+&r06p(�(L�Ls�
(M*0L�o�
(	
(
,(�(�zo�
o�
(	(
,(�(�z*0)�(Q,Q*o�
QP(U*0(�r ;p("+&(T(O(#+($+*0��r06p(�(Lr ;p("+&(So%+o�
+~o�

	o�
o�
o�
+J(�
	o�
,o�
,,tJo�
+o]
(s 7s
o�
(�
-���o
�o
:w����
,o
�(P*OW�4��
03�~0%-&~/�Os�
%�0(&+
('+($+*�(RPo�
-Po�
1**0-�Q{"
,.+s@
Q+sA
Q(S**o�
Q*0E�s�

o�
o�
(	QP~3(x
,~3P(� �s
o�
*0��o�

o�
s~
~s@

oE
	oF
&o%+o�
8o�
(V,#o]
(q 's
o�
8�o�
oo
o�
oo
o�
(�
s�
	~o�
(�
	oI
(�
o�
(<

~rqp
(J
s�
~s�
s�

o�

o�
&o�
o�
&
(c(b `o�
s�
o�
(W(�
~s�
s�
s
~s�
s�
s
~s�
s�
s
~s�
s�
s
~s�
o�
�=s�
s
o�
o
&o�
o
&o�
o
&o�
o
&o�
o
&o�
o�
&(Y	oI
o�
&o
:���,o
�	oI
o
1(XoT
*A9X0J�o�
ok
ol

+(m
o�
o�
,�(p
-���o
�**'80K�s�

o�
+!(�
(�
(a(�
oL
(�
-���~o
�*
.;0)�sO

rmpoP
oQ
oR
oS
*0��s�

~o�
Г(�
�G%�(�
�%�(�
�o�
s�
o�
�=(�
s�
rt;ps�
o�
o�
&o�
~s�
o�
&o�
(�s�
o�
&o�
~ s�
o�
& 0o�
o�
o�
&o�
o�
o�
s

o�
8�(�
	�=s�
s�
�ns
o�
o
&(�
(a(�
(Z	o�
	o�
&	o�
s�
�Us
s

o�

o
&X(�
:[�����~o
�o�
�O(�
s�
�Us
s�
o
&*���0U�s�

r�;p(�
(�
(<
o�
 Po�
Г(�
�G%�(�
�%�(�
�o�
s�
o�
o�
~s�
o�
&o�
(�s�
o�
&o�
~ s�
o�
&o:
~#1ao�
o:
([(`o*

+	o)
o�
o�
&	o
-��
	,	o
�(^r�;p�Us
+s�
o�
�U%s�
�%�s
o�
s
o
&*�"�
0I�н(�
r�;ps�

н(�
�U%�=s�
�s�
o�
o
&*>�sP%}5*>�sX%};*.r�;ps
*nr�;p�U%s�
�s
*�o:
~#1(\((+(]*��%�(]*0$]o�
oo
~!
(�
o�
(J
*0X�s�

 `o�
o�
~s�
o�
&o�
(�s�
o�
&o�
~ s�
o�
&*0i�s�

 o{
o�
~o�
o�
~s�
o�
&o�
(�s�
o�
&o�
~ s�
o�
&*r ��#P�$ (�%*0�
~�(�
,#@o�
*~�(�
,#@o�
*~�(�
,#�?o�
*((�
,#�������?o�
*o�

(�
(�
o�
*0�
s�
*0Q�r06p(�(f
P~?%-&~>�bs�
%�?()+-o�
(	P(h&*�(�
-(� �s
o�
**&s�
*Nr06p(�(i*.s�
*0��r�;p(*+&r�;p(+&r<p(+&r06p(�o�
(	(x
,r�;p(�z(k
P~@%-&~>�cs�
%�@()+-o�
(	P(h&*(*0e�r<p(�
YE+(r
+(p
+(o
+r@<p(�z�$(�
o6
o�
*0$�s�

(q(�
(to�
{�
*0$�s�

(q(�
(uo�
{�
*0Co�
3o�
3
#�������?*#�?*o�
3
#@*#@*0$�s�

(q(�
(vo�
{�
*~..	+(v*(t*(u*�~0(�
,r2p*~1(�
,r�3p*r 5p*�~0(�
,r�1p*~1(�
,r63p*r�4p*�~0(�
,rX1p*~1(�
,r�2p*r^4p*2~5(++*0No�
-o�
.o�
,	o�
3�o�
-o�
rT<p(�
,
o�
(y*Q*0Ir�0p(�
-r�2p(�
-r4p(�
-+~0Q*~1Q*~2Q*Q*0V~��0~��1~��2~1�3~2�4��%~0�%~1�%~2��5*0O~W
}9(4
r^<p(�r�p(+&r�5p(�}<}8s�}7*{:*{;*{@*"}@*0�s�

~4(�*fr�<p(,+&~4(�*�r�<p(,+&r06p(�(�*0	��{:,}:};}=}>}?sd
{7o�{7o�{7o�(�
(�

	o�
}9	{9o�
}G	{9o�
{9s�
}N(�(�{<rqp~W
o�
r�<p(<
s
ojo�
+9o�
{No%
(�	{H	o�
	o
o
-��,o
�(�{Eo�

+*
(�
{No%
(�o

(�
-��
��o
�o$
{No%
(�{?~2(�
,{7o�~2(�
,(�(�{Oo�

+
(�
{No%

(�
-��
��o
�oe(�-1}:{N};{M}={Ls�
}>�E(�,*(��'% ss�
�oq+��{7o��oes�
*A|�F-M7��#22d9E2k�0:jrj6p(�(�s�

o�
(
(��
,o
�*&	/
0blr�6p(+&(�r�<pr�<p(+
(}{<{={>{8{9{?�]%�](�*6~1(�*0q�r^<p(+&r�p(+&r06p(�(�

�(n(�z(�o�
-(j(�zo�
(�
	s�
*#	,�0��
~2(�
,~�

~�
~�
+~�

~�
~�
s�
o�
o�
o�
o5
o�
(o
s

oe
��%�o
	s�
	(�o
	(

��(�
o�
	(o
s



oe
��%�
o
	s�
	(�o
o�
o5
o�
~�
(o
s

oe
��%�	s�
	(�o
(��9&�(�,
(k(�z�,o
,o
,o
�*AL>4r�>4uE>Q�0"�o-+
o
ok
o
o
&*�o�
,(�-(k(�(
(�z*>{:-(�z*05�o,

+o+
o�
3�o
-��
,o
�** '
0q�o�
sm

oy
oz
+5({
tSoh
	o�
ol	sp
oq
(}
-���to
�o$
*B[0|�ol
(w(xo�
(X
,(xo�
s_

r�<prK=p(y(�(	
s
o
	o 
	o$
	*B3rU=p*rc=p*0~�{7{Go�
�es

+6o
	(u,(}-(�o
	oo
o-�o

,	(��
,o
�*as
0��o
o�
s�

o
,ho

(�,r�7ps8
8	
-oo
(X+oo
([ us
o�
8�o9�{?~2(
,*on,4{Lo
-%o4


o$
r�7p
(5
s8
+f,D{Mo
,3	o�
{Mo
&{Lo
,{Lo
&	�e(U �s
o�
s�s
8o
oo-o(�,yo-=ro=po-o	oo(^ |s
o�
op(<o�s8
o
+dro=po-o	-oo�=(Y+oo�=(\ us
o�
Xo

/o9���of(<{Fo�,�p%�+�p{<��o}
o(X
-+o}
os<
}
os<
}
os<
}
os<
}=
}9
o
}:
s?
		o$
		or,{O	o
*{L	o
&*0�oo,(
(
**0��~W

s
{7{Go�o 
+>o!
t>
	oK(X
,(�
-(�o"

	o#
o
-��
,o
�(�
-(�*#Jm
0��o$

(�-*~a%-&~`��s%
%�a(�-'�'%oI(] �s
�oq*s�
{?~0(�
,(�+	(�-+oM,	(�-+~b%-&~`��s%
%�b(�,	(�	{FoIo�

{<sl
oJ
	oJ
s�
	(�
(~:((�, �s
o�


9�{E~d%-&~`��s&
%�d(.+o(
8�o)
o
~e%-&~`��s*
%�e(/+o(
+Uo)
o`
o`
o�
,7o�
,,o�
o`
(r �s
o�

�o
-��,o
�
-�o
:E����,o
�
,{Eo+
+*{Lo
&{Io,
&{I	o,
&o$
or*�bP��p0v�o6
o#o-
o$o-
o%o-
(so'o-
o(o-
o)o-
(sok
	ok_
	*0[�o
o
o.
.*o/

+ (0
o
o1
og
-�(2
-����o
�**-I0T�o/

+.(0
o
oEo3
,o�
,
�
�(2
-����o
�*	*;B0T�o/

+.(0
o
oEo3
,o�
-
�
�(2
-����o
�*	*;B05�o�
o�
o�
s�
o�
{Io4
*05�o.
�e
o.
�e{Io5
{Io5

8�o
o$
o=o3
-Co�
	o�
o�
rqpo$
o=(J
(c ws
o�
*�	o
o$
oEo3
-Co�
	o�
	o�
rqpo$
oE(J
(c ws
o�
*�Xo.
?���s�
o~
*0��o
o�

o[
o�
o`
tt
o[
o}
+)(~
o
o�
_	o
o�
`
(
-���4o
��	_,3o[
(�o
(�o�
o�
(pQ*r	pQ*56k�{7{Go���s6
(�*�{7{Go���s6
(�*�{7{Go���s6
(�*0���es7
sb
o 

+c	o!
t@o�(u,#o8
,o9
o:
o;

o<
o�,
ovoe
	o
-��
	,	o
�o8
,o9
*o�
0�s�
}ho=
o�-s�
{ho>
-go?
s
of|h(�,!�e(Q rs
o�
+�e(S }s
o�
(�{h-��		+{h	(0+((+{h9��:�{i%-&��s�
%}i(1+o(

8�s�
o)
}j{?{jo�
o�
(�-hs�
��sA
(2+(3+

o�
ov
oz(R �s
o�
��(��K
o
:Y����
,
o
��9�{h,-�i{ho>
/{h(+(4+}h+	}h+]�3'o=
o�(g �s
o�
+%o=
o�(f �s
o�
X�i2�{Fo=
oto�{<{hsf
o$
,.
+$oi+'oi{KoC
&+{Lo
&or*��0a�o=
o�
-s�
(�sD

	o$
	om	oE
o�
-
{L	o
&	or*0��sE

sb
QoF
8`oG
o�-ozoo-zo�-8-ozo�ov(V+ozo�ov(Z+ovo�(W us
o�
PovoH
8�	oI
~f%-&~`��sJ
%�f~g%-&~`��sK
%�g(5+ry=pry=poM
oN
ox�(O
oP
	o�
@Cr�=poQ
9o�:oN
oR
:�o�oN
oS
		(T
2+	(U
-)o�oN
oV
		(T
0+	(U
,x(yo�
r�=po��=oN
oS
��oN
oV
��ov
�e(b vs
o�
PovoH
8EoW
oN
o�Ҍ2(O
oP
r�=poQ
9�o�:}oN
oR
:lo�oN
oS
		(T
2+	(U
-)o�oN
oV
		(T
0+	(U
,x(yo�r�=po��=oN
oS
��oN
oV
��ov�e(b vs
o�
PovoH
8&oW
oN
o�Ҍ2(O
oP
8w	o�
.	o�

.
	o�
@$r�=poQ
9Do�:9oN
oR
:(o~oN
oS
		(T
2+	(U
-)o~oN
oV
		(T
0+	(U
,x(yo�
r�=po~�=oN
oS
��oN
oV
��ov
�e(b vs
o�
PovoH
8�oW
oN
o~Ҍ2(O
oP
83	o�
.	o�
:r�=poQ
9o�:oN
oR
:�o|oN
oS
		(T
2+	(U
-)o|oN
oV
		(T
0+	(U
,x(yo�r�=po|�=oN
oS
��oN
oV
��ov�e(b vs
o�
PovoH
8�oW
oN
o|�=(O
oP
o�-,o�,$~X
�W(O
oW
oY
+2o�-*o�,"~X
�W(O
oW
oY
ov	oZ
([
sh
o�
o
:�����
,o
�*Ar�
0q�
+Jo=
ox-8o=
ozoo, {?(�,o=
ovoe
X
o?
2�o�
1Q+QP�*0��{Ko\
>�(�
-*{Ko]
+x(^
{Ho_

ols
(w,r�<pr�=p(w(	
o
r�<pr)p(x(	
o
	o 
	(�(`
:|������o
�**��0��s�

s(~oo(�,*oo
{No
sa

	(b
oo�
�,o
�	joU
&	(c
sd
oe
o{Nsf
o
�,o
�	,	o
�*(Pa+�Hn�
0��(g
o�
(h

o�
oa
o
si
o�
oa
od
+1(e
teo�
oj
(k
sl
om
(j
-���o
�(n
(o
sp

{7o�oq
(�
	or
os
ot
ou
*:>x{A*"}A*:(4
(�*^(�-*(�o�*^(�-*(�o�*�(�,#o�
.
(�o�*(�o�**�s�}C(4
rS-p(�}B*{B*Jr�p(�}B*{C*0Kr06p(�r�-p(v
r!.p(+&r[.p(v
r06p(�s�(�*0N�(�~r%-&~q��s�
%�r(&+(6+,*(�(#+($+*�r�-p(v
r[.p(v
r06p(�s�(�*0M�(�~s%-&~q��s�
%�s(&+(6+,*(�(#+($+*0w�rq-p(+&r�-p(+&r06p(�(�-s�
%(�o�
*sx
rq.poy
(�s�(�
�
,o
�	*E&k
0M�(�~t%-&~q��s�
%�t(&+(6+,*(�(#+($+*0��rq-p(+&r�-p(+&r�-p(+&r06p(�(�-s�
%(�o�
*sx
rq.poy
(�sb

o�
+4o�
(z
rq.p(<
(�	oe
oL
o
-��,o
�s�	(��
,o
�*sA�R��
0N�(�~u%-&~q��s�
%�u(&+(6+,*(�(#+($+*0h�({
- s�
%(� �s�
o�
*(|

(�-s�
%(�o�
�(��
,o
�*/-\
0'�(}
,3
(	Q*(x,**0;�Q(|

(��$,o
�s�
% �(�o�
�*

10_�s�

(�-
(�o�
*P~1(
,~1QP~3(x
,~3P(� �s
o�
*0��s�

~0(�
,(� �s
o�

�r(h-
�`(m(�
,(�
�C{B(�o�o�{Co�o�o�o�o
,Js� �}xo�(7+��s
(8+o�
o�o�
,
ݷo�o�
�,o
�ݒ �(�o�
�| �(�o�
�f �(�o�
�P	 �	(�o�
�:
 �
(�o�
�$(�, �(�o�
+��*	*A��
�	0	%1	;2	Q3	g4	}$EF(� �s
*0��{Bs�
o�o�,(E
(z
(K
-(9++o�
o�,8	~v%-&~q��s�
%�v()+-o�(�
o�
	�,,({
,(�
�*s�0�(�

o�
�
,o
�*

0��o�
o�
-+
o�
(�
,o�
37o�
3.+*(�
r�=p�%o�
�%o�
�(>

,	o�
o�
o�
s�
*	s
*09I~F(c
,!s@
r�=pr?>p(�
F(:+&~F(�
*09I~G(c
,!s@
r�>pr?p(�
G(:+&~G(�
*09I~D(c
,!sA
ra?pr�?p(�
D(:+&~D(�
*09I~E(c
,!sA
r@prk@p(�
E(:+&~E(�
*0q�
(�
o�

	sV
o�

�,o
�	,	o
�s�
r�@po�
o�
o�
o�
��%�-(�
o6
o�
�%�(�
o6
o�
�%�d(�
o6
o�
�%�3(�
o6
o�
�%�e(�
o6
o�
�%Ш(�
o6
o�
�%�f(�
o6
o�
�o�
��%�o�
o�
o�
,>o�
(7+~W
~w%-&~q��s�
%�w(;+(�zo�
o�
*
 ,
{�
*"}�
*{�
*"}�
*v(4
s�
(�
s�
(�
*0D�(�
o�
o�

+(�
o�
(�
(�
-����o
�*#5J(�
o�
,**J(�
o�
,**0 �o�
,
(�
o�
*��*0 �o�
,
(�
o�
*��*�(�
o�
(�
o�
-
(�
o�
*(�
*"(�
*6o�
(�
*6o�
(�
*6o�
(�
*6o�
(�
*0���%r�@p�%r�@p�%rAp�%rAp�%rAp�%r%Ap�%r/Ap�}^K��%r7Ap�%rCAp�%rUAp�%rcAp�%roAp�%rAp�%r�Ap�%r�Ap�%r�Ap�%	r�Ap�%
r�Ap�%r�Ap�%rBp�%
r
Bp�%rBp�%r-Bp�%r=Bp�%rSBp�%reBp�%rwBp�%r�Bp�%r�Bp�%r�Bp�%r�Bp�%r�Bp�%r�Bp�%r�Bp�%r�Bp�%rCp�%rCp�%r%Cp�%r3Cp�% rCCp�%!rOCp�%"raCp�%#rkCp�%$ruCp�%%r�Cp�%&r�Cp�%'r�Cp�%(r�Cp�%)r�Cp�%*r�Cp�%+r�Cp�%,r�Cp�%-r�Cp�%.r�Cp�%/rDp�%0r
Dp�%1rDp�%2r%Dp�%3r�Dp�%4r�Dp�%5r�Dp�%6r�Dp�%7r�Dp�%8r�Dp�%9r�Dp�%:r�Dp�%;r�Dp�%<r�Dp�%=rEp�%>rEp�%?r)Ep�%@r;Ep�%ArOEp�%Br_Ep�%CriEp�%DrsEp�%Er�Ep�%Fr�Ep�%Gr�Ep�%Hr�Ep�%Ir�Ep�%Jr�Ep�}_s�
%r�Epr�EpoL
%r�Epr�EpoL
%r�Epr�EpoL
%r�EprFpoL
%rFprFpoL
%rFprFpoL
%rFprFpoL
}`sb
%r!Fpoe
%r%Fpoe
%r+Fpoe
%r3Fpoe
%r9Fpoe
%rAFpoe
%rKFpoe
%rQFpoe
%rWFpoe
%r]Fpoe
%reFpoe
%rmFpoe
%rwFpoe
%r�Fpoe
%r�Fpoe
%r�Fpoe
%r�Fpoe
%r�Fpoe
%r�Fpoe
%r�Fpoe
%r�Fpoe
%rGpoe
%rGpoe
%rGpoe
%rGpoe
%r)Gpoe
%r1Gpoe
%r;Gpoe
%rGGpoe
%rQGpoe
%r_Gpoe
%riGpoe
%rsGpoe
%rGpoe
%r�Gpoe
%r�Gpoe
%r�Gpoe
%r�Gpoe
%r�Gpoe
%r�Gpoe
%r�Gpoe
%r�Gpoe
%r�Gpoe
%r�Gpoe
%r	Hpoe
%rHpoe
%r/Hpoe
%rEHpoe
%rOHpoe
%rYHpoe
%riHpoe
%rwHpoe
%r�Hpoe
%r�Hpoe
%r�Hpoe
%r�Hpoe
%r�Hpoe
%r�Hpoe
%r�Hpoe
%r�Hpoe
%r�Hpoe
%r�Hpoe
%rIpoe
%rIpoe
%r+Ipoe
%r5Ipoe
%rGIpoe
}as�
%rSIprcIpoL
%ruIpr�IpoL
%r�Ipr�IpoL
%r�Ipr�IpoL
%r�Ipr�IpoL
%r�Ipr�IpoL
%rJprJpoL
%r+Jpr9JpoL
%rGJprWJpoL
%rkJprqJpoL
%r{Jpr�JpoL
%r�Jpr�JpoL
%r�Jpr�JpoL
%r�Jpr�JpoL
%rKprKpoL
%rKpr#KpoL
%r/Kpr7KpoL
%rCKprMKpoL
%rWKpraKpoL
%rmKpr{KpoL
%r�Kpr�KpoL
%r�Kpr�KpoL
%r�Kpr�KpoL
%r�Kpr�KpoL
%r�KprLpoL
%rLprLpoL
%r#Lpr1LpoL
%rALprOLpoL
%r_LpryLpoL
%r�Lpr�LpoL
%r�Lpr�LpoL
%r�Lpr�LpoL
%r�Lpr�LpoL
%rMprMpoL
%rMpr1MpoL
%rCMprOMpoL
%r[MproMpoL
%r�Mpr�MpoL
%r�Mpr�MpoL
%r�Mpr�MpoL
%r�Mpr�MpoL
%r�MprNpoL
%rNprNpoL
%r)Npr5NpoL
%rCNprONpoL
%r]NpriNpoL
%ryNpr�NpoL
%r�Npr�NpoL
%r�Npr�NpoL
%r�Npr�NpoL
}bs�
%r�Npr�NpoL
%rOprOpoL
%rOpr-OpoL
%rAOprMOpoL
%r]OpriOpoL
%ryOpr�OpoL
%r�Opr�OpoL
%r�Opr�OpoL
%r�Opr�OpoL
%rPprPpoL
%r1PprCPpoL
%rSPpriPpoL
%r}Ppr�PpoL
%r�Ppr�PpoL
%r�Ppr�PpoL
%r�PprQpoL
%rQprQpoL
%r'Qpr9QpoL
%rIQpr]QpoL
%roQpr�QpoL
%r�Qpr�QpoL
%r�Qpr�QpoL
%r�Qpr�QpoL
%rRprRpoL
%rRpr%RpoL
%r/RprARpoL
%rQRpraRpoL
%roRpr�RpoL
%r�Rpr�RpoL
}cs�
%r�Rpr�RpoL
%r�Rpr�RpoL
%rSpr+SpoL
%rASprYSpoL
%rsSpr�SpoL
%r�Spr�SpoL
%r�Spr�SpoL
%r�Spr�SpoL
%r�SprTpoL
%rTpr#TpoL
%r7TprGTpoL
%rYTpreTpoL
%rsTprTpoL
%r�Tpr�TpoL
%r�Tpr�TpoL
%r�Tpr�TpoL
%r�Tpr�TpoL
%r�Tpr�TpoL
%rUprUpoL
%r-Upr=UpoL
%rOUpr[UpoL
%riUprwUpoL
%r�Upr�UpoL
%r�Upr�UpoL
}ds�
%r�Upr�UpoL
%r�Upr�UpoL
%rVprVpoL
%rVpr/VpoL
%rEVprQVpoL
%raVproVpoL
%r�Vpr�VpoL
%r�Vpr�VpoL
%r�Vpr�VpoL
%r�Vpr�VpoL
%r	WprWpoL
%r%Wpr3WpoL
%rEWprWWpoL
%rmWpryWpoL
%r�Wpr�WpoL
%r�Wpr�WpoL
%r�Wpr�WpoL
%r�Wpr�WpoL
%r
XprXpoL
%r)Xpr5XpoL
%rEXprQXpoL
%raXprmXpoL
%r}Xpr�XpoL
%r�Xpr�XpoL
%r�Xpr�XpoL
%r�Xpr�XpoL
%r�XprYpoL
%r#Ypr3YpoL
%rEYprSYpoL
%rcYprqYpoL
%r�Ypr�YpoL
%r�Ypr�YpoL
%r�Ypr�YpoL
%r�Ypr�YpoL
%rZprZpoL
%rZpr)ZpoL
%r9ZprGZpoL
%rWZpriZpoL
%r}Zpr�ZpoL
%r�Zpr�ZpoL
%r�Zpr�ZpoL
%r�Zpr�ZpoL
%r�Zpr[poL
%r[pr'[poL
%rt;pr9[poL
%rI[prY[poL
%rm[prw[poL
%r�[pr�[poL
%r�[pr�[poL
%r�[pr�[poL
%r�[pr�[poL
%r	\pr\poL
%r!\pr5\poL
%rI\prU\poL
%ra\prm\poL
%ry\pr�\poL
%r�\pr�\poL
%r�\pr�\poL
%r�\pr�\poL
%r�\pr]poL
%r%]pr5]poL
%rC]prS]poL
%ra]prw]poL
%r�]pr�]poL
%r�]pr�]poL
%r�]pr�]poL
%r�]pr�]poL
%r^pr^poL
%r%^pr;^poL
%rO^pre^poL
%rQRpraRpoL
%ry^pr�^poL
%r�^pr�^poL
%r�^pr�^poL
%r�^pr�^poL
%r_pr_poL
%r_pr3_poL
%rE_prW_poL
%rg_pry_poL
%r�_pr�_poL
%r�_pr�_poL
%r�_pr�_poL
%r�_pr�_poL
%r�_pr`poL
%r'`pr5`poL
%rA`prM`poL
%rW`pre`poL
%rq`pr�`poL
%r�`pr�`poL
%r�`pr�`poL
%r�`pr�`poL
%r�`pr�`poL
%raprapoL
%rapr1apoL
%rCaprSapoL
%raaproapoL
%r{apr�apoL
%r�apr�apoL
%r�apr�apoL
%r�apr�apoL
%r�apr�apoL
%r�apr�apoL
%r�apr�apoL
%rbprbpoL
%rbprbpoL
%r%bpr%bpoL
%r3bpr3bpoL
%rAbprAbpoL
%rObpr]bpoL
%rmbprybpoL
%r�bpr�bpoL
%r�bpr�bpoL
%r�bpr�bpoL
%r�bpr�bpoL
%r�bpr	cpoL
}esb
%rAFpoe
%rmFpoe
%rGpoe
%rFpoe
%rFpoe
%r�Fpoe
%r�Epoe
}fs�
%r)Npr5NpoL
%rNprNpoL
%rcpr-cpoL
%rEcprWcpoL
%rkcpr}cpoL
%r�cpr�cpoL
%r�cpr�cpoL
%r�cpr�cpoL
%r�cprdpoL
%rGIprdpoL
%r#dpr/dpoL
%r=dprIdpoL
%rWdprcdpoL
%rKprKpoL
%rqdpr�dpoL
%r�dpr�dpoL
%r�dpr�dpoL
%r�dprepoL
%repr'epoL
%r;eprKepoL
%r]eprmepoL
%repr�epoL
%r�epr�epoL
%r�epr�epoL
%r�epr�epoL
%r�epr	fpoL
%rfpr'fpoL
%r7fprCfpoL
%rQfpr]fpoL
%rkfprwfpoL
%r�fpr�fpoL
%r�fpr�fpoL
%r�fpr�fpoL
%r�fpr�fpoL
%r�fpr�fpoL
%r�fpr	gpoL
%rgpr3gpoL
%rSgprogpoL
%r�gpr�gpoL
%r�gpr�gpoL
%r�gprhpoL
%r/hprGhpoL
%rahpryhpoL
%r�hpr�hpoL
%r�hpr�hpoL
%r�hpripoL
%r)iprAipoL
%r[iprsipoL
%r�ipr�ipoL
%r�ipr�ipoL
%r�iprjpoL
%rjpr1jpoL
%rIjpr_jpoL
%rwjpr�jpoL
%r�jpr�jpoL
%r�jpr�jpoL
%rkprkpoL
%r/kprEkpoL
%r]kprskpoL
%r�kpr�kpoL
%r�kpr�kpoL
%r�kpr�kpoL
%rlpr+lpoL
%rClprYlpoL
%rqlpr�lpoL
%r�lpr�lpoL
%r�lpr�lpoL
%r�lprmpoL
%rmpr1mpoL
%rGmpr[mpoL
%rqmpr�mpoL
%r�mpr�mpoL
%r�mpr�mpoL
%r�mprnpoL
%rnpr-npoL
%rCnprWnpoL
%rmnpr�npoL
%r�npr�npoL
%r�npr�npoL
%r�npr�npoL
%ropr)opoL
%r?oprSopoL
%riopr}opoL
%r�opr�opoL
%r�opr�opoL
%r�opr�opoL
%rppr%ppoL
%r;pprOppoL
%reppryppoL
%r�ppr�ppoL
%r�ppr�ppoL
%r�ppr�ppoL
}gs�
%r�Lpr�LpoL
%r�Jpr�JpoL
%rMprMpoL
%r	qpr)qpoL
%rIqpriqpoL
%r�qpr�qpoL
%r�qpr�qpoL
%rrprrpoL
%r9rprhpoL
%rUrprqrpoL
%r�rpr�rpoL
%r�rpr�rpoL
%r�rprspoL
%r-sprGspoL
%raspryspoL
%r�spr�spoL
%r�spr�spoL
%r�sprtpoL
%rtpr3tpoL
%rItpr_tpoL
%rutpr�tpoL
%r�tpr�tpoL
%r[MproMpoL
%r�tpr�tpoL
%r�tprupoL
%rupr-upoL
%rAuprUupoL
%riupr}upoL
%r�upr�upoL
%r�upr�upoL
}hs�
%r�upr�upoL
%r
vprvpoL
}is�
%r-vpr;vpoL
%rMvpr[vpoL
%rmvprwvpoL
%r�vpr�vpoL
%r�vpr�vpoL
}j(�r�vps�
(�s�
}R{bs�}S{cs�}T{ds�}U{es�}V{gs�}X{hs�}Y{is�}Z{js�}[{`s�}W{bo�
{co�
(<+{do�
(<+{eo�
(<+{`o�
(<+{bo�
(<+{go�
(<+{ho�
(<+{io�
(<+{jo�
(<+{_(<+{f(+s�
}\{bo�
{co�
(<+{do�
(<+{eo�
(<+{`o�
(<+{bo�
(<+{go�
(<+{ho�
(<+{io�
(<+{jo�
(<+{_(<+s�
}]*0cr�vp(+&{Ro�
,*{Ro�
,*(�-{](�o�
o�
,*o�o�
,**0lr�vp(+&{Ro�
,*{Ro�
,*(�-{\(�o�
o�
,*(�-o�o�
,**�r�vp(+&��s	
(�*0X�{Ro�
,
{Ro�
*(�,*(�(�,(<
*(�,(<
*{]o�
o�
-	o�,(<
*{So�
,{So�
(<
*sb
%r�vpoe
~z%-&~y��s	
%�z(�(�,(<
*sb
%r�vpoe
%r�vpoe
~{%-&~y��s	
%�{(�(�,(<
*sb
%r�vpoe
~|%-&~y��s	
%�|(�(�,(<
*sb
%r�fpoe
~}%-&~y��s	
%�}(�(�,(<
*sb
%r	wpoe
~~%-&~y��s	
%�~(�(�,(<
*sb
%rwpoe
~%-&~y��s	
%�(�(�,(<
*sb
%rwpoe
%r%wpoe
%r-wpoe
~�%-&~y��s	
%��(�(�,(<
*{To�
,{To�
(<
*{Vo�
,{Vo�
(<
*sb
%r5wpoe
~�%-&~y��s	
%��(�(�,(<
*sb
%r?wpoe
%rGwpoe
~�%-&~y��s	
%��(�(�,(<
*{[o�
,{[o�
(<
*sb
%rOwpoe
%rUwpoe
%r[wpoe
~�%-&~y��s	
%��(�(�,(<
*sb
%rawpoe
%riwpoe
%rqwpoe
%rywpoe
%r�wpoe
��s	
(�(�,(<
*sb
%r�wpoe
%r�wpoe
%r�wpoe
~�%-&~y��s	
%��(�(�,(<
*sb
%r�wpoe
%r�wpoe
%r�wpoe
%r�wpoe
%r�wpoe
~�%-&~y��s	
%��(�(�,(<
*r�wp(�o�
,o:
Yo"
r�wp(J
*{Uo�
,{Uo�
(<
*sb
%r�wpoe
%r�wpoe
%r�wpoe
%r�wpoe
%r�wpoe
~�%-&~y��s	
%��(�(�,(<
*r�wp(�o�
-r�wp(�o�
,
r�wp(J
*r�wp(�o�
,
r�wp(J
*r�wp(J
*�r�vp(+&��s	
(�*09�s�
{Ro�
,
{Ro�
*(�,*(�}�{�(�,
{�(<
*{�(�,
{�(<
*{\{�o�
o�
,
{�(<
*{W{�o�
,{W{�o�
(<
*{S{�o�
,{S{�o�
(<
*{Y{�o�
,{Y{�o�
(<
*{X{�o�
,{X{�o�
(<
*{Z{�o�
,{Z{�o�
(<
*{�sb
%rxpoe
~�%-&~y��s	
%��(�(�,(<
*{�sb
%r	xpoe
%rxpoe
~�%-&~y��s	
%��(�(�,(<
*{�sb
%rxpoe
~�%-&~y��s	
%��(�(�,(<
*{�sb
%r)xpoe
~�%-&~y��s	
%��(�(�,(<
*{�sb
%r5xpoe
~�%-&~y��s	
%��(�(�,(<
*{�sb
%r?xpoe
~�%-&~y��s	
%��(�(�,(<
*{�sb
%rGxpoe
%rQxpoe
%r[xpoe
~�%-&~y��s	
%��(�(�,(<
*{T{�o�
,{T{�o�
(<
*{V{�o�
,{V{�o�
(<
*{�sb
%rexpoe
~�%-&~y��s	
%��(�(�,(<
*{�sb
%rsxpoe
%r}xpoe
~�%-&~y��s	
%��(�(�,(<
*{[{�o�
,{[{�o�
(<
*{�sb
%r�xpoe
%r�xpoe
%r�xpoe
%r�xpoe
%r�xpoe
~�%-&~y��s	
%��(�(�,(<
*{�sb
%r�xpoe
%r�xpoe
%r�xpoe
~�%-&~y��s	
%��(�(�,(<
*{�sb
%r�xpoe
%r�xpoe
%r�xpoe
%r�xpoe
%rypoe
~�%-&~y��s	
%��(�(�,(<
*{�r�wp(�o�
,%{�{�o:
Yo"
r�wp(J
*{U{�o�
,{U{�o�
(<
*{�sb
%rypoe
%rypoe
%rypoe
%r'ypoe
%r/ypoe
��s	
(�(�,(<
*{�sb
%r7ypoe
~�%-&~y��s	
%��(�(�,(<
*{�sb
%r7ypoe
%r?ypoe
%rGypoe
~�%-&~y��s	
%��(�(�,(<
*{�rOyp(�o�
, {�{�o:
Yo"
(<
*{�r[wp(�o�
,
{�(<
*{�r�wp(�o�
, {�{�o:
Yo"
(<
*{�(<
*0Q�o�

(�,>o:
-*o:
s�
o�
(�
o�
&o�
o�
&oI
**0- o�

Xo;
QXo�
*J(�
-(�
**�o�
(�
-o�
o�
,
rWyp(�
,**0_r�vp(+&{^(�(�-;(�o�
o�
-royp(�o�
-{_o�
(=+,**�(�,o:
1{ao�
o�
,**0nrwyp(+&r�yp(+&{Ro�
,r�yp(�r�yps�
z{Ro�
,rwyp(�rwyps�
z{Ro�
*�r�yp(�o�
-o:
Yo"
r�yp(<
**{k*"}k*�r�yp(>+&o�
r�vp(�
,s�*o�
(�s�
z(4
*0'�s�
}�}���s�
(?+*rQ(�,o�
Q**�(4
}n|m(�}l*0��~5~�%-&~���s�
%��(@+~�%-&~���s�
%��(A+o�

+#o�
QP(��2
	(�-��o
-��
,o
�~1QP(�**\k
ES/�
2{lo�
*2{lo�
*{n*{m*N{l{m(*0
B�sY
~p~�%-&~���s�
%����%~o�(*0
B�sY
~r~�%-&~���s�
%����%~q�(*0
B�sY
~t~�%-&~���s�
%����%~s�(*0
J�s!
~w~�%-&~���s�
%����%~u�%~v�(*2{lo�
*{l*0w�{ls�
(
o�
o�
o�
�+o�
&o�
o�
&o�
-�(�
o�

�,o
�,o
�	*"?a
Rk
0��o�

o�
o�
o�
-%(�
-( 
(J
o�
+o�
*s�

8!	�s�
s�
o�
+7(�
		oB_,#	oC-	(+	((�
-����o
�o�
,Mo�
,$( 
o�
&r�ypo�
&( 
o�
&r�ypo�
&o�
&r�ypo�
&o�
,Mo�
,$( 
o�
&r�ypo�
&( 
o�
&r�ypo�
&o�
&r�ypo�
&X	�i?���s�
o�
,,( 
o�
&r�ypo�
&( 
o�
&o�
&(�
-( 
o�
&o�
&oI
o�
*qD�0��s�

r�ypo?(r�ypo@(oAo?-o@-oA�+,rzpr)p(o�
,rzpo�
&r�ypo�
&o�
&r�ypo�
&*0��9�o�
,rzpo�
&o�
&rqpo�
&o�
&r)zpo�
&r9zpo�
o�
(�
(�
(<

o�
&s�
o�
o�
o�
o�
&*0[r=zp�orAzp�pr��p�qr��p�rr%�p�sr-�p�trt�p�ur��p�vr��p�w*v~2(�
,s�*s�*0
L}z{zo~}s�
��%~|�(}y{yo�
}x*0E�{xo�

,-{{-o	�}{{x{{o�
&+}{*v(�
{xo�
{yo�
*0Q
o,T*o
rߪp(�
-r�p(�
-r�p(�
-+T*T*T*T*fo
ooss*0�(�
-�.*�.*Vr��p�|r��p�}*b(�
r�p(�
(1*>(�
(2*{�*{�*{�*{�*{�*{�*{�*{�*{�*{�*{�*{�*2(�
o�
*s!*0r�p�(�
s�
}�(�
{�o�
r0�p�(�
s�
}�(�
{�o�
rB�p�(�
s�
}�(�
{�o�
rR�p�(�
s�
}�(�
{�o�
rd�p�(�
s�
}�(�
{�o�
rx�p�(�
s�
}�(�
{�o�
r��p�(�
s�
}�(�
{�o�
r��p�(�
s�
}�(�
{�o�
r��p�=(�
s�
}�(�
{�o�
r��p�(�
s�
}�(�
{�o�
rެp�(�
s�
}�(�
{�o�
r��p�(�
s�
}�(�
{�o�
*0	(�
r�po�
}�(�
r0�po�
}�(�
rB�po�
}�(�
rR�po�
}�(�
rd�po�
}�(�
rx�po�
}�(�
r��po�
}�(�
r��po�
}�(�
r��po�
}�(�
r��po�
}�(�
rެpo�
}�(�
r��po�
}�*s5*.�>(�
*f(�
(�
t=}�*{�*0>�{�o#(-
t�
�#{�o#o�
{�o�
(�z*#�N{�o#(
*0>�{�o$(-
t�
�#{�o$o�
{�o�
(�z*#�N{�o$(
*0>�{�o%(-
t�
�#{�o%o�
{�o�
(�z*#�N{�o%(
*0>�{�o&(-
t�
�#{�o&o�
{�o�
(�z*#�N{�o&(
*0>�{�o'(-
t�
�#{�o'o�
{�o�
(�z*#�N{�o'(
*0>�{�o((-
t�
�#{�o(o�
{�o�
(�z*#�N{�o((
*0>�{�o)(-
t�
�#{�o)o�
{�o�
(�z*#�N{�o)(
*0>�{�o*(-
t�
�#{�o*o�
{�o�
(�z*#�N{�o*(
*0>�{�o+(-
�=
�#{�o+o�
{�o�
(�z*#�b{�o+�=(
*0>�{�o,(-
t�
�#{�o,o�
{�o�
(�z*#�N{�o,(
*0>�{�o-(-
t�
�#{�o-o�
{�o�
(�z*#�N{�o-(
*0>�{�o.(-
�
�#{�o.o�
{�o�
(�z*#�b{�o.�(
*J{�o#(
*J{�o$(
*J{�o%(
*J{�o&(
*J{�o'(
*J{�o((
*J{�o)(
*J{�o*(
*J{�o+(
*J{�o,(
*b(�
r�p(�
(j*>(�
(k*{�*{�*{�*{�*{�*{�*{�*{�*{�*{�*{�*{�*{�*sY*0wr�yp�(�
s�
}�(�
{�o�
r�yp�(�
s�
}�(�
{�o�
r6�p�(�
s�
}�(�
{�o�
rJ�p�(�
s�
}�(�
{�o�
r��p�=(�
s�
}�(�
{�o�
r�p�(�
s�
}�(�
{�o�
r`�p�(�
s�
}�(�
{�o�
rr�p�=(�
s�
}�(�
{�o�
r�=p�=(�
s�
}�(�
{�o�
r��p�=(�
s�
}�(�
{�o�
r�=p�=(�
s�
}�(�
{�o�
r��p�(�
s�
}�(�
{�o�
rȭp�(�
s�
}�(�
{�o�
r�p�(�
s�
}�(�
{�o�
*05(�
r�ypo�
}�(�
r�ypo�
}�(�
r6�po�
}�(�
rJ�po�
}�(�
r��po�
}�(�
r�po�
}�(�
r`�po�
}�(�
rr�po�
}�(�
r�=po�
}�(�
r��po�
}�(�
r�=po�
}�(�
r��po�
}�(�
rȭpo�
}�(�
r�po�
}�*sn*.�@(�
*f(�
(�
t?}�*{�*0>�{�o[(-
t�
�#{�o[o�
{�o�
(�z*#�N{�o[(
*0>�{�o\(-
t�
�#{�o\o�
{�o�
(�z*#�N{�o\(
*0>�{�o](-
t�
�#{�o]o�
{�o�
(�z*#�N{�o](
*0>�{�o^(-
t�
�#{�o^o�
{�o�
(�z*#�N{�o^(
*0>�{�o_(-
�
�#{�o_o�
{�o�
(�z*#�b{�o_�(
*0>�{�o`(-
t�
�#{�o`o�
{�o�
(�z*#�N{�o`(
*0>�{�oa(-
�=
�#{�oao�
{�o�
(�z*#�b{�oa�=(
*0>�{�oc(-
�=
�#{�oco�
{�o�
(�z*#�b{�oc�=(
*0>�{�ob(-
�=
�#{�obo�
{�o�
(�z*#�b{�ob�=(
*0>�{�od(-
�=
�#{�odo�
{�o�
(�z*#�b{�od�=(
*0>�{�oe(-
�
�#{�oeo�
{�o�
(�z*#�b{�oe�(
*0>�{�of(-
�
�#{�ofo�
{�o�
(�z*#�b{�of�(
*0>�{�og(-
�
�#{�ogo�
{�o�
(�z*#�b{�og�(
*J{�o[(
*J{�o\(
*J{�o`(
*J{�oa(
*J{�ob(
*J{�oc(
*J{�od(
*J{�oe(
*J{�of(
*0k
~W

(�-(p
(�-&~W
(X
,rqp(<

(r(<

~W
(X
,rqp(<

(t(<

*�{�o[(-
{�o\(-
{�o](-
ss*0J�o�

o
+3X~W
	o

( 
	(J

o�
(<

o
-�*F�.-(�z*b(+&o:
-(�z*B,3*(�z0�(ds�

*0�(es�

*0�(_s

*0�(as

*0	Gs�

*0	�s

*0
�s

*0	�sn

*0
�s

*:(P(�*.(N(�*.(O(�*F�6(`(�*F�6(h(�*2(ls
*2(ms
*6(is
*s
*"s
*b(B+&(w-(�z*�r�p}�(4
}�}�}�}�*0	ss	
(�*0P�o

�s�
o�o�~�o�o+o
+o
o�o
-��
,o
�o+o


+	o�
o�
(�
,o�	o
-��
	,	o
�o
>�(�
s
s�
o�
o
o
(
o

�s�o

+
(
o�
(
-��
��o
�o
(�		o
o
*(>X
n+�
#0N
o
oI

+r�p~W
o�

r�po
-�+r�p~W
o�

r�po
-�*V(
(
,(�z*0z(�o_

0
.$.:+R..!$.6+Att(�*tQ(�*tj(�*td(�*t�(�*o_
(�z0��{�o
-r5
p+r �po
{�r)po�
o

o�
,so�
o�
o�
o_
�,o�
t�o�
( 
-(!
,4o�
(�
,r>�p	r�yp(J

{�r�7p	o

{�:�{�rV�po"
�(�o
{�rj�po#
�(�o
{�rz�po$
�(�o
{�r��po�
�(�o
{�r��po%
�x(�o
+,o
,$o�
,{�r��p�(�o
o&
,{�r�po&
o
o'
,{�r�po'
o
o(
,{�r�=po(
o
o
o

+(
(�(
-���!o
�o�
9�:�o�
o�
o�
o_
3jo�
o�
o�
t�o�
o�
t�{�r�7po
{�r�po
(�{�o
{�o

{�o
*�0|{�r�po
{�r)po
o
{�rK=po�
o�
(�o
{�-!{�r<�po
��(�o
{�o
*0��{�rF�po
{�r)po�
o
of
,{�r^�pof
(�o
oC+od

+(e
(�(j
-���o
�{�o
*Vr0��{�rp�po
{�r)po�
o
oy
oz

+({
(�(}
-���to
�o
o)
+(*

	(�(+
-����o
�{�o
*2Nh�0R�{�r��po
oE
o}

+(~
(�(
-���4o
�{�o
*80J{�r��po
rįpo�
o�
(�rدpo�
o[
(�{�o
*0v-{�o
{�r�po�
o

+;{�r��po
{�r)po,
o�
o
{�o
X
o-
2�{�o
*0�
{�r�po
{�r�po�
o
o�
o�
t�o�
(�
{�rK=po
{�r�po�
(�o
o�
,r0�po�
(�{�o
*�{�o
{�rB�p��oI
o
{�o
*�E+rP�p*rT�p*rX�p*~W
*0|�{�rb�po
{�r)po�
o
of
,{�r^�pof
(�o
o|
,{�rx�pr��po
o
o
9�o
o�
o`
3m{�r��po

+@{�r��po
{�r)po
o�
o�
o
{�o
X
o
o
2�{�o
o
+o}
+(~
(�(
-���4o
�o.
o

+(
o`
3(�(
-���#o
�{�o
* :(b0k�{�o
,Zs�
(�o/
&o�
+(�

	oI
o/
&(�
-���o
�{�oI
o
*)"K0�{�r��po
{�r)po�
o
{�r°po0
oh
o
{�rܰpo1
o�
o
{�r�poR
o�
o
{�o
*0�{�rO
po
{�r)po�
o
{�rK=po�
(�o
o�
(�{�,Ho=
rG8po2
,6{�r8p(�rC7po=
rG8po3
o?
(�o4
{�o
*07�(�
(�oh
o5
8�(6

	(�,
	oN
+Do7
+#o8
o9
	oW
(�
,�o
-��,o
�	(�:�{�,^o_
3Ttqo�
.	o�
-8	oW
r�=p(�
,&	(:
,{�	oW
(�r��po
+#{�	oW
(�	oj
(�o
(;
:�������o
�*A4G0w(Vr�p(�
,r�p**�-*oR
,*oj
-*o<
-oj
o=
o�
,**0v{�,IoW
r�p(�
-5oW
rF�p(�
-#oW
r8p(�
-oW
rf�p(�
**oW
r8p(�
-oW
rf�p(�
**0*��@(�
rz�p$(>

�o?
t�*�o5
�(�
(c
,oI
(�
o�
*oI
*r{�,
o�
(�*o�
*0!(�
o_
3o�
*(�*�o_
.
*of
,o�
{�(X
-�*0��{�{�-+(s
{�r�=po@
{�r��po
{�ṟprرpo
{�,,{�~2(�
,{�r�prC7pr�po4
{�-2(�
-{�r�po
(�
-{�r,�po
++�]
{�rX�p(A
(B
oC
X�i2�*0?�{�rd�po
{�r)poo
o
{�,Ho=
r�6po2
,6{�r��p(�rC7po=
r�6po3
o?
(�o4
ok
ol

+@(m
o_
.
3t>(�+t�(�+o_
(�z(p
-���o
�o�
~�%-&~��s
%��(+o,

+	o-
(�	o
-��
	,	o
�{�o
*�M�
)
0��{�r��po
{�r)po�
o
{�rp�po
(�o
oR
oW

+(X
(�(Y
-���ko
�{�o
*Nj0M{�r�po
{�r�poD
o
{�rȲpoT
o�
o
{�o
*0�{�rȲpo
{�r)po�
o
{�rb�po�
(�o
(�o=
rܲpo>
,6o?
,.{�rܲpo
{�oE
oF
{�o
+ro=
r�=po>
,$o?
,{�oG
o?
oI
o
o=
r��po>
,$o?
,{�oG
o?
oI
o
{�o
*0w�o=
~�%-&~��sH
%��(D+oI

+0oJ
oG
(�,{�	o?
oI
o4
o
-��
,o
�*0<l
0u�
o_
3t�o�
o�
r�po_
3	o�
+o�

o�
-
+
rqp(J

,(�
�%	�(>

	*6(K
��**oL
�*0p�r$�p(E+&uy,~M
*u�
-o5
oI
(�(�z��(�
oN
u�-r4�po5
oI
(�(�z*0	�s

*0'�o�

+oO
o�
,*X2�*"(�*0&-,!
+o�
(9
-*X
o:
2�*0/-,*o:
(�

+o�
(9
-*X
2�*0,�s�

r�	po�
&(�r�	po�
&oI
*NrJ�p~W
(�*0��-*
sb
o"
+-o 

	-+rP�p�%	�(�oe
o
-��uL,o
�,(G
oP
oQ
+(R
-o�
&o�
&
(S
-����o
�*9Lw,�6(�
(>
*0a(�
,r	p*rX�pr\�po�
rh�prl�po�
rv�prz�po�
r��pr��po�
r��pr��po�
*0A-:o�

2o:
X0QQ*o;
QXo:
YYo;
Q*0YIoT

~�(U
,C~�(U
,6~�(U
,)~�(U
,~�(U
,~�oO
�**0X�( 
s�

o,
+'o+

%X,( 
o�
&	oI
o�
&o
-��
,o
�oI
*3G
0+�o�

+
o�
o
o
-��
,o
�* 
*o_
�**o_
�*.o_
�*.
o_
�*0%Euq
-*~0(�
,
o�
�**.o_
�*0[�|(�
���}(�
���~(�
���(�
��Ѐ(�
���2(�
��*0N(4
r��p(F+&r��p(+&rֳp(+&}�}�}�(s}�*�r�6p(+&(�(�o
*0��r�p{�o@
r"�p{�oo
o
rP�p{�oo
o
{�{�oV
oW

+#(X
{�{�oo
(�(Y
-����o
�{�{�oZ
o[

+((\
{�{�o]
(�(^
-����o
�{�{�o
+(
(�(
-���Uo
�{�{�o_
+&(`
		oa

	ob

(�(c
-����o
�o
*4S0��5��;3n0��rv�p{�o@
r��poh
o
r��po�
o
(.

9�o�
o�
o�
t�o�
o�
tdr�p{�o@
r��p{�o@
r$�poh
o
oE
o}

+((~
{�{�o�
(�(
-���4o
�o
o
o
*�5�0��o	o
od
:�r6�p{�o@
r)po	o�
o
r$�po	o
oh
o
rb�poo�
o

+.o{�{�oe
(�X
o
os
2�o
*0�o
od
:�r6�p{�o@
r)po�
o
r$�po
oh
o
(�
rb�poT
o�
o
oR
oW
+%(X

{�{�	oe
	(�(Y
-���ko
�(�o[
o}
+(~
o�
,	(�(
-���4o
�o
*q2��(��r��p{�o@
rJ�po�
o
r��pr�po
o
*0�(�
oR
o�
o�
of
*0:�
o
o
o)
+
(*

(+
-����o
�**0��r��p{�o@
r)poD
o
oT
o�
o
od

+0(e
te{�{�o�
(�
	(�(j
-���o
�o
*8=u0X�og
(�
oD
o�
o�
(�
,2+ o�
o�
3
o[
o�
*Xo�
o�
2�*�r��p{�o@
r)po�
o
(�o
*�rܵp{�o@
r$�po�
oh
o
(�o
*0��r�p{�o@
rb�po�
o
o�
o
o}

+6(~
{�{�oh
,{�{�o�
(�(
-���4o
�o
*3Cv�r �p{�o@
r)po�
o
rJ�po�
o
o
*�r>�p{�o@
rN�prZ�po
*0Q(4
-(b
+(G
si
}�sj
}�~�%-&~��s	
%��}�*�(4
-(b
+(G
si
}�sj
}�}�*:{�ok
*0`�
{�o�
+"X
{�o�
(�
(�
(<
{�ol
-�{�ok
,
{�om
*&(�*:{�on
*0J�(o

(op
oq

+	�or
oq

	3��,o
�,o
�*5
8?
00
(s

rb�po�
,o�

rh�prqpo�

*(t
*
*0��(u
(o
sV

(-rl�psv
z	-rζpsv
z-r*�psv
z(u
~�~W
o�
rq.p(<
(rx�p(<
(r��p(<
((	((�
,o
�*��
0�op

(�
,o
�*		
0
�
ow
ox
o�
r��p(�
,	s�
+s�
(u
(o
(c
(�
s

(y
oz
(
	o�o�
-	oT
	oI
s{
o|
�	,	o
�,o
�,^o�
1Uo,
++o+
o}
o~
o
sv
o
-��,o
�z(u
(*(L>�
AS�
�8��s�
(
,~0*s�
(
,~1*~2*:(u
(*>of
{��*Jo�
{�(�
*f(4
}�(�
}�*0-{�
�.3
�(�*0��{�{�,.d
ݏ}�{|ot
o�
}��}�+>|�(�

	u�-*{{	o�
oG+}�}�
�2�}�|�(�
-�(|���
�(�*��f}�|���o
*{�*s�
z07�{��3{�(�
3}�
+s
{�}�*(*.s��*(@*V(4
}�
}�
*.s+�*6ttsu*6tdsS*6t<sc*6tQs/**(1*0[�ob

-1o}o�
,o)}*o}*o(3}}*0!o%
(3
}}*z3(5+
3	(6*.(2*0М(�
o
*0�}(�
o
*{*{*.s:�*�-{s
o�
*{s�
o�
*0Ks�
}s�}s�}s�
} sM
}!s}"(4
*.s?�#*ro�
-o�
,
o"
�**�o�
,3o"
-+o
~%%-&~#�Bs�
%�%(H+***o
�*o
**o�
�*N{,{+(*2{-s�
*{.*.sN�/*:o�
~%�*f(4
}1(�
}3*0�{1
E_�*}1}68�{6~$Z~$X{4o:
/4{4{6~$Z~$o;
}2}1*}1+-{4{6~$Zo�
}2}1*}1{6X}6{6{4o:
~$[>T���*{2*07{1�3{3(�
3}1
+sP
{5}4*(V*f(4
}7(�
}9*0��{7
,.F*}7{:}<}=+={<{=�(^(_}8}7*}7{=X}={={<�i2�}<*{8*07{7�3{9(�
3}7
+sX
{;}:*(^*.sa�>**o�
�*0�s�
}E~�%-&~��s	
%��s�}Fs�
}Hs�
}Is�
}Js�
}Ks�
}Ls}Ms�
}Os�
}Ps�
}Qs�
}Rs�
}Ss�
}T(4
}V*0�s
}�*:{So�
&*6{So�
*0N{Io5

{Ho_
*n{Po�
{Qo�
*2{Po�
*0_{Po�
,*(g,*{Ro�
-3�'%�e(T ts
�(q{Ro�
&*0{Qo�
*:{To�
*:{To�
*0X�R{N(prqp(J
oI+
,1{V~2o�
/Po�
.Po�
3RQ**0S{U-D{NoJ+o�

+o�
(�,o�
}U�o
-��
,o
�{U*)B
&(r*0R�o�
,I-~�{Mo�
,{Mo�
o�
*u
-s�

{Mo�
*0i,(�
-oI
}\+}\,(�
-oI
}]+}],(�
-oI
}^+}^}_*R�e�eo�
*.(t�*{\*{]*{^*{_*0Rue-*�e
{\{\(X
,*{]{](X
,*{^{^(X
,**0F-
{\,{\o�
a
{],{]o�
a
{^,{^o�
a
*0y
~W

(v,
(v(<

(w,&~W
(X
,rqp(<

(w(<

(x,&~W
(X
,rqp(<

(x(<

*r{\-{]-
{^�**.s�`*o=*oE*�o
~c%-&~`��s*
%�c(/+*o[
*o9
*o�
*J{ho�
o�
*^ov{jo�
(�
*0�(4
}k{ko5

tr��p�Go�
}lr��p�(�
�Go�
}mrηp�(�
�Go�
}nr�p��(�
�Go�
}or�p�+(�
�Go�
}p*b{o{ko�
t�*R{n{ko�
*b{m{ko�
t�*R{m{ko�
*R{p{ko�
*0n{l{k�o?
t�
�Mo
-+o
s�

	o�
o�
	o�
	(�o�
(�	o�
&~W

�*M�0I-#~4(�
,(�s�*(�s�*~4(�
,(�s�*(�s�*.s��q*�~W
(�
-( 
oI
(J
*oI
*6{x(�*.s��y*jo:
Yo"
r�vp(<
*jo:
Yo"
r�Cp(<
*jo:
Yo"
r2�p(<
*jo:
Yo"
r<�p(<
*jo:
Yo"
rF�p(<
*jo:
Yo"
rN�p(<
*jo:
Yo"
r�wp(<
*jo:
Yo"
r7yp(<
*2r�wp(<
*2r�wp(<
*jo:
Yo"
r�yp(<
*2r�wp(<
*jo:
Yo"
rT�p(<
*jo:
Yo"
rZ�p(<
*jo:
Yo"
rd�p(<
*jo:
Yo"
rn�p(<
*jo:
Yo"
rx�p(<
*jo:
Yo"
r��p(<
*Bo:
Yo"
*jo:
Yo"
r�wp(<
*Bo:
Yo"
*jo:
Yo"
r��p(<
*jo:
Yo"
r��p(<
*j{�{�o:
Yo"
*R{�{�o�
*.s���*2~1(x
*
*0n~�%-&~���s�
%��(K+~�%-&~���s�
%��(L+~�%-&~���s�
%��(M+*2r�yp(N+*2r6�p(N+*2r��p(O+*0n~�%-&~���s�
%��(K+~�%-&~���s�
%��(L+~�%-&~���s�
%��(M+*0n~�%-&~���s�
%��(K+~�%-&~���s�
%��(L+~�%-&~���s�
%��(M+*0n~�%-&~���s�
%��(K+~�%-&~���s�
%��(L+~�%-&~���s�
%��(M+*2r��p(N+*2rެp(N+*N(o�}{*>((*6o�}{*Z{{o�
t�s�*
*:{{�(P+*:{{�(P+*:{{�(P+*:{{�(Q+*:{{�(Q+*:{{�(Q+*:{{�(Q+*:{{�t�*:{{�(�
*:{{�t�*:{{�(�
*>{{	�t�*>{{	�(�
*r��p*Z{{o�
t�s**:{{�(P+*:{{�(Q+*:{{�(Q+*>{{
�t�*>{{
�(�
*>{{�t�*>{{�(�
*r��p*{�*:(�}�*s�*s�*(�
*.s��*o�
**o�
�*0js�
}�s�
}�s�
}�s�
}�s�
}�s�
}�s�
}�s�
}�s�
}�(4
*{�*"}�*js�
}�(4
}�*{�*{�*�(
o�
(
X]o�
(*0M(Q(
on
o�
TTJ.#(on
o�
-on
o�
T*0R	o
o
o�

oR
oS
on
o�
3+,
oR
oS
*oR
oS
*0L
{�os
.*((-*(-*(-*(,**0%s)
}�o[
�*s�
(!+*F(,(**0?o[
o}

+(~
o�
-�(
-���4o
�**!-02
s�

((o�
{�o�
o
o�
�*0<�o[
o}

+(~
o�
o�
(
-���4o
�*!-0Qo�
o�
o�
t�o�
{�o�
3(o�
o�
o�
t�o�
{�o�
�**�{�o�
o
o
o�
Q{�o�
o
o
o�
Q*.s��*.s��*Frqpr�po�
*f(4
}�(�
}�*00-{�
�Y63�..��(#�("�*!(0�{�{�,.p
ݺ}�{Mo�
o�
}��}�+i|�(�

	o�
}��}�+(|�(�
}�}�
�Q�}�|�(�
-�(#|��|�(�
-�("|���
�( �*��f}�|���o
*j�}�|��o
*{�*07{��3{�(�
3}�
+s
{�}�*('*J{�o[
o�
*BSJBv4.0.30319l��#~H���#Strings��#US�e#GUIDf�v#BlobW��+	�3�}�*��3�5=�	2Q}[0LU�.NU�mJ؈ϋ�N"��J��N_NN"���"��M"��Jl�Ll�Ml?OltNl�NlCLl`Ll�L��KJ��Ll�Jl!OltOU��V�	N���_3J_
�L�Z
bO�Z�_x|��_uwk
O_
��B_}m�^��Z�	~j��^
2��}|^m,ym�m
cl�}
�z�}
���}�_ms_�qm�s"�rm�qm�^�^� �^s_�x�^&	�^�	~�݅d~�^�F�^���^�~#@�^⩢Z�<�Z�=�Z��^�s_�݅�E_(KU�
8)B_�t_�IU�y/_S�q��	~//q��K؈�@�^
#nB_*x�^
�gB_
UgB_H��^
7jB_
jB_
xB__x�^
A�B_�r_
зĖ�^�^
NoB_[k�^�ul
?hB_
(V�D�^��^
�hB_
qfB_
�B_
 "B_�p�^�?�^
�B_
��B_
L�B_
fB_?�^
?�^
tgB_L_�E�^­^�G_�_X_�~Oym_�m
	~�	~r__i�l���^
�$B_I<_

gB_gF�^
�eB_
6oB_� �^
�fB_%,�^玲^| �^�_�__�>_
��B_
QfB_
�fB_[��f~��l�ul�݅�ulTulJul\FlfMl	~"y�]�y�^�q�I�^�*�Z��_���]箨]d|�]F��]�+�]�K�]/��]��]�e_m�^���^�	����l�݅�D�^�@�^|�^��^���^�k�^�K؈�M_Dm�S�_�S�SUT�Sl{�
3�B_
�fB_
Z�B_
��B_
ڭB_
�gB_]	�Z�#�^x�l�)�Z�oVt��Vt	�Vt��VtCp��m&�^�s_xr2+�^~�-?�^0_�_�݅v^m0S��e��+��N؈9t�^
��}
w��}
��}
�n�}�rl�_��o�݅�-- ���xVt���a�u�k���k�{J؈�s_�rCr_�m�^�mMz_S_|�i"z�i3u�iM�iɓ�i�r�]�
SiU_�z_
mz�v
^z�
ї�}�WmB^m
+m�m�Emc`m�~_~	~=/Gw��Z��Z
AnB_�__�/_&;l
��Z
�gB_
oB_�K�k�K�k
�J�Zsw_
�B_;[��
1wĖ
tnĖ
TFĖ~V_

�Ė
WCB_
GlB_
�nB_�~�^
�mB_
�mB_�_
�fB_eA��Fq�ۮ_!�U���_�/_
/lB_
�hB_
n�B_����
bhB_
`pB__Sw�O_
�gB_S _F_
��B_ڢ��袼��q_�q_�G_�~�^X
_{7XӴ�^I|�Z�q�Z1_�-�]�l�]Dv�]HS�0�Vt~0_B�^H/�S��S�~��/_��{�S_r_
��B_�/_�=�]K�Vtn[���^���^�t�^�{�{.h�3f��h��e��h��pVt�+��Vta0m�_
�l���A�X="é7w�Gw�x����mvF�o&Z�&C	�=�n���nVtVt
ٯ�Z	�_5?[�]u��^l��^ݽ�����r	~�s_�s_�s
S,r_�r_�z�U�jW|�i
K6QS
��B_���^}p�Z0|l�|l&��� �^��LuXOy�}N��Z}x����X�/ց��}�4�9���}�H����\�S�Z���}�X
���X�c����\�u�u��}�|dn�����A����������(��O���(��H���T��\�����R���T����F��@���`���@��r���X�W)��}��ו��}�7�'�!`}�N�'�!`}��v!`}��W}!`���q}!`�����!`}��Oq!`���3�!`}��p�!`���Vs!`��Y�!`����ɕ!`}��R[!`}��!`}���!`�=��!`}
=�!`�D�3�!`}DƆ!`}"E�o�!`}&e�v�!`}&f� �!`}&m���!`}0m�!`}6{6}!`}A�:�!`}B�u��}P�o���*R�='���R���S��k��b(��}k��"[��}l�bya�}l��9ya�}x�*a��~!!�na���!��a�E�5!�na���Y��a�E�n�F[it}����it}���[it}��r�it}��w(it}����Q�}�zQ����yQ����yQ����yQ����}�2}��}�7
}�!�}��"�!�?�%lD�%ā�%n})!�}*u�90!�}9r�9<!H}<!�}#>�}+G}-I�}.K!�}/M�}1P]}7X!�}>`!��Ad!H}Ed�C�Ws
i�9\s!�}`~a}h��}j�}�}k�!�}q�X}x�!�}y��}���}��!�}��j��������u}��`����
���v.�!�}���}���}�	!�}�<9�!�}�F}��}�)��TS���S���S�P�S�[�S����S�E�S�f!�S�F!�S��<�S��A�S�=�S�*=�S�/��S�L��S�w��S�v�S���S�I��S��^�S��$�S��,�S�:c�S�m�S�~�S�m�S����S��=�S��8�S�S��S�(��S��S���S��z�S�QW�S��t�S�"T�S���S�*��S��A�S�@]�S�0�S�{B�S��B�S�[B�S�c¦S��¦S��¦S�!G�S�G�S��F�S���S��9�S����S�Lk�S��j�S�k�S�q7�S�~��S����S��Y�S����S����S�[��S���S����S�8��S��j�S���S�E9�S����S�f��S�柦S���S�.V�S�㻦S����S��?�S�8�S���S����S�ϣ�S����S�0��S�I�S�k�S��^�S��	�S���S���S�i��S�G��S���S�|��S�	��S�j��S����S�ߠ�S����S�#��S�S��S��"�S����S�a��S����S�䐦S�㛦S�5��S��_�S��G�S�_�S���S�0!�S�\��S�=��S�0z�S�`"��y�Tŋ�T�$�˨�T�Q�T�m�T��T^��T��Tچ�T���Te)�Te)�T1�%��I�T1��Tچ�Th�T�R�TQ��;�T��;��T��E�T��'#��æ1���T1���TQ��T�,U1��UQ��#�1��U1��U1�U�UV��TV��Y�TV���TV��H�TV�bY�TV��TV��H�TV�?�TV��X�TV���TV���T_UQ��Y�Q��Q�W�Q��H���U�$��V�Q��;��UV��%UV��!%UV�,�%UV��%UV�ӳ%U�R)U�R)UQ�o�Q�,2�j>�Tm��T3�C.U3�C.UQ��9�Q�-:�Q�:�Q�:�V�w4�v�3UR<3U�3U�3Uʶ3UpU3U�_3U!ׂ8U!��8U!�EU!��VUV��$�V��%�V�#%�V�+&�V��1�V��1�V�p1�V��1�V��6���iU��D�mUzv}U_qU+v�U��UU�U�UV��*UV��*U[��Tu��U�V��)UO1��A3U���U螗U���U�)�U�>3U��U?��U���US��:�S�M�S��
�S��
�12��U1?��U1L��U3d�6�	�U6��U6�UQ���Q�r�Q�{�1~�U���UG~�U���U3��8��m�T}�U�d�Uz%�T�T�UV����UV��+�UV��?<����U���U�UV��<�UV�".�UV�8��UV��p�UV�y[�U3�2�3�5�3ڷ�3�4�3�8�3�8�3�E�3á�3�;�32�3ɬ�3:��3�~�U^qU1�U1�U1�US��%�S�c%�S��5�S�/5�S�]5�S���S�q��S��t�S�2�S����6�	�U6��U6�U���U��U���UQ����y�U!{�`�t~�U)m�U3�wV��V�d�U�T�V_qU+v�U�
.U�
.U�
.U�
.UQ��4�Q��4�Q�W4�Q�;4�Q�}
�Q��
�Q�a
�Q�v
�.�"W#�V�'VY'V,(V�'V�&V'V�'V(VI(V։"Vĉ"V��iU0�iU�}Un�"V=�}U��}U��}U��}UR�"VR�}U�}UY�}U¼}U�*V!Tp/V!Je�U!�:�1ć�1^�1���1�]�1���1�]�1Q��1r��1�]�Zy4V; 9VTp/V��>V1���1kG��UV��OBVV��BVV�[BVV��BVV�O�BVV��=BVV��,BVV�:cBVV��BVV�!BVV�yBVV�ٳBVV��BVV���BVV�oBVV�,BVV�BVV�[�BVV�c�BVV��BVV�9!BVV��!BVV��qBVV�oqBVV�{BBVV��BBVV�[BBVV���BVV���BVV�8�BVV��tBVV�cBVV�!BVV��BVV��9BVV�vBVV���BVV��BVV��eBVV�ރBVV���BVV��BVV��BVV�_BVV��-BVV�E9BV��UGV�5GV��-GV��`GV��UGV�GV�u-GV��`GV�YGV��7GV�FGV�dIGVQ���Q�
�Q�r�Q�Q�Q���Q��Q�i�Q�G�Q�?�Q���Q�G�Q�I�s�LV�VGV��GV��-GV��XGV�DaGV��.GV��<GV��WGV��cGV��cGV�P-GV���GV�GV��GVQ���Q�
�Q�u�Q�T�Q�?�Q�]�Q���Q��Q�c�Q�[�Q�W�Q���Q�4�Q���-�QV6!YVVzZ�TwVu�[VFd�U#7%�Q���1�D.U1�D.U1|D.U1�=.U1�@.U1	E.U���U�}�U�}�U%�!�`V!�|iV!g_rV3M
{V+@VVw��8HUͲ�UU��T�	�V6��V�rV�UV� #�VV��ÏVV��|�V�UV�휔VV�I��VV���VV���VV��!�VV��!�VV�ڀ�VV�Ȁ�VV�(��VV���VV��|�Vص�	� �	6��V�.3U%/3U6��V3rVT��pZ�$^�uZ�}m�T���Vr��V���V���V��V���U6��Vy�V2�Vo�V"�Vs�VH�V�V폭V�V�W���U6�W�W8HUͲ�UUU�PU��U8HUͲWU#�iU�iU�	iU�U6�WwW�W�UV��XWV���WV��W�!Wd��VŚ+Wƥ5W�vBW�vOW�ZW��dWTvV�m�U��nW#wxWw�WԌ�W��W�v�W�$�!�d�U�UV�u�WV�".�WV�8��WV��p�W!V�!�!?<�!D�W6��W��Ww�Wg�W�W��Wq�WV�W��W&�V�bX�(XW�
XAWX֔X��X+vX6�X�W�W�W�W�W
X�*BV6�%X�rVRrV�rVBrV�rVrVrV�rV8rV�rV#rV
rV
rV�rV�rVrVMrVLrV�rVXrV�rVrV�rVrV�rV�rVrV�#��#�LF*V6�*X�/X�:X�GX=GXtRX�]X2GXpGX�RX�]X}GX�GX�RX�]X�GX�GX�RX�]XQ��UQ��UQ��UQ�UQ��UQ�GUQ��UQ��UQ��UQ�\UQ�4UQ��UQ��UQ��UQ�UQ��UQ�GUQ��UQ�#UQ��UQ��UQ�\U��>V6�tX�V
yXgE�X���X4��X�@�X
x�X(��X��X��Xa��X���Xi�Yk�
Y6�YnrV6�YVrV8HUͲYU�Y�	#Y�5Y�?YP ��Y �
t�� ��� ��Tw!� ��� ��yDY� �F� ���IY� �FUOYt!�FUt	�!�FUVY�!���]Y	�!���bY
�!��fY
("��*zY�$�CP<%����%�S��Y�&�s��Y�&�ߩ�Y0'�ku�Yd'�ku�Y�'�t,�Y�'��(�Y�'�u��Y(�y��Y(�y��Y"6(�y��Y%P(�y��Y)�(�y��Y-�(�y�Z1)���96p)���Z6�)�)#Z6�)�),Z7�)��69*��(#Z;�*��2�<�*��2�<�*�&w!<�*�6�6Z=�*�ҁ;Z=�*��Q9=�*��~@Z=+���FZ=+��MZ>+��TZ?(+��	A�+�-g]ZA,�FgfZBK,��^�CX,��(�YC`,��oZCp,�e�uZD-�M�~ZF�!�e��ZI�!�e��ZK�-�FK�ZM�-�FK�ZP.�3��ZS�.��I�ZW /�T��ZX<1�e��Z[�1��9t	]�1��J�Z^2�b��Z`H2�x��Zb�2�x��Zd�2��J�Ze43�!M�Zf`3���bYgl3���ZgR4�;k	[ii4��[j�4���[l�4���$[o5�+�/[r"7�ß6[tL7��@[v\7���I[x�7�=�S[{�7���bY|	8��Y[|8�e�b[~08��>�T8�X�Ka8��^i[n8��o[}8�l]u[��8��\u[��8�zh~[��8��R�[��8�腎[��8���o[��8��(�Y��8�ҁ;Z��8�h�[��!���bY�9�[�(9��	��;����[��;�A��[��;��G�<�Ѿ��<��/�[��<�̛b[��>�S�b[�d?���[��?�Qÿ[�B�$��[�C�1"�[��D�9�[�F����[�xF�8B�[��F�dg�[��F��^�	8��\��F���b[�LG��	�H�e�b[�8H��>��\H�X�K�iH��^!�xH��\�I�ַ\�CI�����KI�	��TI����\I���eI��!��mI��!�vI��<\�~I��<"\��I��Xt	��I��Xt	��I�õo��I�t	�
J��t	�J��Yt	�.J�|Yt	�@J��Ht	�RJ�eHt	�dJ�`Yt	�vJ�DYt	��J��t	��J��t	��J��t	��J��t	��J�	t	��J��t	��J��Ht	�K��Ht	�K�=t	�*K�#t	�<K��t	��K��Eo��K��#(\�L���bY�vM���~M�K.\��M�u5\�HN�]0C\�hN�wM\��O�#X\�Q�.#� Q�qb\��Q�TZ�R��?i\��R�;Zr\�S�
�y\��S���y\�$T�iD�\��U�t	�V�����(V��#(\�|V�'��\�W�t,�Y�&W��,�\�/W�A��\�LW���bY��W�\��W��^�\���G��W�՚�\�X�O��\�
X�f��\�X�}��\�X����\�'X�4��\�4X�PX�\�XX�kQ�\��X��Q�\��X�}M�\�Y�8M]�PY�6�]�`Y�^K]�Y��]��Y�p���Z�u��Y�[�
-$]��[��,2]��[�$�?]\���bY�\��G]�\�i�b[�\��b[(]��Q]�a�W8[](b�i;w!Eb��^f]Tb�vAl]�b��Ev]�b��"]�\�]tc�gj�]�c�i�b[Td���]�e���]Of��R�]hf��E��f��^�]�f�<��f�В�]�f���]tg����
�h�<��]i����]!�j��u�]#�k���](\l�9P�]*�l�%��]+$m�	�9-`m�D^-Tn�� ^/�n��1w!0�n��1w!1�n�kR^2�n�xR^2�n�1�2o�1�2o���92Io���^2To��g!^3p��*^4hp��*^5�p��P1^6�p�Q1^8pq��P1^:�q���9<�q��0�<�q�3;�<�q�A:�<�q�gj;^<hr��,I^@s��S^B�i�b[Es��GF8s���Ft�p�b[F,t��9#G�t��^]^H��	H�t�\H�t�e�b[J�t��GK�t�e�c^K,u���s^N�u�阃^Qv��^�^Tv��b[TDv��	UNw��>�Uuw�^U�w�e�b[W�w���b[X�X�KYx�#b[Y({��^�Z5{�R�9Z@{��"�^Z�{��>�^[�{��^?|�7C�^^P|��B�^_h|�7C�^`�|�U�^b�|�U�^c�|�U�^e�|�w?�^f�|�nC�^g�|�@�^h}�D�^i}�0��^j)}���^l8}�3��^nX}���^q�}��B�^r�}��B�^s�}�4�_t�}�h��u~�E<�u&~����uI~���ul~����u�~����u�~�Ȝ�u�~����u�~�xT�u�~��_�u�~���bYu�(�_uX��46%_u���46,_v��463_wH��46:_xe��46A_y���46I_{�q�46P_|����Ft	}��q9t	~���7t	���7t	�/���W_�8��F6t	�E���9t	�R���6t	�_���:t	�l��v ]_�����:S[�Ȃ��5t	�؂�p8[]����0h_�|����bY�ȃ��e�ԃ��e���Pt_����[z_�����_�.��Ez_�D��f!z_�Z��F!z_�p���<_�����At_����=t_�„�*=�_���/�_���L�t_���w��_�>��vz_�T���_�r��I�z_�����^z_�����$z_�����,�_���:c_����ie�
��~z_� ��mt_�:����t_�T���=z_�j���8t_����S�z_����$�e�����z_�����z_�҆��zz_���QWt_����t�_�$��"Tz_�:���_�X��*�z_�n���At_����@]t_����0e����{Bz_�ć��Bz_�ڇ�[Bz_���c�z_�����z_�����z_�2��!Gz_�H��Gz_�^���Ft_�x���t_�����9_������e����Lkz_�҈��jz_���kz_����m7e�
��~�t_�$����z_�:���Yz_�P����z_�f����t_����[�_�����_�������_�މ�8�t_����je����e���E9t_�*����e�6��b�e�B���e�N���z_�d��.Vt_~���t_�����z_����?z_Ċ�8_���t_	�����z_��ϣt_,����t_F��0�z_\��Iz_r��ke~���^z_����	e����e����e���i�t_ҋ�G�z_���z_���x�e
���e��f�e"����e.��۠e:���eF���eR��O�e^���"ej����ev��]�e�����e����e���ߛe���1�e����_e����Geʌ�[e֌��e��0!z_���X�e��=�t_��0zz_4��`"t_N���]�_V���,�_^��<�_e��l�_l������ �����#!���h��_"���R#"΍�&�_#ݍ��^w!%���^ &���mw(����(����_(�(�5-�_*�0-�_,�&-�_0�1�5-�_3�0-�_5�&-�_9����_:T����_;���6�_<Ď�N�_=����>��\>0��8q�Y?8��Kq�\?K���u�_@S���*`@|���*`B����*-`E����*:`G����tM`Jl��>sj`Ql��>sw`T��>s�`W���J��`Y����FZZ���MZ[��`\0���]F��E��`^g���V�^o���9^z��ZG^����^Ɣ�`^���)�\a��:1�a��%A�a��4A�a%�����`b-��̞�`b5�����`b=���bE���bn����`b����)�^d���:>�d���G>�d�����`eƕ�)��`eΕ����`eؕ�ދ�`e8��M^�`j�����bYlu���	al����ealԙ���bYm��Ym���an<���aqȚ�R(at����}x���am�x����&9ax����&?ax˛���9yӛ��yܛ�8Faz��8Qaz���{d���g|����S}؜��Sg~��0Fa8���g����Sg�آ���_a�,��uia�d���ua�D��ܑ�a����=i�a����G�a�������a�P�������z������a���QE�a�,�����a�|���i�a�����a�ܭ���a����s�a���m@b���7*b�԰�\�$b���x�0b�'��x�7b�@����Ab�����Kb�����Xb�l���wbb�����wzb���y6�b�5���2t	�@��d2�b�ʹ�y6t	�ش��0�b�5��b�q����&�~���U�����E������0�����Y��b����}��b������bY�4��\�M����V��8q�Y�^��Kq�\�t��c��b���c��b���c��b�x�����b�з�[��b����Gc�<���Gc�8��x�-c�w��e�@c�����z^c�չ���|c����d�c�4��E��c���0��c�H����c�����*�c����"�c�ܿ�	"�c�P��{d����
�d����){d���5.%d���M{+d����5d����6Ad�L��S?Hd������Nd�%����bY�D��ΐUd����wmfd���wm}dU�����d{��m�d	���m�d���>m�d���>m�dL���	aT���#e���3#e���83#e(��re*ex��X3#e���h$1e��� $#e���8$#e "��R$#e!O��hd;e"\���eBe#����eMe%����bY't����&'����}*����l�*�����9*����*���Fa+��Ve+)��ie,L��ie.����0����g1R���oe2`���o�e4���D&�e7����j�e:&�����e;N���l<`�����e<���ɤ�e=D����e?����C�eA������eB|���p�eC ��,�eFH�����eI���W@fJ���ŒfLd���%fP���
/=fSL���.=fU����LfW��\�af\D��$�fb �����edG��z��een��7��ef������fg`��&E�fk����D�fp������fu���B�gz,����$g��g&.g����:g�����&9a�����&?a�����?a����4w!� ��i:w!�8���;Dg�f��\����8q�Y����Kq�\�����u�_�����*Lg����*:`�b���*bg�����*-`�����*rg�����*`�����*�g�����*`�H���*�g������g����d�g�d���d�g�����*�g�0����h�D���h���I0h�8��a�%h����
1h���11h�`���
1h����1h���?C5h��!���bY�����h#�����#����w�t#������-#���������#�,��е*�?��� �#�T���OS����EQ�#�����OZ��������@h���е#����� #���EQw!����Ow!� ������Y#�x�xw#���,Rw!��$Rw!�x!�IRw!��!�ARw!��)�6RKh�D*�~#Wh�o*��#��*�ȝ#��*��Q#�+�`##�H+�/# ��+�*w!��/# ��+�F^h��+�Fdh���Y#��xw#��,Rw!��IRw!�,��&kh�:,���D,�>�th�w,�7#�h��,�� ��,��o�h��-�`��-�AG��-��:���-�.ed��-�_��h��-����h�.���h�`.�@��h��.�f��h�/�+pX�/�?p�h�/��-�h��/�	 �h��1��id2��t#i3���bYk3��G0i�3�yDi�3�r954�ZG�ɳ�
�U��
E��
5��
%A��
�G9�
w_9�
h/9�
�9�
�R9�
!9��
L\9�
&B��
s\9�
+��
�[9T4�,+Si�4�c�[i�4��[ai�Vhi��uoi�
�]�:,���4���bY5�� 5��%05�Pbui85��`ui@5�yauiH5��buiP5�<buiX5��`ui`5�gauih5��buip5��buix5��aui�5�aui�5�bui�5�څb�5��(E%�5���7��k�8��{{i�8��D��8��>%9��-�i9��U�x9��U�9���9�(�9��-�X:��-l:��`��:��`�:��U�8;��UL;����;���;�]-�<�i-,<�n`��<�{`�<��X �<��X =��7�!p=��7!�=� �"�=�3"�=�$I9#P>�DI#i>��\9$|>��[9$�>�'\9$�>�	]9$�>��\9$�>��[9$�>�\9$�>��\9$?��\9$?�5\9$'?��$@?��%$P?�dbui&X?��`ui&`?��aui&h?��aui&p?��aui&x?�bui&�?�vbui&�?��bui&�?�cui&�?�Waui&�?�mcui&�?�(aui&�?�Vcui&�5�څb&�?��(E%&�?��&DB��k&�C��{{i&�C��D�'�C��>%'�C��-�i(�C��U�(D��U(,D�E�)�D�P)�D��3�*�D��3*E�$7�+hE�37+|E��.9,�E��.,�E��<�-PF��<-dF��W.�F��W.�F��c/8G��c/TG��c0�G��c0�G�<-1(H�F-1DH���92�H���2�H��93I�34I���94�I�ѹ4�I��\95�I��[95�I�d\95�I��\95�I�0]95J�]95J�
\95.J��]95AJ��[95TJ��3�5�J�c��i5K�?`�i6^K��]�i7pK�_�S!9�K����i;�K�m�i=�K��}�i>�K�I��i@�K��$�iAL��]�iB$L�ǯ�iC<L�ǯ�iDTL��j�iFlL�kT�iG�L�P�iI�L���iL�L���iL�L�>�iL�L��B�iM�L��iN�L���iO�L��8�iP�L��/�iR�L��/jSV���,jUM�s�jVM��jXPM��],j\tM��]Bja�N�<�ejjRO��$khO�r�ljl�O���m�R���sjnXS���zjoT����jp�T����jq8U�|�ir�U�L��jsV��v�V����jw�V�1��jyW�˪�jz�X���lj{DY�
��j|�Y���}�Z�ߝ�j~\�6w!\���j�T\����j��\���j�]��T�j�>]� @�j�\]��4�j��]��?�j��]�̩k��^�᫂Y�$`��k��`���� a�6�k�@b��k��b��6$k�Uc���bY�cc�.>	�pc�0����c��/�i�d��+k�7d��#��@d��#!�td��#7k��d��T>k��d��TEk��d�LHOk��e�j�OY��e�URt	�Xf�D;\k��f�Aek�g�E,lk��g���xk��g��@	��g��D�k��g�?�k��g����k��g��D�k�-h��@�k�<h���bY��h�k��h��]g� i��g��j�b��k��k�#��k��l�#��k��m�˫�k�$n�.�k�Pn����k��n�ݬ�k�Po��b�k��o�E�l��o��l� p�L�l��p�)�l�q���g�(q����q��l��q��|��q��|+l�4r��|w!�>r��01l�:,���Pr�t)8l��r��Vt	�s���s��Cl�s��*Ll��s�
*Sl�s���s��Cl�4t��*Ll�xu��dal�s���s��Cl��u��*Ll�s���s��Cl��u��*Ll�:,����u�_jl�:,����u��ql��u����u�GG�0v���9��v�
�w�	���^�w�ϧ�w�	��K�(w���xl�kw���b�sw���bY�:,���w�	w!����5-w!��0-�l��&-�l����5-�l��0-�l�&-�l�w��Z�w���bY:,���w���l�w�	�l
�w�G�l�w�~�l�w�l�w�lTx���l�x�J)�l�x���l�x����l�x����l!�x�_.�#�x�R.�#�x���bY#:,��#w�<w!#y�y��Y$8y��(�y���bY(:,��(�y���[(�y�y�[)�y�<�l*z�,m+z�}m,	z�R�^-	z��^.:,��/z�9m/:,��0(z���`0:,��05z���`0=z���bY0:,��0Iz��m0Xz��1�!�GG2tz���92\{�	N��2w�ϧ2\{�	��K2d{�_�m2�{���b2�{��2�!�GG3�{���93Z|�	�[3w�ϧ3Z|�	��K3d|���$m3�|���b3�|���bY3:,��3�|��m3�|��m4�|��/m5�}��6m6�}�|�Am6�}���Hm7�}���Om8�}�E�Xm9~��bm;(~�]�mm;�~�u�xm=�~�CA�m>�~�TA�m@�~��>�mB4��$�E���B�mE���B�mG��mI������mM������mO����U�Q���E�Q����3�Q����C�mQȀ���Q(���*R|��=U�R���9R����bYR:,��R*����mR2����mS:���mTf��q�mUf����mVn��{�mWv��`�mX:,��Y~��H�^Y:,��Z����nZ���[����"\�����n\���W�]ƃ�.W]ۃ�v@h^��I��_|���Gn_ф���bYa:,��a�|��ma�|��mb�|�Amc�|�md�|��me݄�%nf:,��h��--nh����bYi:,��i���w!i9��\w!jT���w!ko��Lw!l����w!m���w!n����w!oۅ��w!p���Bw!q���w!r��.w!s+��!
w!t+��
w!u8���w!vS���w!wn�� w!x���Ww!y���Vw!z����w!{چ�bw!|���w!}��w!~���w!2��w!���w!����w!�چ�(w!�:,���M��=
w!�:,���h���#�}����bY�:,�������6n�����=n�����Fn���Yn�#��WYn�0���`n�@��WFn���<Yn�#��zYn�0���`n�����Fn����Yn�#���Yn�0���`n�8��Fn�����Yn�����Yn�0��`n�̉��gn����Di���Vhi�����uoi���
ɳ�� ��U����E��(��5��7��%A��F���G9�U��w_9�d��h/9�s���9��q��R9����!9�����L\9����&B�����s\9����+��Ί��[9�ފ��]��̉��nn����Di���Vhi����uoi����
ɳ����U��(��E��7��5����%A��d���G9�s��w_9�U��h/9����9����R9����!9��Ί�L\9�-��&B��=��s\9�M��+��]���[9�m���]��t��k�un���xzn�:,���|��n�����xzn�|��n�����xzn�����������bY�:,�������[����8�n�ċ���:��ޤm)�B����k�K���k�f����n��U��n�v��B�n������n������n�\��ni9����J��n���o.�n�����a�n�T����n������n���"��n�I�����n������bY�:,������ww!������bY�:,������`w!������̏�GG�$����9���
�2����M��	F��n�w�ϧ�M��	��K�X��]��n������b�:,������w�^�Jt5��Q@<��@<@<!X@<��mۆ��ȧ.i___+@w�w��x+q��w��x+qf,�*��*�ӷf,�*�ӷ�*�ӷw�f,�*�w�f,�*���w��E�E�|3@<�E�2����ۆ�@O z�f)b�KZ�>ۆKZb�KZb�KZ&6b�KZ&6�E�xۆcZ���xb�cZ��b�KZ�0�>���O���O��cZcZcZ_mo_2�moL�mo��Ӯmoܶ�]ikmo2�mo	S2�moܶۆ�DKZۆ�h�h�E�x�Qۆu~���� �+�KZKZ%�%�%���(#�(�(#�(��ۆ��KZKZP8�E�,�<�Q�Q�Q�Q�<�<�<�	��<�<�<�<�<�<�<�<�<�<�<�<�<�<�<�<�<�<�<�<2����<�#�,[yv��,�%[yv�[yv��%[yv�W:�<W:W:�<�<@<W:G2�<W:2<W:2<ٶ�<@<�<�<�#�<�#�<�#@<�Qۆ_��_____Կ__�OԿ�O1�T�Կۆ�$�VD� -@<�E -D�ۆ�k>KZKZȧW��E�;�t2<ȧ�!uxȧۆ��k>�AKZKZ�AKZ�=f)T���T���J�T��J��̘A8Կ����J�� �QJ�� ��NDn,2<2<�����Q�Q�Q���Q���Q���<�E1Zw��>�Dۆ_k>KZKZ@<ۆ_KZ7KZ��7KZ�7KZ@�KZۆ�?KZKZKZ��KZ�>T>�E�E�Я�E�E�|��@<@<@<@<@<@<3@<��BB]D�x�x�x�x�xyX�x�xܶ@<8888�@<@<@<@<�E�?@<�O�E@<�t@<�t_=��	���	������	���	��	��	���	���	��	����	������	��9��	����	��	���	������	��	����	����	��	����������	��	��	������	�����	��	���	���	���	��	���	��	����	���	���	��	�����	�����	���	�6�6D%&D%D%D%&D%D%�Q��(#)|]R)|]R.X��A���(#)|]R)|]R.X��A��Q�Q�Q�Q`q�Q�ȧ�ȧڇ�V�V�V�W���y�ȧ�V�V�����*ti�*ti�*t������v��V�)P1�A�Q�)�>�Qf^R+�+@+�O���^wd2~2~3�8*m3�82~��3�8�Q�Q�d,4v�,4v�v�v�
iH~*�
i;hA
i
i��
i��
i
i�
iE
ii��H��+
i��
i��
i�Q�
iB@
i�i�i
i�i�i3��A
i�i
ib_�u�Eʏ
i�wU*ڏ
i�wڏm* *5�}2}2K5@<KV@<����V@<`q�Q�l�W�l��l��d�l�d�l���l�l�d=��l{=�6��l{=�6��l=�6��l�d�l6��{=�T��{̨'j6��6ʷ��J�(�UU#�z{D eU���4�m�eݙ��ݙ�d��Ud e��ݙ��ݙ�d���lvlݙ���lvlݙ�d��	e�#	e	e	e	e	e�#	e	e	e	e[y	e�2	e�:,U3�Q͚͚�d͚�d,4v��:,U�:,U�dD�p�d�&����
i�E
i�E�C
i
iK���
iO=�
i
iR�
iƷDE7E��R�B7��R���R�
i�Ez�W��k
i�i��R����iY,
i
i
i
i��>D
iR��D��
iR��D��
iR�۸��
�
iR��۸�u~
iu~
i��&�Q�(�3�3�3`q�Q�V�W���d�V�W���V�W�d�V�W�ȧ�d�ȧ�ȧڇ�d�ȧڇ�Vj����d[y	e�V�dy�d�VGdj����d�Vj����V-��*�zt3
5�Q�Q:��Q�Q�Q�QSQ�O:��Q�Q�Q�Q�#�#�#�#�#�#�#l�#s#�#�#�#�#�wZ%��wZ�Q�#�#�#�#LF�#��LF�#��P#LFk#�:,U�:,UKe͚͚͚͚͚ ^��/o�͚��Up ^�Go�͚��< 	�ԇ"�< 	�ԇ2<�QUp͚KeUp͚�+�Q�u�u��!|~�Q�Q�Q�Q�Q�Q�Q�Q�Q�Q�Q�Q�u��!|~�Q�Q�Q�Q�Q�Q�Q�Q�Q�Q�Q�Q�QD]R�Q�9�Q�9�Q�6�9
9�9�93��f,�~-�-�/sP7�3/s� � 3
9�82~f,f,�~�6�d�9v�{ZwGdv��o�IGdz�v��o�Iw�{`Gd	z���I�E�p��D�@�D���3O �O �:la��E�E�x�x/,�:��1t���E�u/,/,+@{${`z��~��O ��_�E_�-�=��Q�Q"��Q"��W��!|��z{��I�/P�5���ܶ@<�W&6]R��Ǚ_�E�E�F	e�E�E���}�}Gdv�v�v�op��v���v��E�Zv��b�E%�v��E�Z�Ev�v��E�Zv��E�Zv��E�Zv��E�Zv��Q�Qh_}}�Q}�Q�||�WW�||���t3�|�d�|�|�5w8H%���(#�<�<.X��A���(#ۆ_ۆ_.X��A�޵� ۆD�ۆD�ۆD�ۆD�f)?f)?� f)�D� ۆf)�>� f)�Dۆf)�>f)�>@<f,�*�]RSS5w5w5w5w5w5w%�8H8H]R]R�d۸۸O ��E��E�E��E��E
5?��E���E��V@<D��������X'�'�߶������5w��(�Q�Q�Q�,�d]R]R]R]R]R����%�%�%�%�%�%�%�%�%�%�%�%�%�%�%�%�%�%�%�%�%�%�%�%�%�%�%�%�%����'�'�'��'�'�'��'�'�'��'�'�'��uUp͚�u�uUp͚�u�����W5w�Q��ʷ\z�>�����z�>�%����	��	����	��%���	��	%�%�8H�!16�;1==?=N
N=NN1N5__=__1_5``=``1`5|&|=|"|1|5	���
)�1�9�A�Q�Y�a�i�q�y����������������� ����&��,�A�2Y�aZGi��9��Fi�i��KڅXyڅb��������$��F,څX4��F<څXD��FLڅX��a�����
t��SP�����D�9;������,�FU���W�xU�'�	9F�.���!����i͗W��A�]{Wea�a���y�i�=U��'�o�<a80v	�|Yq�q�0qR�q7|i����xVIKX�Q��������AGIAGa�I�AG�j���_��� ��A?�Yݘ�1�F�d�lڅt��Fd��*��0�6�d�*t��9���O|څ���F����0����9�ݕr�A�E�)c���A{�����Aص�	�x	q!��W�#��^(�9�.��@)9,�9�F)i�9�W9�f�څ����F9������9R2��0����OB�9�>9����)$�����^�����0��D��Y������+�I�?��>D���������څX���F������GY�,M��0�9�/U1a:^q&dd)R.99���v�����B�������9�6�ں�9E�	���	���	xP���j������v����0���#���#�cR
�_R
�=_��(V�5�9����^��O���W0�;`&�Ә,�xU1t�	$F�j�6��=!!�K1�V)�v������X�����������U���ݘ�����Ǡ��څ���F���9���Q�QQ��+�	�@	��+��>D!��0�i���9iA�@		�FIQ�M1�F�SIW�[	�a��I���0I�2I4A��@A�A�<����F��֥��<���<�����s�M���G1�,�!	�y����	��1����<��0��������@QW�Aڅ��F��9�+^�����G��0�y�S�{	Y���څ��F��9!z��$��1	����^��!�K9	�<e�cR�R���$!�څ�,��F4W�*4�^S4�Z,��9�y<�e<�<��ĺ�DڅXL��F�ĺ�<��<sV@<FXF<�vF��#��cR��$	��W04�A	��	�0�&	TuP:	�OK	� 4t	v�y	=U		U��Y��	Y	��	1�X�\�	Y��	��,�	\W�*\�Z\�^Sdص�	9Q_�	d� �	d�Z�?x�	�	�)
���MA�a	�/
y�ya1yP��yɢ�i	A�SA�h�1�1�,�
1	mwy	
�(D�9���
9��9�a:�
:>�l��#Iԝ�
|uP:	Q�OK)�PK�	Q�	�{y=U6� G��Sa��Sa�fi��S�څ����F���9������G��,��'���:��p�9�څ���F���9�������@���y�M�څ����F���9���y���y���y�CHSI��IP����Z�CHS�ӸF��O�I��I���Z�CHS�ӸF��O��9o�U
��0�W�*�Z�^S�^Z�څn
���
�@��9��!�
����
��!�
	�"�
	�"�
��H9�r�9�g69��H9�r�9�g69�=U	�Y��1��
�` �
څ���F$ӸF$�O���9��y��	��	�\�\���
\R*\uP�
\�^Z\mw\���	�<�	R���	�n,�,�@4څX<��Fd���G���I9q� �D��ҙ2��H�	�(Q
�GW��,D�^SLcR�T�^�!!ce�YZ�Y�
R��ZG�����)�����!���G�!wn!h��9�!�-)�)�$ 9g+9�1څb9	�&)
څb9�0�9�O�I�1
;IDSAI��!�+H9�RQ�G[9+ugQAGY�tA���\Q�G�!�jY�_�d���yi>D�d�@l�Zdڅ�t��Ft��9|��څX���FlR*��F�|�,�څX���Flk����,�څ����F���9��>�I�+������@�G��k���څ8��������8YP���9�k���څ8�������9��Z�څX���F9
WA�A��A��&A���@?I�GE�:<���2���N�f�Y��Y��#_�@�l/k���kQ�s��A
�G��@I,�$��!�K$�@!��$څ�,��FY�w,��94�l�<څ8D���4�@D��9i��rL�^���lW�*l�^STڅ\��F\��9luP�
�G�KdW�*d�Z�>D���l�Z�uP�
t�luP:	duP�
t�@��J��Z)�k|�Z|��#|xP��i��w�l�^S���i-���Zd���uP�
��Z��Z��^SY�_�I
�L�څ���F��Z���9�C�i���������^��Ay[�A˺��f0�	�s0�	��Z��^��ӍK|�^S���$��*$�^���k�B�Ox��w�ӸF��O���*��^S��==��C�+�Nt�^�t�����k�Z�	��p��	�=U��A'�&��d��am��5-F�څX���F�]~�OT$Q�J9Q
�/��@����������i��l���}Y
QV���a
!_�q
gV��H������a
ڲ��dv#�څn
����
�ӸF��O����99s=k	�^uy�v	`�M�
�	=U	I%A�yy�h���}��Y���!ΐ�Y=U1�
eG�!��YZ�a����1(^-�9_�J�^S9g3�9��JYM�YW�9��JA��X��9��=l�r9�Y6����Q���Q0��Q�_�Q��a��څX��F$�Z,څ�4��F4��9<څ�D��FD��9L����
ҽ�IpXAUa�^Y��Y��Y��Y�p�Y�p�Y�S�i�Y�i�t�t���i�m�Q�p�iݕ�T�^�\�^�i%���
��	<�Ad�dmwd�@d��d�^�l��*\uP�
\R*lR*t�t�@����[7���Gk�{_k��kt��G<�@l�*�
���I�G�|��څX���F|mw|�@|�^���AϺn�څX���F�,�@�R*��^�|��|څ����F�5-S���9�uP:	��Z��^S�������5-��mwtmw��@��^�������A�&�A
0���*��4��څX��F��@��Aֻ�$�^SQ
t�Q�G�$�^Z$uP�
�z�9�FP ,بF,hP9�^Q Q�0��
Ц $�Z$k��I�G ����څR 4��F$�^S4��9��Q�G� ��G� L�L�@� �
�_� �
)�� <��(.� �
�� D�Z<�@�
��!�
��%!��1!a��>!Q�pD!�
 M!�����
_�S!A˺Y!a�a�cw!4e	�����G�
2d�!A&?"L���9��IA�E"	=�t		�IP"Q�G["Qx+b"�f���kS9��x��	bGs"�\<��`��3���,z"�(1]��"�������>���/�2��"1i��,ji�)�"���"TA�G�"�H��1D�"\.�"\W#d�\�#l�\��-#\�d���
tڅR#|��Fd�^S\�OZ|��9\�h#dW�*\w�t#lW�*\е*\� �#l�^Sd�Zl�ZT�T�#Tе*T� �#TEQ�#T�OS	�t�\k���j��#t��*��#��W�#�5-S���H��#�L �#�L �#��~!�&V�T�OZ	�3�	;��	����AS$�څX���FA`AAG�a�oX�)�x~$!��$Y��1v��$!ڡ�$a��$1r9i;/�$�5-Sa �$�=�$���"���څ����F���9��W�L �$)W��$���9��39��O���%1ZG�ZG��[%!�!�3!�%YڅbA�$%Q�0%Q�^7%��>%��-E%A$7�!�3���^R%�e]h%)sx%�)�~%q�q%q%y�y%L���#�%TڅX���F�څXL�����%IPjI[�%Q�G�%Lڅ����F���9QxVQ:�Q��i{
&���#�ϴQ!Q%&Q�9Q��Q�T �?5&��?5&Q�K9Q�K9Q�L9Q�M<&Q	K�Q�N�QE��څ���F���9��^�����捭&�n<�#��A�&��w�	T��#T�^(Q�T�&|څ��FڅX��F�z:�	�P#'��9��9��PK9�"0'�5-�Q�� �ӸF��O�Q�TN'��0����Q�T�0�$څX,��F�3@�'��#�%��(�'��(�'4�^�t�(tڅ�<��F<��9)D�9���
l���
DڅR#L��FL��9����
TڅR#\��F��^S\��9څ�d��Fl�	Fl��d��9�:�9��^STxP����m)|W�*t�|�t�ZtW�*|�Z|uP�
	@0�)��)�)I�OI�O�)�Qt	����V����)��z*id�eX*!&dd)����*19,�9\<9�`Y�*	j��9	�"*�څ����F�_9*���9�ص�	�� �	d�Q�9�9�*,�$�������l�<�����������*���*��Z��Z�k���uP�
�uP�
��Z�uP�
�_�*Y!u�*�څX���F\W�*\�^S\�Z��*����*���*9�"+9E�+	�P/+���t��yS�4��D+�A`�$AY�\+�Q��+I	�<K\�� �+��|�l������������d�d�^��������@\k���څ8�������9���*:,�,�,-*-[- �-$�-(<.,c.0�.4�.8,/<e/@�/D0HH0L}0P�0T�0X
1\?1`v1d�1h�1lM2p�2t�2x 3|e3��3��3�4�O4��4��4�45�U5��5��5�6�G6��6��6��6�E7��7��7�8�_8��8��8��8�U9��9��9��9�+:�N:��:��:��:;];�;�;:<�<�<3= L=${=(�=,�=0>4Q>8�><�>@2?Dw?H�?L@P`@T�@X�@\!A`fAd�Ah�Al5BpzBt�Bx�B|1C�`C��C��C�D�HD��D��D��D�DE��E��E��E�,F�gF��F��F�&G�IG�tG��G��G�7H$�H(�HT�Hh�Hl�Hp�Ht�Hx�H|�H��H��H��H��H��H��H��H�I�I�I�*I��H��H��H��H�/I�\I�}I��I��I��I�I0JJ4qJ8�J<�J@KD-KHZKL�KP�Kx*I|�H��K��K�=L��L��H��L��L *I$�H@*ID�HH�HL�HP�H�M��M�N�N�*N�3N�@N�KN�vN��N��N �N$O(mO,�O0#P4�P8�P<@Q��Q�Q�Q�Q�Q�Q�Q�Q�Q �Q$�Q(�Q,�Q0�Q4�Q8�Q<�Q@�QD�QH�QLRPRT
RXR\R`Rd!Rh&Rl+Rp0Rt5Rx:R|?R�DR�IR�NR�SR�XR�]R�bR�gR�lR�qR�vR�{R��R��R��R��R��R��R��R��R�R
SS=SZSPyST�SX�S\�S`
Sd�Sh�Sl�SpTt!TxDT|OT�dT��T��T*I�H�H*I�H �H$�H(�H,�H0�H4�H8�H<�H@�H	*I	�H	�H`	*Id	�Hh	�Hl	�H�
*I�
�H�
�H�
�H�
�H�
�H�
�H�
�H�
�H�
�H�
*I�
�H�
�H�
�H�
�H�
�H�
�H�
�H�
�H�
�H�
�H�H.�H.�p.�p.#�H.+�p.3�p.;�H.C�p.K�p.S�p.[�p.c
q.k%q.sEq.{zq.�zq.��q.��q.��p.��q.��q.�u.�5uC��vc��v���H�#�v �>uC3�H��H�3�p�3�p�{�p	{�p#	{�pC	{�pc	��H�	��H�	��H�	��H�	��H�
��H�
��HC��Hc��H���H���H���H���H���H��H#��Hd��H�k�v���H���H
��HC
��Hc
��H�
��H�
��H�
��H�
��H�3�p���H#��Hc��H���H���H�3�pa��H���H� ��H(��H!(��H*��H!*��Ha-��H ;��H@;��H`;��H�;��H�A3�p`B��H�B��H�G+�HH+�H H+�H@H+�H`H+�H I3�p@I3�p`I3�p�I3�p�I3�p�K��u�K��u�L�H�O��H�O��H�T��HU��HY��H Y��H@Y��H`Y��H�\��H ]��H@]��H$_��H�fs�H�ms�H���H���H���H ��H@��H`��H���H���H��H ��H`��H���H���H���H��H��H ��H`��H���H���H���H��H���H���-v$���Hd���H����H��H��H���H���H���H��H��HĨ��Hz��)��8l��Rr����)/5j~����Eci�'hnw��d����	'bt�����		C	L	�	�	�	9
H
N
U
^
j
s
|
�
�
�
�
�
�
�
�
�
&0>]lr����

�
�
�
!;����,n|���{���������a��'p���$0Udv�����Dc~��	9?|�����&4r�Fh�+Jg�����
/i�@+ 3 e � e!|!�!�!�!�!."U"j"�":#�#�#�#�#�#�#�#I$e$k$�$�$�$%%K%Z%a%o%�%�%�%�%&H&s&�&�&�&*':'V'r'�'�'�'�'�'�'�'(+(=(Q(�(	));)A)R)f)s)�)�)�)�)�)&*@*P*f*l*�*�*�*�*�*7+�+�+�+�+�+�+�+�tUx	

 !./02<`c!e"g$m&r's)w,|0}1~2�3�4�8�:�;�=�>�?�@�N�V�_�`�c�e�i�p�q�rx|
>toDFo��o�,oW)o��o��%o�2o�2oW�)oց.o�Q%o�~3o_9oW)o_?o�REoІKoW)oց.ohEo_Po_Vo�o��o #o�E\o�,oE�ao_qo��o_wo�E}o_�o<o
�%o�R�o|R�oW1o1o��%o��%o�0o%<oE:o_�o_�o_�oV�%ol�}oI<}o�}o�}o��}o��}o̜}o��}oiU}o�_}o��o��om�o(��o0�o���oq7�o�j�o��o���of��o柡ok�o�	�o��o��o|��o	��oj��o���oߠ�o���o#��oS��o�"�o���oa��o���o䐡o㛡o5��o�_�o�G�o_�o��o\��ol��o_�oӳ�oOqov�o�Vo�%o�)qo>1o�A}o���oО�o���o�)�o�>}o��o-��o���o��od~Po}m�ob(�o�%oVo�o:<o���o��pOqo��od~Pomp�%o�(�oOqov�o"�p��pDF$p�:o2e*p/p0pCp6pͳ�oVo�o!5o�Ao�G%o{_%ol/%o�%oS%ot9oP\%oABow\%o+o�[%o�]oTb<p�`<p}a<p�b<p@b<p�`<pka<p�b<p�b<p�a<pa<pb<p".Bp�Uo<o�-o�`o�Uoo|-o�`oY�o�7oMokI%ohb<p�`<p�a<p�a<p�a<pb<pzb<pc<pc<p[a<pqc<p,a<pZc<p".HpVo�o�3oE7o�.%oF=o�W�o�c�o�c�oW-�o��%o$%o�%o!��o'�Np�.}o/}o�o'�Npu�Rp'�Np��Xp�$oVo�o�3o�Ccp�%o��ipÔop2Wovxpͳ�oVo�o!5o�Ao�G%o{_%ol/%o�%oS%ot9oP\%oABow\%o+o�[%o�]oͳ�oVo�o!5o�Ao�G%o{_%ol/%o�%oS%ot9oP\%oABow\%o+o�[%o�]o���pW��p���p���pri%oϰ�p'�Np����	
 &')*+,34W!\#]%^%_'`)a+t-{/~11�3�3�5�5�7�7�9�9�;�=�?�A�C�E�G�I�K�M�O�Q�S�U�W�Y�[]
_ac,e-g.i/k0m1o2q3s4u5wNyO{d}kv�������������������������������������������������������������������������������������������������������������?�@�A�B�C�G�H�m�|�}�~������	�	���
�
����	

!#%')+-/1357#9$;%=&?'A(C)E*G+I,K-M.O6Q7S8S9U:U;W<W=Y>Y?[@[A]B]C_D_EaFaGcHcIeJeKgLgMiNi[k\m]o^q_s`uawbyc{d}ef�g�o�p�q�r�s�t�u�v�w�x�y�z�{�|�}�~������������������������7�8�S�U�[�]�e�p�v�w�x�y�}��������������������������������������������������������������������������	�	



$&N,9N.;N2=N4?N6AN8CN:E_�9_�;_�O_�?_�A_�Q_�E`�9`�;`�S`�?`�A`�U`�E|@
9|B
;|H
W|J
?|L
A|N
Y|P
E=Ohpw~������!Zc���7�� >���08LU���=E���1	�	�	�
�
	�����;DXam������K
_
z
�
�
u~�&���p��������� ,DWco����d���QZf}���Cs�W`����;OY%/@}�
"+4=��^����S]�����G��������� \ � !"�"�"###H#^#�#�#�#�#$7$@$O$�$�%�%&a&j&�&�&'''�'�'�'�'$(�(�(�(�(�(�(�)�)0*F*\*r*|*�*�*�*�*�*K+w+�+�+�+,���),!`,u,_,2�,�E,�], ,j,7w,n����O<����|����LMNOP
QRSTUVWX%Y'Z'['\,],^,_,`,a.b1c1d1e1f1g1h1i3j3k3l6m6n9o:p;q;r;s;t;uBvBwDxDyEzK{c|c}xh��h� �J�^
��7�-�q����}�}������/��W/�,�
qq*,/,5,c,�,��������,��,�aae�
g�
���	�,�C������e��
	�, �f,�	�O�O���
������
�����"a%"�
�"9�"C�
��
,�#	�
�f�.$,f/B&��',�',K(	�C	�*��*i	U+k	U+k	�+o	�
o	�+6�
6�+<>9__31_10<InternalSingularize>b__31_10<InternalPluralize>b__29_10<get_Errors>d__20<>c__DisplayClass20_0<>9__0_0<.ctor>b__0_0<>c__DisplayClass0_0<>9__11_0<GenerateCode>b__11_0<>c__DisplayClass11_0<>9__31_0<InternalSingularize>b__31_0<>c__DisplayClass31_0<>9__41_0<CreateCodeGeneratorType>b__41_0<WriteExtendedPropertyAttributes>b__41_0<>c__DisplayClass51_0<>9__1_0<CreateEdmItemCollection>b__1_0<>9__12_0<.cctor>b__12_0<LoadViewDetails>b__12_0<>9__22_0<GenerateCodeFor1_1Schema>b__22_0<>9__13_0<CreateFunctionImportStructuralTypeReaderMethod>b__13_0<GenerateCode>b__13_0<LoadTableDetails>b__13_0<>9__53_0<CreateEdmProperties>b__53_0<>9__14_0<LoadFunctionReturnTableDetails>b__14_0<>9__4_0<CreateStoreSchemaConnection>b__4_0<>9__15_0<GenerateCode>b__15_0<LoadRelationships>b__15_0<>c__DisplayClass15_0<>9__55_0<CreateEndMultiplicityOverride>b__55_0<>9__5_0<.ctor>b__5_0<>9__16_0<HandleValidationErrors>b__16_0<>c__DisplayClass16_0<>9__6_0<CreateStorageMappingItemCollection>b__6_0<>9__37_0<WriteEntityContainerElement>b__37_0<>9__7_0<EmitFactoryMethod>b__7_0<>9__18_0<.ctor>b__18_0<>9__38_0<MapFunctions>b__38_0<>c__DisplayClass38_0<>9__29_0<InternalPluralize>b__29_0<>9__39_0<CreateAssociationType>b__39_0<>9__9_0<GenerateCode>b__9_0<>c__DisplayClass9_0<>9__0<InternalGenerateCode>b__0<CreateEntityType>b__0<GetDirectSubTypes>b__0<IsAtLeastOneColumnFKInBothAssociations>b__0<GenerateViews>b__0<GetSchemaElement>b__0<DoesWordContainSuffix>b__0p0constraint0<>9__31_11<InternalSingularize>b__31_11<>9__29_11<InternalPluralize>b__29_11T1EdmxNamespaceUriV1MementoV1FunctionDetailsReaderV1get_UnableToGenerateForeignKeyPropertiesForV1<>9__31_1<InternalSingularize>b__31_1<>c__DisplayClass51_1get_EdmVersion1_1<>9__12_1<.cctor>b__12_1<LoadViewDetails>b__12_1<>9__13_1<LoadTableDetails>b__13_1<>9__53_1<CreateEdmProperties>b__53_1<>9__14_1<LoadFunctionReturnTableDetails>b__14_1<>9__4_1<CreateStoreSchemaConnection>b__4_1<>9__15_1<LoadRelationships>b__15_1<>9__55_1<CreateEndMultiplicityOverride>b__55_1<>9__38_1<MapFunctions>b__38_1<>9__29_1<InternalPluralize>b__29_1<>9__39_1<CreateAssociationType>b__39_1<i>5__1<CreateEntityType>b__1Func`1ISchemaElementLookUpTable`1Nullable`1IEnumerable`1IOrderedEnumerable`1Stack`1ICollection`1ReadOnlyMetadataCollection`1EnumerableRowCollection`1ReadOnlyCollection`1IComparer`1IEqualityComparer`1IEnumerator`1HashSet`1IList`1get_Template_GeneratedCodeCommentLine1get_Item1Version1<>7__wrap1str1constraint1<>m__Finally1<>9__29_12<InternalPluralize>b__29_12<InternalSingularize>b__12Int32T2VBTemplateCodeGenResourceV2CSharpTemplateCodeGenResourceV2_vbCodeGeneratorTypeV2_csharpCodeGeneratorTypeV2EdmxNamespaceUriV2CreateVBCodeGeneratorV2CreateCSharpCodeGeneratorV2<>9__31_2<InternalSingularize>b__31_2<>9__12_2<.cctor>b__12_2<LoadViewDetails>b__12_2<>9__13_2<LoadTableDetails>b__13_2<>9__14_2<LoadFunctionReturnTableDetails>b__14_2<>9__15_2<LoadRelationships>b__15_2<>9__29_2<InternalPluralize>b__29_2<>9__39_2<CreateAssociationType>b__39_2<MapFunctions>b__2Func`2Tuple`2Memoizer`2KeyValuePair`2BidirectionalDictionary`2get_Template_GeneratedCodeCommentLine2get_Item2Version2<>7__wrap2str2<>m__Finally2<>9__31_13<InternalSingularize>b__31_13<>9__29_13<InternalPluralize>b__29_13<GetSourceTypes>d__3390EEE9F1BE125B634A197AA7BD83E6811BE8B6F3VBTemplateCodeGenResourceV3CSharpTemplateCodeGenResourceV3_vbCodeGeneratorTypeV3_csharpCodeGeneratorTypeV3EdmxNamespaceUriV3MementoV3FunctionDetailsReaderV3CreateVBCodeGeneratorV3CreateCSharpCodeGeneratorV3<>9__31_3<InternalSingularize>b__31_3<>9__12_3<.cctor>b__12_3<LoadViewDetails>b__12_3<>9__13_3<LoadTableDetails>b__13_3<>9__14_3<LoadFunctionReturnTableDetails>b__14_3<>9__15_3<LoadRelationships>b__15_3<>9__38_3<MapFunctions>b__38_3<>9__29_3<InternalPluralize>b__29_3<>9__39_3<CreateAssociationType>b__39_3Func`3get_Template_GeneratedCodeCommentLine3StoreSchemaMappingVersion3StoreSchemaDefinitionVersion3ConceptualSchemaDefinitionVersion3p3<>9__31_14<InternalSingularize>b__31_14Int64<>9__31_4<InternalSingularize>b__31_4<>9__38_4<MapFunctions>b__38_4<>9__29_4<InternalPluralize>b__29_4<>9__39_4<CreateAssociationType>b__39_4p4<>9__31_5<InternalSingularize>b__31_5<>9__29_5<InternalPluralize>b__29_5Action`5p5__StaticArrayInitTypeSize=6<>9__31_6<InternalSingularize>b__31_6<>9__29_6<InternalPluralize>b__29_6<>9__31_7<InternalSingularize>b__31_7<>9__29_7<InternalPluralize>b__29_7<SplitViewStrings>d__28get_UTF8<>9__31_8<InternalSingularize>b__31_8<>9__29_8<InternalPluralize>b__29_8<GetViewStringsAppendToStringBuilder>d__29<>9<>9__31_9<InternalSingularize>b__31_9<>9__29_9<InternalPluralize>b__29_9<Module><PrivateImplementationDetails>FK_SCHEMAPK_SCHEMANormalizeForVBDoFixUpsForVBGCIS_SERVERGENERATEDRELATIONSHIP_IDSCALEIS_NULLABLEFK_TABLEPK_TABLEDEFAULT_NAMESPACE_NAMERELATIONSHIP_NAMEERRORCODE_MAPPINGALLQUERYVIEWATCOMPILETIMEDATA_TYPEget_EOFFK_CATALOGPK_CATALOGMAXONELINELENGTHMAX_LENGTHget_NamespaceURIIsFkPartiallyContainedInPKORDINALFK_COLUMNPK_COLUMNDATETIMEPRECISIONSystem.IODoFixUpsForCSTPROC_SCHEMA_INDEXPROC_ISNILADIC_INDEXPROC_ISCOMPOSABLE_INDEXPROC_NAME_INDEXPARAM_NAME_INDEXPARAM_TYPE_INDEXPROC_RET_TYPE_INDEXPROC_ISAGGREGATE_INDEXPROC_ISTVF_INDEXPROC_CATALOG_INDEXPROC_ISBUILTIN_INDEXPARAM_DIRECTION_INDEXNAMESPACE_NAME_SUFFIXENTITY_CONTAINER_NAME_SUFFIXCONTAINER_SUFFIXIS_PRIMARYKEYIS_IDENTITYvalue__GenerateCodeFor1_1Schemaget_FKSchemaset_FKSchema_columnFKSchemaget_PKSchemaset_PKSchema_columnPKSchemaget_Schemaset_Schemaget_Template_UnsupportedSchemaCheckValidSchemaIsValidSchema_sourceSchemaWriteStoreSchemaNullAdditionalSchemaInternalWriteModelSchemasourceEdmSchema_columnSchema_schemaSystem.DataDoGenerateStoreMetadataInternalGenerateMetadataTemplate_GenCommentAddToMethodVbSystem.WebmscorlibrbTemplateCodeGenerators.VBCodeGenTemplateV5.0.vbTemplateCodeGenerators.VBCodeGenTemplate.vb<>cget_IsNiladicVBMarkPropertyGetAsPublicCSMarkPropertyGetAsPublicVBMarkPropertySetAsPublicCSMarkPropertySetAsPublicCodeGenerationValueAccessibilityPublicSystem.Collections.GenericComputeFromStringGenericgenericMicrosoft.VisualBasicCSMarkClassAsStaticorderByFuncget_CurrentManagedThreadId<>l__initialThreadIdget_RelationshipIdset_RelationshipId_columnRelationshipIdPrivateMemberPrefixIdReadLoadEdmFunctionPayloadAddreplacedget_EntityStoreGeneratorSchemaNotLoadedget_EntityModelGeneratorSchemaNotLoadedInterlockedVBMarkOverrideMethodAsSealedCSMarkOverrideMethodAsSealedLazyLoadingEnabledCannotCreateEntityWithNoPrimaryKeyDefinedCodeGenNamespaceCannotBeDeterminedInvalidSchemaEncounteredget_IsRequiredaccumulatedadd_OnTypeGeneratedremove_OnTypeGeneratedget_IsServerGeneratedset_IsServerGenerated_columnIsServerGeneratedadd_OnPropertyGeneratedremove_OnPropertyGeneratedget_SingleStoreEntityContainerExpectedVBMarkPropertyGetAsProtectedCSMarkPropertyGetAsProtectedVBMarkPropertySetAsProtectedCSMarkPropertySetAsProtectedCodeGenerationValueAccessibilityProtectedIsClassWantedNotImplementedIsLanguageSupportedTargetVersionNotSupportedClientAutoGenNotAllowedSystem.Collections.SpecializedIsCapitalizedfdget_EdmSchemaNotValidParameterDirectionNotValidSourceSchemaIsInvalidCodeGenAdditionalEdmSchemaIsInvalidCodeGenSourceFilePathIsInvalidappendToFrontIfFirstCharIsInvalidExcludedColumnWasAKeyColumnEntityIsInvalidVoidget_GuidGetCodeExpressionFromGuidNewGuid_guid<Service>k__BackingField<Culture>k__BackingField<GenerateForeignKeyProperties>k__BackingField<FirstToSecondDictionary>k__BackingField<SecondToFirstDictionary>k__BackingFieldPropertyInfoFieldCodeMemberFieldCreateEntitySetFieldEmitFieldAppendChildstoreEndfkEndpkEndTrimEndfromEndCreateAssociationEndReadToEndtoEndtargetRelationshipEndAddAssociationSetEndGetStoreAssociationSetEndstoreAssociationSetEndCreateModelAssociationSetEndStoreAssociationSetEndToModelAssociationSetEndGetFromAssociationSetEndGetAssociationSetEndassociationSetEndDbCommandCreateFilteredCommandCreateCommandEntityCommand_commandstringToAppendDateTimeKindget_PrimitiveTypeKindTryGetPrimitiveTypeKindget_BuiltInTypeKindGetCollectionKindcollectionKindSpecifyKindget_PropertyKindkindTSecondExistsInSecondsecondInvalidKeyTypeFoundOneToOneAssociationFoundEdmSchemaFileNotFoundTableReferencedByTvfWasNotFoundTableReferencedByAssociationWasNotFoundDirectoryNotFoundget_Methodset_MethodGetAddMethodEndMethodreferenceMethodGetRemoveMethodIntializeMethodBeginMethodCreateViewReturnMethodCodeMemberMethodCreateFunctionImportStructuralTypeReaderMethodEntityClient_ReturnedNullOnProviderMethodCreateAndAddGetViewAtMethodGetGetMethodEmitGetMethodGetSetMethodFixMethodIncludeFieldInFactoryMethodget_Template_RegionFactoryMethodEmitFactoryMethod_methodAddWordTryInflectOnSuffixInWordoperationOnWordIsNoOpWordnewWordprefixWordGetSuffixWordsuffixWord_CSClassKeyWordIndexOfKeywordkeywordGetSchemaXsdReplaceget_DataSpacedataSpaceIsNullOrEmptyOrWhiteSpaceIsWhiteSpaceget_NamespaceGetStoreSchemaNamespaceGetMappingSchemaNamespaceGetEdmSchemaNamespaceGetSchemaNamespaceschemaNamespaceAddNamespaceEdmReservedNamespaceCodeNamespace_codeNamespaceget_StoreNamespace_storeNamespaceValidateNamespaceAdoFrameworkNamespace_xmlNamespaceAdoFrameworkMetadataEdmNamespaceedmNamespaceIsSystemNamespaceEdmAnnotationNamespace_hasAnnotationNamespaceEntityStoreSchemaGeneratorNamespacehasNamespaceAdoAttributeDataClassesNamespaceAdoFrameworkDataClassesNamespaceTryGetObjectNamespaceobjectNamespaceAdoEntityClientNamespaceGetProviderSchemaMetadataWorkspaceCreateMetadataWorkspacemetadataWorkspaceworkspaceget_Serviceset_ServiceCreateServiceget_PluralizationServiceset_PluralizationService_irregularVerbPluralizationService_wordsEndingWithSePluralizationServiceEnglishPluralizationService_assimilatedClassicalInflectionPluralizationService_classicalInflectionPluralizationService_wordsEndingWithSisPluralizationService_irregularPluralsPluralizationService_wordsEndingWithSusPluralizationService_oSuffixPluralizationService_wordsEndingWithInxAnxYnxPluralizationServiceUniqueIdentifierServiceuniqueIdentifierServiceGetServiceserviceget_InstanceCreateInstance_instanceget_TypeReferenceGetLeastPossibleQualifiedTypeReferenceGetFullyQualifiedTypeReferenceCodeTypeReferenceGetCollectionTypeReference_typeReferenceAddArtifactReferenceget_TypeSource_typeSourceCompileAssemblyFromSourceget_PropertySource_propertySourceXmlSchemaResourceCreateEmbeddedResourceSetupEmbeddedResourcedeleteBehaviorOverrideCreateEndMultiplicityOverrideendMultiplicityOverridemultiplicityOverrideGenerateVBCodeInternalGenerateCodeGetHashCodeGenerateCSharpCodeget_ErrorCodeModelBuilderErrorCodedefaultErrorCodeerrorCodeget_ModeFileModeget_ProcParameterModeTryGetParameterModestorageSchemaNodeconceptualSchemaNodeSelectSingleNodeWriteNodemappingNodeXmlNodeImportNodemodeExcludeDbCommandTreeDbQueryCommandTreeget_TypeUsagestoreTypeUsageCreateStringTypeUsageGetModelTypeUsageGetScalarFunctionTypeUsagetypeUsageget_MessageCombineErrorMessageerrorMessagemessageusageget_Languageset_Language_languageAddRangeColumnFacetValueOutOfRangeArgumentOutOfRangeDisallowReturnTypeChangeCompareExchangeTryAddNameToCacheAddElementNameToCachecacheEndInvokeBeginInvokeget_Scaleset_Scale_columnScaleget_FKTableset_FKTable_columnFKTableget_PKTableset_PKTable_columnPKTableget_TableLoadDataTableget_NameTableXmlNameTable_columnTableMissingTvfReturnTableGetAssociationSetEndForForeignKeyTableget_VariableGetViewStringBuilderVariableget_Nullableget_NonNullableIsAtLeastOneColumnOfBothDependentRelationshipColumnSetsNonNullable_nonNullableget_IsNullableset_IsNullable_columnIsNullableAreAllFkKeyColumnsNullableAreAnyFkKeyColumnsNullable_nullableIEnumerableAsEnumerableFunctionImportMappingComposableget_IsComposableIDisposableset_GenerateExecutableAreTypeAndSetAccessCompatibleProviderIncompatibleDoubleRuntimeFieldHandleRuntimeTypeHandleGetTypeFromHandleSingleget_CodeGenSourceFilePathIsNotAFileAddFileOpenFileSaveXmlReaderToFileCopyFileget_FromRoleget_ToRoleTupleset_BracingStyleget_PropertyFQNameget_Nameset_NameCreateValidEcmaNameunqualifiedNameTryGetAdjustedNameTryGetReservedNameget_FieldNameget_ComplexPropertyInitializedFieldNameget_BackingFieldName_backingFieldNameset_MethodNameReportPropertyChangedMethodNameGetValidValueMethodNameSetValidValueMethodNameReportPropertyChangingMethodNameOnChangedPartialMethodNameOnChangingPartialMethodNameGetViewAtMethodNameDetachFromParentMethodNamemethodNameget_NamespaceNameCreateValidNamespaceNamestoreNamespaceNamecsdlNamespaceNameCreateValildModelNamespaceNamexmlNamespaceNameget_SourceEdmNamespaceNameget_SourceObjectNamespaceName_namespaceNameGetStoreSchemaXsdResourceNameGetMappingSchemaXsdResourceNameGetEdmSchemaXsdResourceNameresourceNamenodeNameget_TwoLetterISOLanguageNameget_TableNameset_TableNameGetMostQualifiedTableNamestoreTableNametableNameget_FileNameset_FileNameGetTempFileNameGetFileNameoutputFileNameVBTemplateCodeGenV3TypeNameCSharpTemplateCodeGenV3TypeNameFQMetaDataWorkspaceTypeNameviewStorageTypeNameBaseTypeNameVBTemplateCodeGenTypeNameCSharpTemplateCodeGenTypeNameGetTypeNameGetEntityTypeNametypeNamestoreNameget_ProcedureNameEntityStoreSchemaGeneratorSchemaAttributeNameEntityStoreSchemaGeneratorNameAttributeNameEntityStoreSchemaGeneratorTypeAttributeNameViewGenerationCustomAttributeNameGetFullyQualifiedCodeGenerationAttributeNameTranslateFacetNameToAttributeNameattributeNameShouldReserveNameFQAdoFrameworkNameget_LocalNameget_IsSpecialNameCreateModelNameget_FullNameCreateFullNameGetFullNameGetExtentFullNameextentFullNameVerifyComplexObjectIsNotNullNameparamNameFQAdoFrameworkMetadataEdmNameitemNameget_ColumnNameset_ColumnNamegetColumnNamecolumnNameStoreFunctionNameget_MissingDocumentationNoNameget_RelationshipNameset_RelationshipName_columnRelationshipNameComplexPropertyInitializedNameFromPropNameFieldNameFromPropNameTemplate_ConflictingGeneratedNavPropNamepropNamepropertyFqNamefqNameIsNameAlreadyAMemberNameDoesTypeReserveMemberNameStoreEntityContainerNameDuplicateEntityContainerNamenewModelEntityContainerName_modelEntityContainerNameEdmEntityContainerNameentityContainerNameget_ParameterNameset_ParameterNameUnableToGenerateFunctionImportParameterNameFixParameterNameparameterNameAncestorClassDefinesNameFQAdoFrameworkDataClassesNameIEntityWithRelationshipsTypeBaseClassNameDuplicateClassNameEntitySetClassNameObjectResultClassNameNewContextClassNameget_PropertyClassNameclassNameGetNameGetEntitySetNameget_FacetNamefacetNameSplitNameget_ProviderInvariantName_providerInvariantNameFQAdoEntityClientNameEdmxRootElementNameelementNamefunctionImportNameget_DisplayNameAssemblyNameget_PropertyNameTrySplitExtendedMetadataPropertyNameGetFullyQualifiedPropertyNamegeneratedPropertyNameValuePropertyNameGetNavigationPropertyNameViewCountPropertyNameSearcherGetContextPropertyNameEntityGetContextPropertyNameget_EntityPropertyNamepropertyName_nameget_DateTime_dateTimeget_LineReadLineAppendLineWriteLineget_NewLineCombinelineNoneClonescopeget_Typeset_TypeSchemaTypeget_DataTypeset_DataTypeUnsupportedDataType_columnDataTypeUnsupportedFunctionReturnDataTypeUnsupportedFunctionParameterDataTypedataTypeDbTypeapplyToSpecificTypeMakeGenericTypeStructuredTypeUnsupportedTypefieldTypeset_CommandTypeNullReferenceTypeGetReferenceTypeget_NodeTypeXmlNodeTypeModelGeneration_UnGeneratableTypeNonSerializableTypeIsStoreTypeget_BaseTypeset_BaseTypeeventReturnedBaseType_declaringTypeUsesStandardBaseTypeAssignBaseTypeGetBaseType_baseTypecreateTypeattributeTypeget_IsValueTypeTryGetStorePrimitiveTypeGetEdmPrimitiveTypeIsPrimitiveTypeprimitiveTypeOfTypeRefTypeMappingTypeget_DeclaringTypeCreateConstructorForViewStoringTypeAdoFrameworkTypeIsNominalTypeStructuralTypestructuralTypeGetCSDeclTypeGetModelTypemodelTypeTemplate_DuplicateTopLevelTypeget_EdmTypeAdoFrameworkMetadataEdmTypeGetEdmTypeedmTypeGetBuiltInTypestoreAssociationTypeCreateAssociationTypeCreateModelAssociationTypeStoreAssociationTypeToModelAssociationTypeassociationTypeAccessViolationTypeIsEnumerationTypeIsCollectionTypeGetCollectionTypeIsCatchableExceptionTypeget_ReturnTypeset_ReturnTypeAddTvfReturnTypeTryGetTvfReturnTypetvfReturnTypeGetReturnTypeCannotChangePropertyReturnTypepropertyReturnType_returnTypeUnsupportedDataTypeUnknownTypetoTypeFixUpTypeget_RelationshipTypeset_RelationshipTypeinnerTypeget_ParameterTypeDetermineParameterTypeget_ClrTypeInvalidInterfaceSuppliedForTypeInvalidAttributeSuppliedForTypeInvalidMemberSuppliedForTypeComputeNullableForTypeComputeForTypeMissingGenerationPatternForTypeAddErrorsForTypeVerifyLanguageCaseSensitiveCompatibilityForTypeCreateCodeGeneratorTypeCodeBinaryOperatorTypeAdoFrameworkDataClassesTypeComplexTypeBaseClassTypeEntityTypeBaseClassTypeget_ObjectTypeDbObjectTypedbObjectTypeGetSourceNameFromObjectType_objectTypeGetTypeAdoEntityClientTypeget_ClrEquivalentTypeget_ElementTypegetElementTypeelementTypeGetVBStatementTypeThreadAbortTypenewTypeCreateTvfReturnRowTypeGetRowTypeStackOverflowTyperowTypeIsComplexTypecomplexTypeIsValidKeyTypeOutOfMemoryTypeSecurityTypestoreEntityTypeCreateEntityTypefkEntityTypepkEntityTypeCreateModelEntityTypeStoreEntityTypeToModelEntityTypeGetEntityTypeentityTypeget_PropertyTypepropertyTypem_typeFileShareWhereSystem.CoreInsertBeforestoreHashOverMappingClosureget_Cultureset_Cultureget_InvariantCultureget_CurrentCulturecultureCaptureMethodBaseEntityTypeBaseInternalDataCollectionBasePropertyEmitterBaseAddEntitySetBaseentitySetBaseget_OrdinalIgnoreCaseCamelCaseItemExistsWithDifferentCaseEntitySetExistsWithDifferentCasePropertyExistsWithDifferentCaseCloseSystem.IDisposable.DisposeTryParseFunctionOrderByClauseorderByClauseSaveAssociationForCollapsedAssociationCandidateParseAndValidateCreateMulticastDelegateget_IsIsAggregateget_Template_CurrentlyRunningTemplateLoadMethodSessionState<>1__stateEvaluateToSeparatedStringPrivateVBMarkPropertyGetAsPrivateCSMarkPropertyGetAsPrivateVBMarkPropertySetAsPrivateCSMarkPropertySetAsPrivateget_IsPrivateCodeGenerationValueAccessibilityPrivateRELATIONSHIP_IsCascadeDeleteget_RelationshipIsCascadeDeleteset_RelationshipIsCascadeDelete_columnRelationshipIsCascadeDeletenamespaceToWriteMetadataArtifactLoaderCompositeget_IsCompositeCompilerGeneratedAttribute_GeneratedCodeAttributeEmitGeneratedCodeAttributeDebuggerNonUserCodeAttributeAttributeUsageAttributeNeutralResourcesLanguageAttributeDebuggableAttributeget_IsComposableAttributeAddBrowsableAttributeComVisibleAttributeAssemblyKeyFileAttributeEmitSimpleAttributeAssemblyTitleAttributeget_StoreFunctionNameAttributeIteratorStateMachineAttributeEmitSchemaTypeAttributeGetCodeAccessibilityTypeAttributeXmlIgnoreAttributeSoapIgnoreAttributeget_AggregateAttributeDebuggerStepThroughAttributeXmlAttributeget_BuiltInAttributeDebuggerHiddenAttributeAssemblyDelaySignAttributeExtensionAttributeAssemblyFileVersionAttributeAssemblyInformationalVersionAttributeSatelliteContractVersionAttributeget_NiladicFunctionAttributeEDesignResDescriptionAttributeAssemblyDescriptionAttributeBuildProviderAppliesToAttributeAddDataMemberAttributeGetAccessibilityCsdlStringFromMemberAttributeDefaultMemberAttributeGetCodeAccessibilityMemberAttributeAssemblyDefaultAliasAttributeget_ParameterTypeSemanticsAttributeSecurityRulesAttributeFlagsAttributeDefaultDllImportSearchPathsAttributeCompilationRelaxationsAttributeAllowPartiallyTrustedCallersAttributeAssemblyProductAttributeAssemblyCopyrightAttributeCLSCompliantAttributeSecurityTransparentAttributeget_CommandTextAttributeDebuggerDisplayAttributeParamArrayAttributeAssemblySignatureKeyAttributeAssemblyCompanyAttributeEDesignResCategoryAttributeRuntimeCompatibilityAttributeattributeReadByteWriteByteget_Valueset_ValueAddValueGetSecondValuesecondValueBaseValuemetadataArtifactProcessingValueStonglyTypedAccessToNullValuenullValueGetEnumValueget_MinValueset_DescriptionValueget_HasValueTryGetValueSetValueIsUnboundedFacetValueget_DefaultValueGetCodeExpressionFromDateTimeDefaultValueGetCodeExpressionFromTimeSpanDefaultValueGetDefaultValueGetCodeExpressionFromDateTimeOffsetDefaultValueGetFirstValuefirstValueget_MaxValueGetTypeAccessibilityValueGetAccessibilityValuevalueToAppRelativeIsUninflectiveget_IsLanguageCaseSensitive_isLanguageCaseSensitivecaseSensitiveRemoveInitializeSuppressFinalizeInternalPluralizeCapitalizeInternalSingularizeEntityizeLastIndexOfget_FieldRefget_ComplexPropertyInitializedFieldRef_complexPropertyInitializedFieldRef_fieldRefget_ThisRef_thisRefCreateEdmStructuralObjectRefget_IsTvftagSystem.ThreadingOrderByDescendingDbExpressionBindingset_EncodingSystem.Runtime.Versioningget_IsWarningset_IsWarningSystem.Data.MappingStoreSchemaMappingInternalWriteStorageMappingICustomPluralizationMappingStorageEntityContainerMappingstorageEntityContainerMappingUnsupportedQueryViewInEntityContainerMappingTryGetFunctionImportMappingStrongTypingget_String_onContextCreatedStringMembersToCommaSeparatedStringGetLocalizedStringWriteStringWriteAttributeStringGetAttributeValueStringComputeFromStringset_ConnectionStringconnectionStringToStringGetString<>3__largeViewStringviewString_stringSubstringSystem.Web.Hostingget_FKCatalogset_FKCatalog_columnFKCatalogget_PKCatalogset_PKCatalog_columnPKCatalogget_Catalogset_Catalog_columnCatalog_catalogAttachIsMatchTargetVersionSchemaVersionMismatchGetMappingClosureHashComputeHashPushFlushMathtempSchemaPathsourceEdmSchemaFilePathget_TargetFilePath_targetFilePathDllImportSearchPathget_VirtualPathGetResourceNameForVirtualPathvirtualPathget_SourceCsdlPathset_SourceCsdlPath_sourceCsdlPathDbProviderServicesInformationLocationPathGetTempPathtargetPathoutputPathget_Lengthget_MaximumLengthset_MaximumLength_columnMaximumLengthlengthEndsWithStartsWithfixmlNamespaceUriobjAsyncCallbackusedFallbackcallbackExtensionCheckPeekSeekGetAccessibilityRankget_TargetFrameworkcheckForSpecialVBMarkMethodAsPartialCSMarkMethodAsPartialMarkAbstractMethodAsPartialset_IsPartialNormalget_Ordinalset_Ordinal_columnFieldOrdinal_columnOrdinalNoSpecificTypeSentinalAddInternalVBMarkPropertyGetAsInternalCSMarkPropertyGetAsInternalVBMarkPropertySetAsInternalCSMarkPropertySetAsInternalCodeGenerationValueAccessibilityInternalFactoryParamCommentGeneralIsPluralpluralop_GreaterThanOrEqualop_LessThanOrEqualisVirtualFixUpMethodDecltypeDeclFixUpClassDeclpropertyDeclCsdlSsdl_isModelSystem.Collections.ObjectModelSystem.Data.EntityModel.SchemaObjectModelSystem.ComponentModelSystem.Data.EntityModelmodelset_ConformanceLevelMetadataUtilPluralizationServiceUtilStringUtilEDesignUtilEntityFrameworkVersionsUtilEntityUtilAllSystem.Data.Entity.Design.dllIsDBNullConvertDBNullIsFKSchemaNullIsPKSchemaNullIsSchemaNullIsIsServerGeneratedNullget_IsParameterModeNullIsScaleNullIsFKTableNullIsPKTableNullIsRelationshipNameNullget_IsParameterNameNullIsDataTypeNullget_IsParameterTypeNullIsFKCatalogNullIsPKCatalogNullIsCatalogNullIsMaximumLengthNullIsOrdinalNullEmitExpressionDoesNotEqualNullIsFKColumnNullIsPKColumnNullIsDateTimePrecisionNullIsPrecisionNullCannotChangePropertyReturnTypeToNullIsNullEmitExpressionEqualsNullCheckArgumentNullIsIsIdentityNullSystem.XmlWriteXmlescapeForXmlFunctionReturnTableDetailSqlget_FunctionDetailSqlRelationshipDetailSqlViewDetailSqlsqlMslGetManifestResourceStreamFileStreamOutputXmlElementToStreamedmxInputStreamMemoryStreamstreamTemplate_CommentFactoryMethodParamSystem.Data.Metadata.Edmget_Itemset_ItemMetadataItemSerialization_UnknownGlobalItemTryGetItem_itemTypeSystemCreateMetadataHashAlgorithmTrimSystem.CodeDomIsAssignableFromfrom_transformEnumget_IsBuiltInScanBooleanop_GreaterThanop_LessThanget_TimeSpan_timeSpanget_Template_ReplaceVsItemTemplateTokenGetProviderManifestToken_providerManifestTokenOpenSystem.Data.Entity.DesignMinGetMessagesFromEntireExceptionChainSeekOriginget_FKColumnset_FKColumn_columnFKColumnget_PKColumnset_PKColumn_columnPKColumnget_Columnget_FKSchemaColumnget_PKSchemaColumnget_SchemaColumnDataColumnget_RelationshipIdColumnget_IsServerGeneratedColumn_columnFieldColumnget_ScaleColumnget_FKTableColumnget_PKTableColumnToPropertyHasNonNullableColumnget_IsNullableColumnget_TableNameColumnget_ColumnNameColumnget_RelationshipNameColumnget_DataTypeColumnget_RelationshipIsCascadeDeleteColumnget_FKCatalogColumnget_PKCatalogColumnget_CatalogColumnget_MaximumLengthColumnGetAssociatedFkColumnfkColumnpkColumnget_OrdinalColumnget_FKColumnColumnget_PKColumnColumnget_PrecisionColumnget_DateTimePrecisionColumnExcludedColumnWasAKeyColumnAssociationMissingKeyColumnget_IsPrimaryKeyColumnget_IsIdentityColumnget_Precisionset_Precisionget_DateTimePrecisionset_DateTimePrecision_columnDateTimePrecision_columnPrecisionAddExtensionget_FileExtension_edmxFileExtensionget_VersionTryGetSchemaVersion_schemaVersionmaxExpectedVersionIsValidVersionruntimeVersionget_MappingVersionGetMinimumTargetFrameworkVersiontargetFrameworkVersionGetEntityFrameworkVersion_targetEntityFrameworkVersionentityFrameworkVersionactualVersionget_StoreSchemaModelVersion_storeSchemaModelVersionget_EdmVersionGetEdmVersionedmVersionConvertToVersionSchemaVersionHigherThanTargetVersionTryGetEdmxVersionDbExpressionDbNewInstanceExpressionCodeFieldReferenceExpressionCodeMethodReferenceExpressionDbVariableReferenceExpressionCodeVariableReferenceExpressionCodeTypeReferenceExpressionCodeBaseReferenceExpressionCodePropertySetValueReferenceExpressionCodeThisReferenceExpressionCodeArgumentReferenceExpressionCodePropertyReferenceExpressionGetEndTypeCodeExpressionGetMultiplicityCodeExpressionOnContextCreatedCodeMethodInvokeExpressionCodeObjectCreateExpressionCodeArrayCreateExpressionGetDefaultValueExpressionCodePrimitiveExpressionCodeTypeOfExpressionget_NullExpression_nullExpressionDbScanExpressionCodeParameterDeclarationExpressionCodeDirectionExpressionEmitEnumMemberExpressionCodeBinaryOperatorExpressionDbProjectExpressionset_InitExpressionCodeCastExpressionDbPropertyExpressionexpressionsessionget_LocationsourceLocationtargetLocationIsAssociationPartOfCandidateCollapsedAssociationget_MeetsRequirementsForCollapsableAssociationstoreAssociationmodelAssociationassociationSystem.Web.CompilationGetInformationAddStoreGeneratedPatternAnnoationCodeTypeDeclarationtypeDeclarationCodeAttributeDeclarationset_OmitXmlDeclarationEmitPropertyDeclarationget_MetadataItemErrorsFoundDuringGenerationForceViewGenerationInvalidOperationget_DocumentationMissingComplexTypeDocumentationMissingDocumentationget_Template_CommentNoDocumentationGetDocumentationMissingPropertyDocumentationdocumentationSystem.GlobalizationSystem.Runtime.SerializationSystem.Xml.SerializationUpdateMemberFieldsAfterDeserializationdeleteActionOperationActionoperationActionactionSystem.ReflectionCodeNamespaceCollectionCodeTypeReferenceCollectionTempFileCollectionstoreCollectionXmlAttributeCollectionValueCollectionmappingCollectionStringCollectionedmCollectionCheckValidItemCollectionget_StoreItemCollectionCreateStoreItemCollection_storeItemCollectionCreateStorageMappingItemCollectionget_EdmItemCollectionCreateEdmItemCollection_edmItemCollectionRegisterItemCollectionitemCollectionDataColumnCollectionCodeExpressionCollectionCodeParameterDeclarationExpressionCollectionCodeTypeDeclarationCollectionCodeAttributeDeclarationCollectionFixUpCollectionGroupCollectionCodeTypeMemberCollectionDbParameterCollectionEntityParameterCollectionCompilerErrorCollectionTableDetailsCollectionRelationshipDetailsCollectionNestedStoreObjectCollectionCodeStatementCollectionCodeCommentStatementCollectioncommentCollectionCodeAttributeArgumentCollectionDataRowCollectionKeyCollectioncollectionCreateStoreSchemaConnectionDbConnectionget_StoreConnectionCreateConnectionproviderConnectionget_InnerConnectionget_EntityConnection_connectionFieldDirectionstoreFunctionModelFunctionCreateEdmFunctionfunctionStoreSchemaDefinitionGetConceptualSchemaDefinitionDbCommandDefinitionCreateCommandDefinitionIsCSClassDefinitionget_LinePositionlinePositionget_LanguageOptionset_LanguageOptionm_languageOptionIncompatibleSettingForCaseSensitiveOptionSchemaDataModelOptionIOExceptionMetadataExceptionNotImplementedExceptionNotSupportedExceptionFileNotFoundExceptionDirectoryNotFoundExceptionNullReferenceExceptionArgumentOutOfRangeExceptionIndexOutOfRangeExceptionProviderIncompatibleExceptionStrongTypingExceptionArgumentNullExceptionXmlExceptionTargetInvocationExceptionAccessViolationExceptionInvalidOperationExceptionget_InnerExceptioninnerExceptionCreateErrorForExceptionTerminalErrorExceptionUnauthorizedAccessExceptionArgumentExceptionThreadAbortExceptionInvalidCastExceptionStackOverflowExceptionOutOfMemoryExceptionSecurityExceptionexceptionget_Descriptionget_LongDescriptionproviderFacetDescriptiondescriptionSystem.Data.CommonSystem.Data.Entity.Design.CommonGenerateCodeCommonAddComparisonStringComparisoncomparisonStoreGeneratedPatternUnsupportedForeignKeyPatternUnsupportedForeinKeyPatternUnknownDoCompareToWriteToBuildProviderAppliesToFieldInfoMethodInfoCultureInfoGetElementLocationInfoSerializationInfoserializationInfoMemberInfoEventInfoPropertyInfoCreateMementomementoAddGetterSetterFixUpget_EdmToObjectNamespaceMapset_EdmToObjectNamespaceMap_edmToObjectNamespaceMapXmlNamedNodeMapItemToErrorsMapHasQueryViewForSetMap_mapUnsupportedDbRelationshipPopMicrosoft.CSharpRelationshipEndTypeLookup_tvfReturnTypeLookupEntityContainerLookupErrorsLookup_errorsLookup_reverseEntityLookup_entityLookupGroupSystem.Xml.LinqSystem.LinqSystem.Data.Objects.ELinqClearCharIsSingularsingularAddMemberstoreEndMemberget_FromEndMemberset_FromEndMemberCreateAssociationEndMemberget_CorrespondingAssociationEndMemberStoreAssociationEndMemberToModelAssociationEndMemberget_ToEndMemberset_ToEndMemberRelationshipEndMemberendMemberCodeTypeMemberEdmMembermemberget_LineNumberlineNumberget_ErrorNumberDbDataReaderEntityDataReaderCreateReaderExecuteReaderInitializeReadersourceEdmSchemaXmlReaderStreamReaderFunctionDetailsReaderTextReader_readerEntityStoreSchemaGeneratorDatabaseSchemaLoadersourceLoaderMetadataArtifactLoaderGetLoader_loaderStorageModelBuildProviderMappingModelBuildProviderEntityModelBuildProviderEntityDesignerBuildProviderEntityClient_DoesNotImplementIServiceProviderVBCodeProviderCSharpCodeProviderEntityClient_InvalidStoreProviderVirtualPathProviderget_CodeDomProviderGetViewsAndCodeDomProvidercompilerProviderIFormatProvider_providerCreateSizedStringBuilderGetViewStringsAppendToStringBuilderAppendStringToStringBuilderGetStringBuilderstringBuilderStringHashBuilderNewRowFromBuilderSystem.Data.Common.CommandTrees.ExpressionBuilderDbExpressionBuilderDataRowBuilderAssemblyBuilderassemblyBuilderbuildersenderBinderset_VerbatimOrderSchemaManagerBuildManagerXmlNamespaceManagerResourceManagerOtherParameterModifieraddGlobalQualifierRegisterUsedIdentifier_identifierToAdjustedIdentifieradjustedIdentifierAdjustIdentifieridentifier_pluralizationServiceHandlerEntityDesignPluralizationHandlerTypeGeneratedEventHandlerPropertyGeneratedEventHandlerSystem.CodeDom.Compiler_storeContainer_modelContainerget_EntityContainerget_StorageEntityContainerInvalidStoreEntityContainerInvalidNonStoreEntityContainer_storeEntityContainer_modelEntityContainerget_EdmEntityContainer_entityContainercontainerinnerMetadataHelperIsUpperMetadataArtifactLoaderXmlReaderWrapperget_LanguageAppropriateStringComparerQualificationCharacterDbParametertypeParameterstoreParameterCreateFunctionParameterget_ReturnParameterObjectParameterCreateFunctionImportParameterEntityParameterparameters_defaultDelimitersourceWriterStringWriterstringWriterXmlWriterStreamWriterGetWriteroutputWriterget_IsUserSuppliedTextWriterIndentedTextWriterGetOrCreateTextWriter_ownTextWritertextWriter_writerReflectionAdapterConverterFixUpGetterLineIsVBBeginSetterGetterisGetterEndPropertyGetterBeginPropertyGetterEmitPropertyGetterIsLetterFixUpSetterEndPropertySetterBeginPropertySetterEmitPropertySetterNamespaceEmitterSchemaTypeEmitterStructuredTypeEmitterAssociationTypeEmitterComplexTypeEmitterEntityTypeEmitterCreateEmitterget_AttributeEmitter_attributeEmitterMetadataItemEmitterEntityContainerEmitterCreateElementEmitterCommentEmitterNavigationPropertyEmitteremitterToLowerOneToOneMappingSerializerMetadataItemSerializer_fromStringGenericMemoizer_nullableForTypeMemoizer_forTypeMemoizer_fromStringMemoizerget_TempDirCommandBehaviorget_DeleteBehaviorset_DeleteBehaviordeleteBehaviorget_Majorget_MinorConvertToEdmSchemaErrorAddErrorCreateSourceEdmSchemaNotValidErrorEdmErrorThrowOnErrorPreprocessTemplateCompilationErrorPreprocessTemplateTransformationErrorUnknownErrorCompilerErrorSecurityErrorerrorLazyTextWriterCreatorseparatorIEnumeratorSystem.Collections.Generic.IEnumerable<System.String>.GetEnumeratorSystem.Collections.Generic.IEnumerable<System.Data.Metadata.Edm.GlobalItem>.GetEnumeratorSystem.Collections.Generic.IEnumerable<System.CodeDom.CodeMethodInvokeExpression>.GetEnumeratorSystem.Collections.Generic.IEnumerable<System.Data.Metadata.Edm.EdmSchemaError>.GetEnumeratorSystem.Collections.IEnumerable.GetEnumeratorget_Generatorset_GeneratorEntityStoreSchemaGeneratorEntityModelSchemaGeneratorEntityCodeGeneratorClientApiGeneratorSystem.Data.Entity.Design.SsdlGeneratorget_TargetEntityFrameworkVersionToNewForEntityClassGeneratorEntityViewGenerator_generatorActivator.ctor.cctorCodeConstructorMetadataMappingHasherVisitorBindAsTemplate_GenCommentAddToMethodCsRelationshipDetailFromTableAliasRelationshipDetailToTableAliasFunctionReturnTableDetailAliasFunctionDetailAliasViewDetailAliasaliasadditionalEdmSchemasRelationshipSpansSchemasTemplateCodeGenerators.CSharpCodeGenTemplateV5.0.csTemplateCodeGenerators.CSharpCodeGenTemplate.csParameterTypeSemanticsGetCollectionTypeReferenceForBagSemanticsGetCollectionTypeReferenceForListSemanticsSystem.DiagnosticsSetupFieldsget_AssociationSetEndsEmitPropertyOnChangePartialMethodsget_Template_RegionPartialMethodsCreateContextPartialMethodsMetadataExtensionMethodsget_Template_RegionAddToMethods_VBFixMethods_CSFixMethods_knownPluralWords_knownSingluarWordsEDesignResAddInterfacesget_AdditionalInterfaces_additionalInterfacesv1Namespacesv2Namespacesv3Namespacesget_Namespacesget_EdmNamespacesxmlPrefixToNamespacesSystem.Data.Entity.Design.PluralizationServicesUnsupportedLocaleForPluralizationServicesSystem.Runtime.InteropServicesDbProviderServicesSqlProviderServicesGetProviderServicesproviderServicesSystem.Runtime.CompilerServicesPropertyTypeReferencesSystem.Resourcesget_ResourcesSystem.Data.Entity.Design.resourcesDebuggingModesExtractConceptualMappingAndStorageNodesSelectNodesSystem.Data.Common.CommandTreesget_ReferencedAssembliesDbProviderFactoriesAddStoreSchemaResourceMapEntriesAddMappingSchemaResourceMapEntriesAddEdmSchemaResourceMapEntriesTryGetEndEntities_missingEntitiesGetAllEntitiesget_Template_RegionEntitiesReadOnlyEntitiesget_Propertiesget_MetadataPropertiesAddMetadataPropertiesget_Template_RegionSimplePropertiesget_Template_RegionPrimitivePropertiesCollectAllFkPropertiesCreateEdmPropertiesget_FromPropertiesget_NavigationPropertiesCreateModelNavigationPropertiesget_Template_RegionNavigationPropertiesget_ToPropertiesGetPropertiesget_Template_RegionObjectSetPropertiesEmitPropertiesget_Template_RegionComplexPropertiesget_GenerateForeignKeyPropertiesset_GenerateForeignKeyPropertiespropertiesTypeValueTablesusedNamesInitializeTypeReservedNames_typeReservedNamesusedEndNamesUsedTypeNamesUsedGlobalModelTypeNamesUsedEntityContainerItemNamesLoadNameLookupWithUsedMemberNamesusedMemberNamesusedEndMemberNamesusedParameterNamesusedPropertyNamesAddToPropertyNamesnamesGetFormattedLinesSplitIntoLinescommentLinesget_Typesget_SchemaTypesGetDirectSubTypesInvalidTypes_invalidTypesGetSourceTypesCreateTableTypesget_BaseTypesGetPrimitiveTypesget_Template_RegionEnumTypesCreateAssociationTypesEntityStoreSchemaFilterObjectTypesCreateTvfReturnRowTypesget_Template_RegionComplexTypesqueryTypesCreateTableEntityTypesCreateViewEntityTypes_typesfilterAliasesSystem.Data.Objects.DataClassesFindAllInvalidCollapsedAssociationCandidatesget_Attributesset_Attributesget_TypeAttributesset_TypeAttributesEmitKnownTypeAttributesEmitTypeAttributesAddIgnoreAttributesget_AdditionalAttributes_additionalAttributesget_CustomAttributesEmitCustomAttributesget_AssemblyCustomAttributesMemberAttributesWriteExtendedPropertyAttributesEmitNavigationPropertyAttributesEmitPropertyAttributesget_ValuesGetValuesget_NullFacetValues_values_privateMemberPrefixessuffixesBindingFlagsBuildProviderResultFlagsGetResultFlagsCheckIfAllErrorsAreWarningsSplitViewStrings<>3__viewStringsXmlWriterSettingsget_BaseConstructorArgsTypeGeneratedEventArgsPropertyGeneratedEventArgseventArgsargslhsrhsadditionalEdmSchemaFilePathsset_ReferenceCsdlPaths_referenceCsdlPathsGetPaths<>4__thisget_TicksLeadingBlanksEqualsLoadTableDetails_tableTableDetailsLoadFunctionReturnTableDetailsLoadFunctionDetails_tableRelationshipDetailsLoadViewDetailsSystem.Data.Common.UtilsBuildProviderUtilsEntityDesignerUtilsGetItemscommentedOutItemsContainsget_ColumnsexcludedColumnsAreAllEntityColumnsMappedAsToColumnsInferKeyColumnscolumnsDataTableExtensionsSystem.Data.DataSetExtensionsDataRowExtensionsValidVersionsEntityFrameworkVersionsSystem.Text.RegularExpressionsGetAppendViewStringsExpressionsCandidateCollapsedAssociationsIsEntityDependentSideOfBothAssociationsIsAtLeastOneColumnFKInBothAssociationsSystem.Collections_storeFunctionsCreateEdmFunctionsMapFunctionsCodeTypeReferenceOptionsget_LanguageOptionsset_CompilerOptionsCodeGeneratorOptionsRegexOptionsGetAssociatedFacetDescriptionsget_FixUpsget_ClassFixUps_classFixUps_fixUpsLoadRelationshipsget_Template_RegionRelationshipsMappingLookups_mappingLookups_lookupsget_Groupsfixupsget_Charsget_MembersAddMembersget_AssociationEndMembersget_RelationshipEndMembersget_AdditionalMembers_additionalMembersset_BlankLinesBetweenMembersGetMembersget_KeyMembersGetDeclaredOnlyMembersmemberscloseReadersDisposeXmlReadersxmlReadersGetReadersreadersloaders_knownIdentifiers_CSFieldMarkers_VBNonDeclMarkersRuntimeHelpersTypeHelpersRemoveXmlCommentCharactersget_ParametersReturnParametersCompilerParametersparameters_VBEndOfClassDelimiters_CSEndOfClassDelimitersFiltersfiltersAccessibilityFromGettersAndSettersSystem.Data.EntityModel.Emittersget_Errorsget_ProviderSchemaErrorsschemaErrorsThrowOnAnyNonWarningErrorsGetViewsWithErrorsHandleValidationErrorsget_HasErrorsHasErrorSeverityErrors_errorsEmitterCreatorsCreateConstructorsget_Template_RegionConstructorsget_Classset_ClassAdoFrameworkGenericDataClassAdoFrameworkGenericClassEndClassget_UsingStandardBaseClass_usingStandardBaseClassget_IEntityWithRelationshipsTypeBaseClassget_ComplexTypeBaseClassget_EntityTypeBaseClassEmitApiClassBeginClassget_IsClassInitClass_classFileAccesstypeAccesssetAccessget_SuccessSystem.Data.Objectsget_AssociationSets_storeAssociationSetsCollapsedEntityAssociationSetsget_BaseEntitySetsFixupKeylessEntitySetsIsAlphabetsget_FacetsWritePropertyTypeFacetsAttributeTargetsCompilerResultsresultsDesignXmlConstantsEntityViewGenerationConstantsget_Statementsget_TrueStatementsget_GetStatementsget_AdditionalGetStatements_additionalGetStatementsget_SetStatementsget_AdditionalSetStatements_additionalSetStatementsEmitScalarTypePropertySetStatementsEmitComplexTypePropertySetStatementsstatementsget_Commentsget_GetViewAtMethodCommentsNamespaceCommentsget_TypeCommentsEmitXmlCommentsEmitParamCommentsEmitOtherDocumentationCommentsget_ConstructorCommentsEmitCommentsIndividualViewCommentsEmitSummaryCommentssummaryCommentsget_Argumentsget_TypeArgumentsAddAttributeArgumentsAddNamedAttributeArgumentsargumentsget_ReferentialConstraintsGetConstraintsget_FunctionImportsget_Template_RegionFunctionImportsExistsget_Template_RegionContextsEntityCreationStatusgeneratedViewsGenerateAndStoreViewsInternalGenerateViewsTypeValueViewsCreateTypeForStoringViewsGenerateEntitySetViewsGetEntitySetViewsHashOverAllExtentViewsget_RowstableDetailsRowsrowsget_KeyspKeys_tablesWithoutKeysprimaryKeysConcatFormatformatCreateMetadataPropertyFromOtherNamespaceXmlArtifactget_Abstractget_EffectEntityStoreSchemaFilterEffect_effectStructuralObjectGetObjectset_TargetObjectComplexObjectEntityObjectobjectProjectSelectIntersectTemplate_FactoryMethodNameConflictGeneratedFactoryMethodNameConflictGeneratedNavigationPropertyNameConflictTemplate_CaseInsensitiveTypeConflictTemplate_CaseInsensitiveMemberConflictTemplate_CaseInsensitiveEntitySetConflictEntityTypeAndSetAccessibilityConflictGeneratedPropertyAccessibilityConflictset_HasGetSystem.Data.Entity.Design.AspNetEFNamespaceSetSecurityRuleSetdefiningSetcollapsedAssociationSetstoreAssociationSetCreateAssociationSetget_ModelAssociationSetset_ModelAssociationSetCreateModelAssociationSetStoreAssociationSetToModelAssociationSetparentModelAssociationSet_modelAssociationSetget_ParentAssociationSetCollapsedEntityAssociationSetassociationSetEntityTypeToSetset_HasSetmultiplicitySetget_EntitySet_storeEntitySetCreateEntitySetCreateModelEntitySetStoreEntitySetToModelEntitySetVerifyLanguageCaseSensitiveCompatibilityForEntitySetIsEntitySetGetEntitySetentitySetget_DefaultValueFacetIsSpecialFacetStoreGeneratedPatternFacetSkipFacetfacetCheckForCompatibleSchemaAndTargetexcludedForTargetUnsupportedDataTypeForTargetUnsupportedFunctionReturnDataTypeForTargetUnsupportedFunctionParameterDataTypeForTargetValidateActualVersionAgainstTargettargetSystem.Collections.IEnumerator.Resetget_Offsetget_DateTimeOffset_dateTimeOffsetoffsetPadLeftleftIsLeftMoreAccessableThanRightrightIsLetterOrDigitSplitEmitget_CompileUnitAddCodeCompileUnitGenerateCodeFromCompileUnitCodeSnippetCompileUnit_compileUnitGetValueOrDefaultFirstOrDefaultHasDefaultIAsyncResultCreateModelComplexTypeForTvfResultObjectResultresultToUpperInvariantToLowerInvariantFormatInvariantget_IsConstantset_IndentSystem.Data.SqlClientSystem.Data.EntityClientXElementWriteSchemaElementGetSchemaElementWriteEndElementWriteRelationshipEndElementWriteAssociationSetEndElementSummaryEndElementWriteReferentialConstraintRoleElementWriteTypeElementWriteAssociationTypeElementWriteRowTypeElementWriteComplexTypeElementWriteEntityTypeElementWriteEntityTypeMappingElementWriteEntityContainerMappingElementWriteAssociationSetMappingElementWriteEntitySetMappingElementWriteFunctionImportMappingElementXmlElementxmlElementWriteOperationActionElementWriteFunctionElementWriteConditionElementWriteEntityContainerElementWriteFunctionParameterElementWriteAssociationSetElementWriteEntitySetElementWriteMappingFragmentElementget_DocumentElementWriteReferentialConstraintElementWriteStartElementWriteMappingStartElementSummaryStartElementWriteEndPropertyElementWritePropertyElementWriteNavigationPropertyElementWriteScalarPropertyElementelementCodeStatementCodeAssignStatementCodeExpressionStatementCodeVariableDeclarationStatementCodeConditionStatementCodeThrowExceptionStatementCodeMethodReturnStatementCodeCommentStatementsegmentdocCommentTemplate_FactoryMethodCommentWriteCommentTemplate_ContextCommonCtorCommentTemplate_ContextDefaultCtorCommentWriteErrorsCommentFactoryMethodSummaryCommentEmptyCtorSummaryCommentcommentEnvironmentXmlDocumentInvalidNamespaceNameArgumentInvalidEntityContainerNameArgumentCodeAttributeArgumentInvalidStringArgumentCheckStringArgumentCheckTargetEntityFrameworkVersionArgumentCreateFunctionArgumentCheckLanguageOptionArgumentargumentComponentSystem.Collections.Generic.IEnumerator<System.String>.CurrentSystem.Collections.Generic.IEnumerator<System.Data.Metadata.Edm.GlobalItem>.CurrentSystem.Collections.Generic.IEnumerator<System.CodeDom.CodeMethodInvokeExpression>.CurrentSystem.Collections.Generic.IEnumerator<System.Data.Metadata.Edm.EdmSchemaError>.CurrentSystem.Collections.IEnumerator.CurrentSystem.Collections.Generic.IEnumerator<System.String>.get_CurrentSystem.Collections.Generic.IEnumerator<System.Data.Metadata.Edm.GlobalItem>.get_CurrentSystem.Collections.Generic.IEnumerator<System.CodeDom.CodeMethodInvokeExpression>.get_CurrentSystem.Collections.Generic.IEnumerator<System.Data.Metadata.Edm.EdmSchemaError>.get_CurrentSystem.Collections.IEnumerator.get_Current<>2__currentGenerateHashForAllExtentViewsContentRaiseTypeGeneratedEventRaisePropertyGeneratedEventstoreConstraintAddReferentialConstraintCreateReferentialConstraintRequiresModelReferentialConstraintGetReferentialConstraintconstraintget_Countget_ColumnCountUnsupportedModelGenerationConceptExceptInsertConverttoSortAddFunctionImportUnmappedFunctionImportGetReturnTypeFromFunctionImportStoreFunctionToFunctionImportget_IsFunctionImportShouldEmitFunctionImportfunctionImportDbProviderManifestget_EdmProviderManifestget_IsFromProviderManifestGetProviderManifestLatest_irregularVerbList_uninflectiveWordListXmlNodeList_knownConflictingPluralList_pronounListToList_uninflectiveSuffixListlistget_RealErrorsExistrefconstTFirstReplaceFirstExistsInFirstfirstset_CommandTimeoutinputMoveNextSystem.Textget_CommandTextset_CommandTextsearchTextReadAllTextTransformText_transformTextget_ErrorTextset_ErrorTextinsertTextviewTextStreamingContextstreamingContextget_ObjectContext_objectContextcontextprovGenerateDictionaryForEntitySetNameAndViewValidateFunctionViewGetCqtViewHasQueryViewDefaultTargetVersionTooLowget_EntityCodeGenTargetTooLowget_NowDataRowTableDetailsRowRelationshipDetailsRow_currentRowNewRowAllowrowindexRegexFixViewGenerationTypeNamePrefixAnnotationPrefixPrivateMemberPrefix_complexPropertyInitializedSuffixDoesWordContainSuffixEdmxThenByOrderByget_ByteArray_byteArrayInitializeArrayToArrayToCharArrayEmitPropertyGetterBodyEmitPropertySetterBodyget_KeytableKeyAreRelationshipColumnsTheTypesEntireKeySharedForeignKeyPrimaryKeyCannotBeForeignKeyget_IsForeignKeyfunctionKeyContainsKeyCreateDbObjectKeyGetKeyAddTableWithoutKeyContainsTableWithoutKeyInvalidTypeForPrimaryKeyget_IsPrimaryKeyset_IsPrimaryKey_columnIsPrimaryKeyCannotCreateEntityWithoutPrimaryKeykeySystem.Security.Cryptographyget_Assemblyget_CompiledAssemblyGetExecutingAssemblyget_IsAssemblyAsReadOnlyExcludedColumnWasAKeyColumnEntityIsReadOnlySetReadOnlyIndexOfAnySelectManyget_SummaryGetCodeExpressionFromBinaryget_FirstToSecondDictionaryset_FirstToSecondDictionaryfirstToSecondDictionary_wordsEndingWithSeDictionaryStringBidirectionalDictionary_assimilatedClassicalInflectionDictionary_classicalInflectionDictionaryToDictionaryDuplicateEntryInUserDictionary_userDictionaryAsDictionary_wordsEndingWithSisDictionary_irregularPluralsDictionary_wordsEndingWithSusDictionaryget_SecondToFirstDictionaryset_SecondToFirstDictionary_oSuffixDictionary_wordsEndingWithInxAnxYnxDictionarydictionaryget_DefiningQueryset_DefiningQueryFixupViewEntitySetDefiningQuerycategoryset_GenerateInMemoryProviderFactoryReturnedNullFactoryMetadataItemCollectionFactoryDbProviderFactoryget_StoreProviderFactoryGetProviderFactoryGetFactorySqlClientFactoryfactoryEntityStoreSchemaFilterEntryAddFilterEntryentrycapacityGetXmlMultiplicityget_RelationshipMultiplicityrelationshipMultiplicitymultiplicityop_Equalityop_InequalityVerifyGetterAndSetterAccessibilityCompatabilityVerifyEntityTypeAndSetAccessibilityCompatabilitySetTypeVisibilityDesignerSerializationVisibilityGetEntityTypeAccessibilityGetGetterAccessibilityGetSetterAccessibilityGetFunctionImportAccessibilityGetEntitySetPropertyAccessibilitypropertyAccessibilityaccessibilityVirtualPathUtilityget_SeverityEdmSchemaErrorSeverityseveritySystem.SecuritySystem.Data.EntityAddEntityMissingEntityTryGetEntityget_IdentityitemIdentityget_IsIdentityset_IsIdentity_columnIsIdentityparentIdentityIsNullOrEmptyget_IsEmptyget_Propertyset_PropertyMetadataPropertyStructuredPropertyEndPropertyLineIsVBBeginClassMethodPropertycSpacePropertyreferencePropertystorePropertyhidesBasePropertyget_IsVirtualPropertyCreateModelPropertyStoreEdmPropertyToModelEdmPropertyBeginPropertyCreateModelNavigationPropertyEmitNavigationPropertynavigationPropertyPropertyInfoPropertyCodeMemberPropertymemberPropertyInvalidAttributeSuppliedForPropertyInvalidGetStatementSuppliedForPropertyInvalidSetStatementSuppliedForPropertyVerifyLanguageCaseSensitiveCompatibilityForPropertyget_HidesBaseClassPropertyCreateEntitySetAddObjectPropertyGetPropertyCreateEntitySetPropertyEmitPropertystoreKeyPropertyget_IsKeyProperty_property3System.Data.Entity.Design...	!EdmCodeGenFixup-	.tmpC.1EdmRelationshipAttribute1RelationshipMultiplicity-EdmEntityTypeAttributeeSystem.Runtime.Serialization.DataContractAttributeIsReference'System.Serializable_System.Runtime.Serialization.KnownTypeAttributeNamespaceName	NameUEdmRelationshipNavigationPropertyAttributeKSystem.CodeDom.Compiler.GeneratedCode]System.Data.Entity.Design.EntityClassGenerator5EdmScalarPropertyAttribute#EntityKeyPropertyIsNullable7EdmComplexPropertyAttributekSystem.ComponentModel.DesignerSerializationVisibilityContentGSystem.Xml.Serialization.XmlElementISystem.Xml.Serialization.SoapElement/EdmComplexTypeAttributeaSystem.Runtime.Serialization.DataMemberAttribute?System.Data.Objects.DataClassesFullName;<param name="{0}">{1}</param>
LeadingBlanksLongDescriptionsummary<{0}>
</{0}>7^(?<LeadingBlanks>\s{1,})\S!OnContextCreatedname=!connectionString!EntityConnectionconnectionObjectQueryCreateQuery[]AddToAddObjectExecuteFunctionParameterHasValue<KeyProperties>!</KeyProperties>public abstractpartial'Public MustOverridePartial Private        End Suboverride
sealedOverridesNotOverridablesetinternalSet
FriendgetprivateGetPrivateprotectedProtected
public
Public
staticclassstatic  {}// class @ClassEnd Class!MustOverride SubFunctionSubPropertyEnd PropertyEnd SubEnd FunctionEnd GetEnd Set  GetterAccessSetterAccessMethodAccessTypeAccessInternaleSystem.Data.Objects.DataClasses.EdmSchemaAttributeReference5InitializeRelatedReference'RelationshipManagerValue7InitializeRelatedCollectionEntityReference!EntityCollection'GetRelatedReference)GetRelatedCollectionvalueGetValidValue-ReportPropertyChanging+ReportPropertyChangedSetValidValueCollectionKindOnChangingChangedD
Create9VerifyComplexObjectIsNotNull'System.Data.ObjectsObjectResultObjectContext1IEntityWithRelationshipsid)System.Data.Objects.ASystem.Data.Objects.DataClasses.3System.Data.Metadata.Edm.3System.Data.EntityClient.qhttp://schemas.microsoft.com/ado/2006/04/codegeneration:__Initialize_PropertyInfo_piInitializedGEntityStoreGeneratorSchemaNotLoadedGEntityModelGeneratorSchemaNotLoaded;StonglyTypedAccessToNullValue'NoPrimaryKeyDefined1InvalidTypeForPrimaryKeySCannotCreateEntityWithNoPrimaryKeyDefinedOTableReferencedByAssociationWasNotFound?TableReferencedByTvfWasNotFound'UnsupportedDataType=UnsupportedDataTypeUnknownTypeCUnsupportedFunctionReturnDataTypeIUnsupportedFunctionParameterDataType9UnsupportedDataTypeForTargetUUnsupportedFunctionReturnDataTypeForTarget[UnsupportedFunctionParameterDataTypeForTarget3UnsupportedDbRelationship5ParameterDirectionNotValid+InvalidStringArgument?Serialization_UnknownGlobalItem#ReservedNamespace5ColumnFacetValueOutOfRange7AssociationMissingKeyColumnESingleStoreEntityContainerExpected=InvalidNonStoreEntityContainerUExcludedColumnWasAKeyColumnEntityIsInvalidWExcludedColumnWasAKeyColumnEntityIsReadOnlyCModelGeneration_UnGeneratableType9DuplicateEntityContainerNameEProviderFactoryReturnedNullFactory)ProviderSchemaErrors9InvalidNamespaceNameArgumentEInvalidEntityContainerNameArgumentCEntityClient_InvalidStoreProviderSDbProviderServicesInformationLocationPath9UnsupportedForeignKeyPatternYUnsupportedQueryViewInEntityContainerMapping!SharedForeignKey-UnmappedFunctionImport=CannotChangePropertyReturnTypeICannotChangePropertyReturnTypeToNull?CodeGenSourceFilePathIsNotAFile?InvalidAttributeSuppliedForType9InvalidMemberSuppliedForType?InvalidInterfaceSuppliedForTypeGInvalidAttributeSuppliedForPropertyMInvalidGetStatementSuppliedForPropertyMInvalidSetStatementSuppliedForProperty?PropertyExistsWithDifferentCaseAEntitySetExistsWithDifferentCase7ItemExistsWithDifferentCase)NullAdditionalSchema%DuplicateClassNameqTargetEntityFrameworkVersionToNewForEntityClassGenerator9MissingPropertyDocumentation?MissingComplexTypeDocumentation)MissingDocumentation5MissingDocumentationNoName#NamespaceComments7FactoryMethodSummaryComment5FactoryParamCommentGeneral%CtorSummaryComment/EmptyCtorSummaryCommentOGeneratedNavigationPropertyNameConflictMGeneratedPropertyAccessibilityConflictKEntityTypeAndSetAccessibilityConflictEGeneratedFactoryMethodNameConflictOMetadataItemErrorsFoundDuringGenerationSUnableToGenerateForeignKeyPropertiesForV1WUnableToGenerateFunctionImportParameterNameTypeComments/GetViewAtMethodComments'ConstructorComments-IndividualViewCommentsETargetVersionSchemaVersionMismatch=DuplicateEntryInUserDictionarySUnsupportedLocaleForPluralizationServices=Template_DuplicateTopLevelTypeQTemplate_ConflictingGeneratedNavPropNameETemplate_FactoryMethodNameConflictITemplate_CaseInsensitiveTypeConflictSTemplate_CaseInsensitiveEntitySetConflictMTemplate_CaseInsensitiveMemberConflictATemplate_GenCommentAddToMethodCsATemplate_GenCommentAddToMethodVb?Template_CommentNoDocumentationETemplate_CommentFactoryMethodParamETemplate_GeneratedCodeCommentLine1ETemplate_GeneratedCodeCommentLine2ETemplate_GeneratedCodeCommentLine3ETemplate_ContextDefaultCtorCommentCTemplate_ContextCommonCtorComment;Template_FactoryMethodComment9Template_RegionRelationships/Template_RegionContextsETemplate_RegionObjectSetProperties7Template_RegionAddToMethods=Template_RegionFunctionImports/Template_RegionEntitiesGTemplate_RegionNavigationProperties7Template_RegionComplexTypes9Template_RegionFactoryMethodETemplate_RegionPrimitiveProperties?Template_RegionSimplePropertiesATemplate_RegionComplexProperties1Template_RegionEnumTypes7Template_RegionConstructors;Template_RegionPartialMethodsGTemplate_ReplaceVsItemTemplateTokenCTemplate_CurrentlyRunningTemplate5Template_UnsupportedSchema#EdmSchemaNotValid+EdmSchemaFileNotFound3EntityCodeGenTargetTooLow5DefaultTargetVersionTooLow[EntityClient_DoesNotImplementIServiceProviderSEntityClient_ReturnedNullOnProviderMethodedmNamespaceobjectNamespacelanguageOptionsourceEdmSchema
target)additionalEdmSchemas'additionalEdmSchema/sourceEdmSchemaFilePath9additionalEdmSchemaFilePathstargetPath.csdl'sourceEdmSchemaPath	edmxedm	ssdlmapq/edmx:Edmx/edmx:Runtime/edmx:ConceptualModels/edm:Schemam/edmx:Edmx/edmx:Runtime/edmx:StorageModels/ssdl:Schemac/edmx:Edmx/edmx:Runtime/edmx:Mappings/map:Mapping��/edmx:Edmx/edmx:Designer/edmx:Connection/edmx:DesignerInfoPropertySet/edmx:DesignerProperty5MetadataArtifactProcessing[http://schemas.microsoft.com/ado/2007/06/edmxYhttp://schemas.microsoft.com/ado/2006/04/edmiurn:schemas-microsoft-com:windows:storage:mapping:CSchttp://schemas.microsoft.com/ado/2006/04/edm/ssdl[http://schemas.microsoft.com/ado/2008/10/edmxYhttp://schemas.microsoft.com/ado/2008/09/edmghttp://schemas.microsoft.com/ado/2008/09/mapping/cschttp://schemas.microsoft.com/ado/2009/02/edm/ssdl[http://schemas.microsoft.com/ado/2009/11/edmxYhttp://schemas.microsoft.com/ado/2009/11/edmghttp://schemas.microsoft.com/ado/2009/11/mapping/cschttp://schemas.microsoft.com/ado/2009/11/edm/ssdl.edmxnamespaceName1modelEntityContainerName'storeItemCollection)storeEntityContainer9targetEntityFrameworkVersionoutputFileName
writer��http://schemas.microsoft.com/ado/2009/02/edm/annotation:LazyLoadingEnabledannotationohttp://schemas.microsoft.com/ado/2009/02/edm/annotationReturnType_ResultApplication
TargetModelContext+StoreGeneratedPattern��http://schemas.microsoft.com/ado/2009/02/edm/annotation:StoreGeneratedPatterntypes?Edm_EntityMappingGeneratedViewscSystem.Data.Mapping.EntityViewGenerationAttribute-ViewsForBaseEntitySetsOSystem.Data.Mapping.EntityViewContainer-EdmEntityContainerName1StoreEntityContainerName-HashOverMappingClosure-HashOverAllExtentViewsViewCountGetViewAt<Summary></Summary>#mappingCollectionoutputPathoutputWriterindexGetViewToStringviewString
AppendedmCollectionstoreCollectionreaders-entityFrameworkVersiondataSpace	Edmx+providerInvariantNamefiltersContainerstore��http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator	Type
TablesViews	nullNullablePrecisionScaleMaxLength
Schema{0}({1})_TemplateCodeGenerators.CSharpCodeGenTemplate.csYTemplateCodeGenerators.CSharpCodeGenTemplategTemplateCodeGenerators.CSharpCodeGenTemplateV5.0.cs_TemplateCodeGenerators.CSharpCodeGenTemplateV50WTemplateCodeGenerators.VBCodeGenTemplate.vbQTemplateCodeGenerators.VBCodeGenTemplate_TemplateCodeGenerators.VBCodeGenTemplateV5.0.vbWTemplateCodeGenerators.VBCodeGenTemplateV501/d:PREPROCESSED_TEMPLATE	fishoissheep	deerpos	itisismbisonflounder
pliersbreamgallowsproceedingsbreechesgraffiti
rabiesbritchesheadquarters
salmon	carp
herpesscissorschassishigh-jinkssea-bassclippershomework
seriescodinnings
shearscontretempsjackanapesspeciescorpsmackerelswine
debrismeaslestroutdiabetes	mews	tunadjinnmumpswhitingeland	newswildebeestelkpincers
police	hairicechaos	milk
cotton[pneumonoultramicroscopicsilicovolcanoconiosisinformationaircraftscabiestraffic	corn
millet	ricehay	hemptobaccocabbage	okrabroccoliasparaguslettuce	beef	porkvenison
mutton
cattleoffspringmolassesshamblesshinglesamareiswas	werehas	haveIweyouheshe	theyitmeushimher	them
myselfourselvesyourselfhimselfherself
itselfoneselfoneselvesmyour	yourhistheirits	mineyours	hers
theirs	this	thatthesethoseallanotheranyanybody
anyoneanything	both	eachother
eithereveryoneeverybodyeverything	most	muchnothing
nobody	noneone
others	somesomebodysomeonesomething	whatwhateverwhichwhicheverwhowhoever	whomwhomeverwhosebrotherbrotherschildchildrencow	cowsephemerisephemeridesgenie
geniesmoney
moneysmongoosemongooses
mythos
mythoioctopusoctopusesox	oxensoliloquysoliloquies
trilbytrilbys
crisis
crisessynopsissynopses	roserosesgasgasesbusbuses	axis	axes	memomemos
casinocasinos	silosilos
stereostereos
studiostudios	lens
lensesaliasaliasespie	pies
corpuscorpora
viscusviscerahippopotamushippopotamitrace
traces
person
peoplechilichiliesanalysisanalysesbasisbasesneurosisneurosesoasisoasessynthesissyntheses
thesis
theses
changechangeslie	liescaloriecaloriesfreebiefreebies	casecaseshouse
housesvalve
valvesclothclothestie	tiesmovie
moviesbonusbonusesspecimenspecimens
alumnaalumnae	algaalgaevertebravertebraecodexcodicesmurexmuricessilexsilicesaphelionapheliahyperbatonhyperbataperihelionperiheliaasyndetonasyndetanoumenonnoumenaphenomenonphenomenacriterioncriteriaorganon
organaprolegomenonprolegomenaagendum
agendadatum	dataextremumextremabacteriumbacteriadesideratumdesideratastratum
stratacandelabrumcandelabraerratum
errata	ovumovaforum	foraaddendumaddendastadium
stadiaautomatonautomatapolyhedronpolyhedra
albinoalbinosgeneralissimogeneralissimosmanifestomanifestosarchipelagoarchipelagos
ghettoghettos
medicomedicosarmadilloarmadillosguano
guanos
octavooctavoscommandocommandosinfernoinfernosphoto
photosditto
dittosjumbo
jumbospro	pros
dynamodynamoslingo
lingos
quartoquartos
embryoembryoslumbagolumbagosrhino
rhinos
fiascofiascosmagnetomagnetosstylo
stylos
stamenstaminaforamenforaminalumen
luminaanathemaanathemataenemaenemata
oedemaoedemata	bema
bemata
enigmaenigmatasarcomasarcomatacarcinomacarcinomatagummagummata
schemaschematacharismacharismatalemmalemmata	soma
somatadiplomadiplomatalymphomalymphomata
stigmastigmatadogmadogmatamagmamagmatastomastomatadramadramatamelismamelismata
traumatraumataedemaedemata
miasmamiasmataabscissaabscissaeformulaformulae
medusamedusae
amoebaamoebaehydra
hydrae
nebulanebulaeantennaantennaehyperbolahyperbolae	novanovae
auroraaurorae
lacunalacunaeparabolaparabolae	apex
apiceslatexlatices
vertexvertices
cortexcorticespontifexpontifices
vortexvorticesindicessimplexsimplices	iris
iridesclitorisclitorides	alto	alticontraltocontraltisopranosopranibassobassicrescendocrescenditempotempicantocanti	solo	soliaquariumaquariainterregnuminterregnaquantum
quantacompendiumcompendialustrum
lustrarostrum
rostraconsortiumconsortiamaximum
maximaspectrumspectracranium
crania
mediummediaspeculumspeculacurriculumcurriculamemorandummemoranda
dictumdictamilleniummilleniatrapeziumtrapeziaemporiumemporiaminimum
minimaultimatumultimataenconiumenconiamomentummomenta
vacuumvacuagymnasiumgymnasiaoptimum
optimavelum	velahonorariumhonoraria
phylumphylafocus	foci
nimbusnimbisuccubussuccubi
fungusfunginucleolusnucleolitorus	tori
geniusgenii
radiusradiiumbilicusumbiliciincubus
incubi
stylusstyli
uterusuteristimulusstimuliapparatusimpetusprospectus
cantusnexussinus
coitus
plexus
status
hiatus
afreetafreetiafrit
afriti
efreetefreeti
cherubcherubimgoygoyim
seraphseraphimalumnus
alumnienterpriseenterprisespurchasepurchasessurprisesurprisesreleasereleasesdiseasediseasespromisepromises
refuserefuses
whosesphase
phasesnoise
noisesnurse
nursesfranchisefranchisessupervisesupervisesfarmhousefarmhousessuitcasesuitcasesrecourserecoursesimpulseimpulseslicenselicensesdiocesedioceses
exciseexcises
demisedemises
blouseblouses
bruisebruises
misusemisusescurse
cursesprose
prosespurse
pursesgoose
goosestease
teasespoise
poises	vasevases	fusefuses	musemusesslaughterhouseslaughterhousesclearinghouseclearinghousesendonucleaseendonucleasessteeplechasesteeplechasesmetamorphosemetamorphosesintercourseintercoursescommonsensecommonsensesintersperseinterspersesmerchandisemerchandisesphosphatasephosphatasessummerhousesummerhouseswatercoursewatercoursescatchphrasecatchphrasescompromisecompromisesgreenhousegreenhouseslighthouselighthousesparaphraseparaphrasesmayonnaisemayonnaisesracecourseracecoursesapocalypseapocalypsescourthousecourthousespowerhousepowerhousesstorehousestorehousesglasshouseglasshouseshypotenusehypotenusesperoxidaseperoxidasespillowcasepillowcasesroundhouseroundhousesstreetwisestreetwisesexpertiseexpertisesdiscoursediscourseswarehousewarehousesstaircasestaircasesworkhouseworkhousesbriefcasebriefcasesclubhouseclubhousesclockwiseclockwisesconcourseconcoursesplayhouseplayhousesturquoiseturquoisesboathouseboathousescellulosecellulosesepitomiseepitomisesgatehousegatehousesgrandiosegrandiosesmenopausemenopausespenthousepenthousesracehorseracehorsestransposetransposesalmshousealmshousescustomisecustomisesfootloosefootloosesgalvanisegalvanisesprincesseprincessesuniverseuniversesworkhorseworkhorsesatherosclerosisatheroscleroseselectrophoresiselectrophoresespsychoanalysispsychoanalysesphotosynthesisphotosynthesesamniocentesisamniocentesesmetamorphosistoxoplasmosistoxoplasmosesendometriosisendometriosestuberculosistuberculosespathogenesispathogenesesosteoporosisosteoporosesparenthesisparenthesesanastomosisanastomosesperistalsisperistalseshypothesishypothesesantithesisantithesesapotheosisapotheosesthrombosisthrombosesdiagnosisdiagnosesparalysisparalysesprognosisprognosescirrhosiscirrhosessclerosissclerosespsychosispsychosesapoptosisapoptosessymbiosissymbiosesconsensusconsensuses
censuscensuses
sphinxsphinxes
larynxlarynges	lynx
lynxespharynxpharynxesphalanxphalanxesen	wordmanlousemousetooth	foot	zooncissisxis	trixeauieuchshssalfelfolfeafarf	nife	life	wifeayeyiyoyuyyiesaoeoiooouoosesxmen	lice	miceteethgeese	feetzoa	ches	shes	sses
trices	eaux	ieuxalveselvesolveseavesarvesnivesliveswivesayseysiysoysuysaoseosiosoosuoscessesxesoes[^a-zA-Z\s]esesingular
plural	deafvescultureAND()NOT (WHERECatalogNameSchemaName%	 OR  AND  LIKE @pv�m

              SELECT 

                  v.CatalogName

              ,   v.SchemaName                           

              ,   v.Name

              ,   v.ColumnName

              ,   v.Ordinal

              ,   v.IsNullable

              ,   v.TypeName

              ,   v.MaxLength

              ,   v.Precision

              ,   v.DateTimePrecision

              ,   v.Scale

              ,   v.IsIdentity

              ,   v.IsStoreGenerated

              ,   CASE WHEN pk.IsPrimaryKey IS NULL THEN false ELSE pk.IsPrimaryKey END as IsPrimaryKey

            FROM (

              SELECT

                  v.CatalogName

              ,   v.SchemaName                           

              ,   v.Name

              ,   c.Id as ColumnId

              ,   c.Name as ColumnName

              ,   c.Ordinal

              ,   c.IsNullable

              ,   c.ColumnType.TypeName as TypeName

              ,   c.ColumnType.MaxLength as MaxLength

              ,   c.ColumnType.Precision as Precision

              ,   c.ColumnType.DateTimePrecision as DateTimePrecision

              ,   c.ColumnType.Scale as Scale

              ,   c.IsIdentity

              ,   c.IsStoreGenerated

              FROM

                  SchemaInformation.Views as v 

                  cross apply 

                  v.Columns as c ) as v 

            LEFT OUTER JOIN (

              SELECT 

                  true as IsPrimaryKey

                , pkc.Id

              FROM

                  OfType(SchemaInformation.ViewConstraints, Store.PrimaryKeyConstraint) as pk

                  CROSS APPLY pk.Columns as pkc) as pk

            ON v.ColumnId = pk.Id                   

             t�o

              SELECT 

                  t.CatalogName

              ,   t.SchemaName                           

              ,   t.Name

              ,   t.ColumnName

              ,   t.Ordinal

              ,   t.IsNullable

              ,   t.TypeName

              ,   t.MaxLength

              ,   t.Precision

              ,   t.DateTimePrecision

              ,   t.Scale

              ,   t.IsIdentity

              ,   t.IsStoreGenerated

              ,   CASE WHEN pk.IsPrimaryKey IS NULL THEN false ELSE pk.IsPrimaryKey END as IsPrimaryKey

            FROM (

              SELECT

                  t.CatalogName

              ,   t.SchemaName                           

              ,   t.Name

              ,   c.Id as ColumnId

              ,   c.Name as ColumnName

              ,   c.Ordinal

              ,   c.IsNullable

              ,   c.ColumnType.TypeName as TypeName

              ,   c.ColumnType.MaxLength as MaxLength

              ,   c.ColumnType.Precision as Precision

              ,   c.ColumnType.DateTimePrecision as DateTimePrecision

              ,   c.ColumnType.Scale as Scale

              ,   c.IsIdentity

              ,   c.IsStoreGenerated

              FROM

                  SchemaInformation.Tables as t 

                  cross apply 

                  t.Columns as c ) as t 

            LEFT OUTER JOIN (

              SELECT 

                  true as IsPrimaryKey

                , pkc.Id

              FROM

                  OfType(SchemaInformation.TableConstraints, Store.PrimaryKeyConstraint) as pk

                  CROSS APPLY pk.Columns as pkc) as pk

            ON t.ColumnId = pk.Id                   

            tvf�E

              SELECT 

                  tvf.CatalogName

              ,   tvf.SchemaName                           

              ,   tvf.Name

              ,   tvf.ColumnName

              ,   tvf.Ordinal

              ,   tvf.IsNullable

              ,   tvf.TypeName

              ,   tvf.MaxLength

              ,   tvf.Precision

              ,   tvf.DateTimePrecision

              ,   tvf.Scale

              ,   false as IsIdentity

              ,   false as IsStoreGenerated

              ,   false as IsPrimaryKey

            FROM (

              SELECT

                  t.CatalogName

              ,   t.SchemaName                           

              ,   t.Name

              ,   c.Id as ColumnId

              ,   c.Name as ColumnName

              ,   c.Ordinal

              ,   c.IsNullable

              ,   c.ColumnType.TypeName as TypeName

              ,   c.ColumnType.MaxLength as MaxLength

              ,   c.ColumnType.Precision as Precision

              ,   c.ColumnType.DateTimePrecision as DateTimePrecision

              ,   c.ColumnType.Scale as Scale

              FROM

                  OfType(SchemaInformation.Functions, Store.TableValuedFunction) as t 

                  cross apply 

                  t.Columns as c ) as tvf

            r.FromTabler.ToTable�=

              SELECT

                 r.ToTable.CatalogName as ToTableCatalog

               , r.ToTable.SchemaName as ToTableSchema

               , r.ToTable.Name as ToTableName

               , r.ToColumnName

               , r.FromTable.CatalogName as FromTableCatalog

               , r.FromTable.SchemaName as FromTableSchema

               , r.FromTable.Name as FromTableName

               , r.FromColumnName

               , r.Ordinal

               , r.RelationshipName

               , r.RelationshipId

               , r.IsCascadeDelete

              FROM (

               SELECT 

                    fks.ToColumn.Parent as ToTable

               ,    fks.ToColumn.Name as ToColumnName

               ,    c.Parent as FromTable

               ,    fks.FromColumn.Name as FromColumnName

               ,    fks.Ordinal as Ordinal

               ,    c.Name as RelationshipName

               ,    c.Id as RelationshipId

               ,    c.DeleteRule = 'CASCADE' as IsCascadeDelete

            FROM 

                OfType(SchemaInformation.TableConstraints, Store.ForeignKeyConstraint) as c,

                ( SELECT 

                   Ref(fk.Constraint) as cRef

                 ,  fk.ToColumn

                 , fk.FromColumn

                 , fk.Ordinal

                FROM

                   c.ForeignKeys as fk) as fks

                WHERE fks.cRef = Ref(c)) as r

                INOUTINOUTsp�� 

            ORDER BY

                sp.SchemaName

            ,   sp.Name

            ,   sp.Ordinal

            'RelationshipDetailsPkCatalogPkSchemaPkTablePkColumnFkCatalogFkSchemaFkTableFkColumnOrdinal!RelationshipNameRelationshipIdIsCascadeDeleteTableDetailsTableNameColumnNameDataTypeMaximumLength#DateTimePrecisionIsIdentity#IsServerGeneratedIsPrimaryKeyEdm	<!---->FunctionImportCollection(AggregateBuiltInNiladicFunctionIsComposable-ParameterTypeSemantics#StoreFunctionNameCommandTextCollectionType	ModeComplexTypeBaseTypeAssociationRowType+ReferentialConstraintPrincipalDependent	RolePropertyRefEndMultiplicityOnDelete
Action*1	0..1EntityTypeAbstract	trueKey%NavigationPropertyRelationshipFromRole
ToRoleMaxDefaultValue'ClientAutoGeneratedConcurrencyModeCollation=GetAssociatedFacetDescriptionsNamespaceAlias	Self+UseStrongSpatialTypesfalseProvider+ProviderManifestTokenxmlnsEntityContainer%LazyLoadingEnabledAssociationSetEntitySetDefiningQueryTableCollection({0})factoryGetService, {0}&&amp;<	&lt;>	&gt;'
&apos;"
&quot;lookupsstoreContainermodelContainer-EntityContainerMapping-StorageEntityContainer%CdmEntityContainer+FunctionImportMappingFunctionName%FunctionImportNameResultMapping%ComplexTypeMappingTypeName+AssociationSetMappingStoreEntitySetCondition
IsNullEndProperty!EntitySetMapping#EntityTypeMappingMappingFragmentScalarPropertyMappingSpaceC-S~//aNo Conceptual Schema node to embed as a resource[No Storage Schema node to embed as a resourceMNo Mapping node to embed as a resource.ssdl	.mslcsTransformTextSourceCsdlPath%ReferenceCsdlPaths
Errors/EdmToObjectNamespaceMap	eeth	eeseeetoaan	ouse	ooth	ooseootoonffe�;

            SELECT

                  sp.SchemaName

                , sp.Name 

                , sp.ReturnTypeName

                , sp.IsAggregate

                , sp.IsComposable

                , sp.IsBuiltIn

                , sp.IsNiladic

                , sp.ParameterName

                , sp.ParameterType

                , sp.Mode

            FROM (  

            (SELECT

                  r.CatalogName as CatalogName

              ,   r.SchemaName as SchemaName

              ,   r.Name as Name

              ,   r.ReturnType.TypeName as ReturnTypeName

              ,   r.IsAggregate as IsAggregate

              ,   true as IsComposable

              ,   r.IsBuiltIn as IsBuiltIn

              ,   r.IsNiladic as IsNiladic

              ,   p.Name as ParameterName

              ,   p.ParameterType.TypeName as ParameterType

              ,   p.Mode as Mode

              ,   p.Ordinal as Ordinal

            FROM

                OfType(SchemaInformation.Functions, Store.ScalarFunction) as r 

                 OUTER APPLY

                r.Parameters as p)

            UNION ALL

            (SELECT

                  r.CatalogName as CatalogName

              ,   r.SchemaName as SchemaName

              ,   r.Name as Name

              ,   CAST(NULL as string) as ReturnTypeName

              ,   false as IsAggregate

              ,   false as IsComposable

              ,   false as IsBuiltIn

              ,   false as IsNiladic

              ,   p.Name as ParameterName

              ,   p.ParameterType.TypeName as ParameterType

              ,   p.Mode as Mode

              ,   p.Ordinal as Ordinal

            FROM

                SchemaInformation.Procedures as r 

                 OUTER APPLY

                r.Parameters as p)) as sp

            �3

            Function IsTvf(f Store.Function) as (f is of (Store.TableValuedFunction))

            SELECT

                  sp.CatalogName

                , sp.SchemaName

                , sp.Name 

                , sp.ReturnTypeName

                , sp.IsAggregate

                , sp.IsComposable

                , sp.IsBuiltIn

                , sp.IsNiladic

                , sp.IsTvf

                , sp.ParameterName

                , sp.ParameterType

                , sp.Mode

            FROM (  

            (SELECT

                  r.CatalogName as CatalogName

              ,   r.SchemaName as SchemaName

              ,   r.Name as Name

              ,   TREAT(r as Store.ScalarFunction).ReturnType.TypeName as ReturnTypeName

              ,   TREAT(r as Store.ScalarFunction).IsAggregate as IsAggregate

              ,   true as IsComposable

              ,   r.IsBuiltIn as IsBuiltIn

              ,   r.IsNiladic as IsNiladic

              ,   IsTvf(r) as IsTvf

              ,   p.Name as ParameterName

              ,   p.ParameterType.TypeName as ParameterType

              ,   p.Mode as Mode

              ,   p.Ordinal as Ordinal

            FROM

                SchemaInformation.Functions as r 

                 OUTER APPLY

                r.Parameters as p)

            UNION ALL

            (SELECT

                  r.CatalogName as CatalogName

              ,   r.SchemaName as SchemaName

              ,   r.Name as Name

              ,   CAST(NULL as string) as ReturnTypeName

              ,   false as IsAggregate

              ,   false as IsComposable

              ,   false as IsBuiltIn

              ,   false as IsNiladic

              ,   false as IsTvf

              ,   p.Name as ParameterName

              ,   p.ParameterType.TypeName as ParameterType

              ,   p.Mode as Mode

              ,   p.Ordinal as Ordinal

            FROM

                SchemaInformation.Procedures as r 

                 OUTER APPLY

                r.Parameters as p)) as sp

            �N��(0K�'Q�Z`,     %   e m � �9��  ����	 �9 �5��4�9���9�������9�����������y���� ��  � � �
 ��  ��	�� ��-���������������������������� �� ���� 
 �	�
� �� ������ 

���0
�� �������������� ��
 �������
 �����	 ������  �)����������
 �������������0
0�
�	��� ������
�4���	
 ���		���	
�	�������	���	��

 �%�)�%�)   �����  �� �� ������	 ���� ��M�M
 ���M��M  �- �Y �] �% � � �%�U�]�]�9���%�]����9���]�]�q���]  �]��5 �9 ���]�]�q �U	�U  �E �U ���U �U������ ��	����  ��  �Y��   �� �e �a    �q�%
 ���� �U�u�U��A�a�%���I���������m��������������������  �y �% �} �} �e
 ������������ �a��� �� ������������ ������������ �� �� �U � �% �� �������%%�m�%�����]�����q�q �%���� �� �U�%
 ���U	 �U�U
 �U�� ������ �U�U3�����%���U���������������U�����U
 ������������ �A��U�U�����U
 �%�U �U������%�����������H
0��
�����������I�a��������� �a�@ �) �44��4���4
����4  44�D	���H44�H���H ��4�944��4�94�D��4�9444	�H�H   �)	�������������
 ������ ���'��]���	���9����X�I�	 �� �� ��� �I �I��P��L�P��L�P��L ��m �i;�%���m���U�����������U�q���
�U���q ��	 �%�U������������m�%���m�������������q ���	 ���U	������q�!�����U���!���X��%�)
 ���)���)���-�	�U�� ���	�	�	�	�� 

���1�5 �5�5����q��������e �e �� ���%���a�I������P
����������P�����������%��=�A�����������P�%���E�U���U�������
 �%�U�������%�I��% ������M�%�I�M�%���M�%�%�I�M�%�%	 ����M�%  ��	�M�%	�%�%>����Q���M��U�U�U�U�Y��M�	���	 �U�Q���M� �Y	�Y� �M	�a�a �a	�a�a  �-��M��M���M�	�M�
 �� ttt������
txxx
x
�u
��'�����y���y�9�u�u�y�

���u �u���y���u�9�u:
�������y���y�}�����9�y�����
���y���q4
�����y�u�������u�u�������� ���y���y�u ���u���y�u ����'�������u����-����
 �����u ���� ���� 
	����
�����&���`�����u�5���5���5���1�u�� �� �
 �
	 ����	 ���� ���������� �	 ���� ���������� ���` ��
��
��
��
��	��������	����
�����d����������������������������������9�������9�������������������������E�E�E������ ���� � �E������������������9�� �������9�� ������������-
�%�� �%��� ��������������� �������� �����E�E���E�E���E�E	�M�M�0
�����9�����l���������%���������9������������������
����
��	����
�������� ���%�
 �%�A����Q�Q ��� ����
������������	�%��*	������������������������ ���� ��H�������������������������������������������������������
 ������������������������������������������������E������	����
 ��������/��������������������E���� �������	�%�� �%������
���  �E������Y���M����	 � �E �M �����M ���������E�����������������M�������M�M$	��E�M�Y�����i�M�M
 ���i���i���i �����M�Y
 �������	�M�Y	��������	���������M�M�� �i�i����������������� �% �i
�������Y �������M �I
 �I�Y ����  �p������
������
������
���t������ ������������,���������9������������
������9�� ��
 ���� �����q��
����	����	������ ��������
����B��������9�������Q�]���a��������� ��
���5
�5
���M���������Y���M��	�Y��	�M����+�����A�Y���M��������		 �� �����U�
�9�����=�
 �
 ��U���a ���

��� ���u�������  �������u��������
��� �����	���
���

��
�� �I
��������

����@���!�%�)�-���9��������E�E���������%�)�% �! �-
 �%�-�����9�����������E��E�����������%�)�!�5�9 �!	 �5�!?�u�u�u�5�-�����������������5� �u	 � ���u
���
0�������� �e���}�9���������i�M�����������������������������H������������������%���������%�A��������������%�U�%��U�����9�E���������E�9�EB��������Y���M�Y�M�E�����9�����9����	�������E������������
�E�������9����������
�������i�������� �����������������	�I�M����������������������!�M������q������!��������9�E������
 H�������������������9�������������q�q�	���
��������������� ����G�����9�������)�)�)�Q�����)���)���)�)����9�
 ���m	���m���m�)%��������	
�m�)	���) �m	�)�m �Q�Q�m�%����)���5�U�����������	 �U�U��!�5�������Y���u���u�����u�� �������u'�]���M�a�a�e���������e��	�]�a���M�a �i�m�a��	�M�a�q���M�a�u�]�a �5��a �% �y�} ������������ #�������9�u�u�����u������
��u
��u������.�������������������������
���=
�q���q��
�q��|��������
������ �u�

��u�y����� ��
 �y�u �}
���q����
�q �	��
��
��	�� ��	�� ��
��	�� ��	�� �� ��   �� ������ �� ��
�������9�����1�	����������������
���������9���������E���E���������E ���� ��  �� �E
���E�� 
��������������� �� ����� ������ �� ����	 ���� ��� �� �� �� ���� ������ ��� � �9 �����3��9�����9������������ ��9���� �� ���������� ���-�%����������% ��
�����i�i��������������
�����������q��������������
 ��������������� �% )����m���)�)�m�9�m�m�����)���m�9�m�)�a	 �a�Q�M�M ���������9����
��������9��	���
�����9�������)
�%�� ��=�����������5�1�
 ������9����
�9�u�u
��P������������������������������������������������������������������������������������������������Y����!���������������������������������������� ��������������
������	 ���� 	��������	 ���'	�������u���������9���� ���	 ���� 	�	��	0�8	�P��%�%	�����|��	������������������������������	0
�� ��
�9��������9���� �)��Q �a�Q�!��% ���Q�!���% ����q �q	���E
�E������	���E
�E	�E

 �-���������������������������������y�������y�����z\V4��?_�
:FEntityStoreGeneratorSchemaNotLoadedFEntityModelGeneratorSchemaNotLoaded:StonglyTypedAccessToNullValue&NoPrimaryKeyDefined0InvalidTypeForPrimaryKeyRCannotCreateEntityWithNoPrimaryKeyDefinedNTableReferencedByAssociationWasNotFound>TableReferencedByTvfWasNotFound&UnsupportedDataType<UnsupportedDataTypeUnknownTypeBUnsupportedFunctionReturnDataTypeHUnsupportedFunctionParameterDataType8UnsupportedDataTypeForTargetTUnsupportedFunctionReturnDataTypeForTargetZUnsupportedFunctionParameterDataTypeForTarget2UnsupportedDbRelationship4ParameterDirectionNotValid*InvalidStringArgument>Serialization_UnknownGlobalItem"ReservedNamespace4ColumnFacetValueOutOfRange6AssociationMissingKeyColumnDSingleStoreEntityContainerExpected<InvalidNonStoreEntityContainerTExcludedColumnWasAKeyColumnEntityIsInvalidVExcludedColumnWasAKeyColumnEntityIsReadOnlyBModelGeneration_UnGeneratableType8DuplicateEntityContainerNameDProviderFactoryReturnedNullFactory(ProviderSchemaErrors8InvalidNamespaceNameArgumentDInvalidEntityContainerNameArgumentBEntityClient_InvalidStoreProviderRDbProviderServicesInformationLocationPath8UnsupportedForeignKeyPatternXUnsupportedQueryViewInEntityContainerMapping SharedForeignKey,UnmappedFunctionImport<CannotChangePropertyReturnTypeHCannotChangePropertyReturnTypeToNull>CodeGenSourceFilePathIsNotAFile>InvalidAttributeSuppliedForType8InvalidMemberSuppliedForType>InvalidInterfaceSuppliedForTypeFInvalidAttributeSuppliedForPropertyLInvalidGetStatementSuppliedForPropertyLInvalidSetStatementSuppliedForProperty>PropertyExistsWithDifferentCase@EntitySetExistsWithDifferentCase6ItemExistsWithDifferentCase(NullAdditionalSchema$DuplicateClassNamepTargetEntityFrameworkVersionToNewForEntityClassGenerator8MissingPropertyDocumentation>MissingComplexTypeDocumentation(MissingDocumentation4MissingDocumentationNoName"NamespaceComments6FactoryMethodSummaryComment4FactoryParamCommentGeneral$CtorSummaryComment.EmptyCtorSummaryCommentNGeneratedNavigationPropertyNameConflictLGeneratedPropertyAccessibilityConflictJEntityTypeAndSetAccessibilityConflictDGeneratedFactoryMethodNameConflictNMetadataItemErrorsFoundDuringGenerationRUnableToGenerateForeignKeyPropertiesForV1VUnableToGenerateFunctionImportParameterNameTypeComments.GetViewAtMethodComments&ConstructorComments,IndividualViewCommentsDTargetVersionSchemaVersionMismatch<DuplicateEntryInUserDictionaryRUnsupportedLocaleForPluralizationServices<Template_DuplicateTopLevelTypePTemplate_ConflictingGeneratedNavPropNameDTemplate_FactoryMethodNameConflictHTemplate_CaseInsensitiveTypeConflictRTemplate_CaseInsensitiveEntitySetConflictLTemplate_CaseInsensitiveMemberConflict@Template_GenCommentAddToMethodCs@Template_GenCommentAddToMethodVb>Template_CommentNoDocumentationDTemplate_CommentFactoryMethodParamDTemplate_GeneratedCodeCommentLine1DTemplate_GeneratedCodeCommentLine2DTemplate_GeneratedCodeCommentLine3DTemplate_ContextDefaultCtorCommentBTemplate_ContextCommonCtorComment:Template_FactoryMethodComment8Template_RegionRelationships.Template_RegionContextsDTemplate_RegionObjectSetProperties6Template_RegionAddToMethods<Template_RegionFunctionImports.Template_RegionEntitiesFTemplate_RegionNavigationProperties6Template_RegionComplexTypes8Template_RegionFactoryMethodDTemplate_RegionPrimitiveProperties>Template_RegionSimpleProperties@Template_RegionComplexProperties0Template_RegionEnumTypes6Template_RegionConstructors:Template_RegionPartialMethodsFTemplate_ReplaceVsItemTemplateTokenBTemplate_CurrentlyRunningTemplate4Template_UnsupportedSchema"EdmSchemaNotValid*EdmSchemaFileNotFound2EntityCodeGenTargetTooLow4DefaultTargetVersionTooLowZEntityClient_DoesNotImplementIServiceProviderREntityClient_ReturnedNullOnProviderMethodContext class 	
InternalProtectedPublicPrivate
Value,InlineObjectCollection DetachFromParent0IEntityWithRelationshipsObjectContextEntitySetObjectResultTSystem.Data.Metadata.Edm.MetadataWorkspace&System.Data.Objects>System.Data.Objects.DataClasses0System.Data.Metadata.Edm0System.Data.EntityClientSetValidValue,ReportPropertyChanging*ReportPropertyChangedGetValidValue8VerifyComplexObjectIsNotNullEdmxZhttp://schemas.microsoft.com/ado/2007/06/edmxZhttp://schemas.microsoft.com/ado/2008/10/edmxZhttp://schemas.microsoft.com/ado/2009/11/edmx
ModelApplication��http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGeneratornhttp://schemas.microsoft.com/ado/2009/02/edm/annotationTypeSchemaNameTables
Views*StoreGeneratedPattern$LazyLoadingEnabledannotationContainerXTemplateCodeGenerators.CSharpCodeGenTemplatePTemplateCodeGenerators.VBCodeGenTemplate^TemplateCodeGenerators.CSharpCodeGenTemplateV50VTemplateCodeGenerators.VBCodeGenTemplateV50^TemplateCodeGenerators.CSharpCodeGenTemplate.csfTemplateCodeGenerators.CSharpCodeGenTemplateV5.0.csVTemplateCodeGenerators.VBCodeGenTemplate.vb^TemplateCodeGenerators.VBCodeGenTemplateV5.0.vbpqrstuvwxyz{|}~������������������������������PkCatalogPkSchemaPkTablePkColumnFkCatalogFkSchemaFkTableFkColumnOrdinal RelationshipNameRelationshipIdIsCascadeDeleteCatalogNameSchemaNameTableNameColumnNameIsNullableDataTypeMaximumLengthPrecision"DateTimePrecision
ScaleIsIdentity"IsServerGeneratedIsPrimaryKey, ��������8|	����`�]�u�U<�@����4���y
�P��LL���%�I��%�I�M�%�I�M�%�%���M���ptx��	����	���]��	���	���e�`����������������������	��������������1�����������������������	��	�<�D�H�T�\	����������E�������h
����
����
����
�������x
����������	���E	�������������i��
����	����	���	����������������	��������������
���������������E����
���m���m�)�q���a�������q����
����������
���E
���E�����E���E��
������������������������E�E���M�M������������	��������������	�����������������y����	������� ����|���� �� ��
 ����	������� �� ` ��
 ��� ����
 ����
 ���� ��� ���
 ���� �%�	 �%� 8  �) �� �� �E �Q�M �U�Y ` 0�a ��a \�a X�a	 X�a
 ��e �i�m���] �e P�m���] $�a �]�] �m	�y�}���y�}	�}
���}	���}�}	�} �� �a �� ���U	�U�%�U  �� �� ���	 ���� ���� �m�� ���� ���� �U����� �������� �� �� < �� < <��
 ������	����
 ����	 �����D  4�H���H �� ����4 �y �y���������������������y	���y����	������ 
 ���� �� X��	 ��	 �m�i
���) ��	 �%�i��i ���i	 �� �m�%	 �a�%��` �� �m���] �m���� �����
8����	 ��0�U	 �%����% ��� �U�� �U	 �U��
 �m���%	 �%�%	 �y �� �a���] �a��� �a���e �� �� �� �a�%�% �%� �%��% �% �% �%�M	 �%�%
 �%�% �%�M�% �%�%���M��U�]���e�i�i�L
��-�)�	�� �q 	 �� ��
 ������ �� ��
 ������ t x p �����u�� �����u�����u ���� ������ �y���y��������������������� ���� �� ��
 �y�%
 ����
 ���]	 ���%
 ���
 ���e��������	��������
 �� �� ������ �� ��
 ����
 ������	 �d�� ����� ���d��
 �����d	 �d��	 �d�� �d ���d�� ���d�� ���d���	 ���% ���d�� ���d�� ���d���� �E�d�E �M�Y�d�E�E ���d�E�E	����	 �d�E �d�M�M	 ��� �M�d�M�M�Y� �M�d�M��Y�� � ���� �� �� ������ �������� ����������	���� ������������
���������������������� ������������ �����������������������������������������������������������a�������	�������A	���A���������a������������u���������u�������������������u���������u���������������u�������������u�������������
��	�����
�u���� �������� �����������1
�1���5�)�!���5�������� �����E ������ �� �� �������� �%�� ������ ������������������������ �M�����Y��� ���E�M�M���������E2 �����E�M������q�������� ������q������' ����������������� ����������q	 ���� �5����	 ���5 �M �������� ������ �����u���� �����u�����u�� ����������
 �u�� ������ �����u�� �������������� ���������u���q��
���
 �� ��  �� ������
�����������1��
 ������ ���E���� �10 ���E�����E���E�����������1������
�������������1������ �1���� �A �� �� �� �� �E�� �� �� �����	�����9�9�q	�9���	���
����������=	�=�����
 �������������M"	������������M�� � �� �� �E �� �i���� �� �Y �� �� �%	 �)�m �)
 ���m�  ��% �% �� �M �� �� �y ������=	���=���=��������u���	��� �������� ������	 ���� ������	 ������������ ������������ ������ ������ ��  
���� ���y ��
���������� � �	
 �9��
 ���� ��	 X�� ������ X�� `�� `���
 `���
�%`�%�
 `��
�%`�% �� �� ���� �� �9
 �9�� ��
 ���� �� �� ���i	 ����
 ����
 ���� ����	 ����
 ����
 ��
 ��� ��q��	 ��	���� �� ��
 �����E
 ������ �m �)�m �	 �������� �q ���q �� ���� ���E���E �E �E �� ��  ��  �
 ���� ���Y�� �������Y��	����	 ���������� ���� ��
 �9��(����(��(`(��((8((�)(�E(���U((��(��(<(����4(�y(��(�%(��(�(��(��(��(�q(((p
(����
(���]
(���
(���e��(��(��(��(��(��(��(��(��(��(�!(�1(��(��(��((��
(����(��(�}(��	(��((��(��
(����(��$TSkipVerificationInFullTrust"System.Data.Entity.Design.dllMicrosoft CorporationMicrosoft® .NET Framework4/© Microsoft Corporation.  All rights reserved.
4.8.4161.04.0.0.0
en-US)$f:\dd\tools\devdiv\EcmaPublicKey.snk�H�@002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a235e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f302d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd911f0571aaf3d54da12b11ddec375b3�a5a866e1ee186f807668209f3b11236ace5e21f117803a3143abb126dd035d7d2f876b6938aaf2ee3414d5420d753621400db44a49c486ce134300a2106adb6bdb433590fef8ad5c43cba82290dc49530effd86523d9483c00f458af46890036b0e2c61d077d7fbac467a506eba29e467a87198b053c749aa2a4d2840c784e6dTWrapNonExceptionThrowsE@System.Data.EntityModel.ClientApiGenerator+<GetSourceTypes>d__33JESystem.Data.Entity.Design.EntityViewGenerator+<SplitViewStrings>d__28]XSystem.Data.Entity.Design.EntityViewGenerator+<GetViewStringsAppendToStringBuilder>d__29b]System.Data.Entity.Design.EntityStoreSchemaGenerator+LoadMethodSessionState+<get_Errors>d__20�	Item94Catalog={Catalog}, Schema={Schema}, Name={TableName}�O����lSystem.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089#System.Resources.RuntimeResourceSettPADPADP�/8�m�m�m�D�7���7�O^����<��͎�!�f���K���U�̧��D����_�G[�|��ջy�DS� c��,s��&��a=����	�&°E{�[�a�p���w��ܠ�����sc�=�"�D��mq͒��Ni����ƹ�OX:��(?���ڴ����(���h���{����!�L��搠�O����"�y���NE���
<��>��v��:���n�xT��1�E���GW��5>��4Vq �
���IBv�6RkKy�jP����8�!�	>$��t*�2�+���,���.�ٺ/�(�1�6q30�!4���8��,:Sv&<l�<=��?5��@��%D[4DT*RE�u�F��J��K�9Nj�yNлQ��&QZU1W�Z���d�w�e�o�g-��h]b*m}m�an~�wi�&xhp�z=�{
��|qj�~k��B�o|V�_;���V	c��l
�V�b�<��7�go
�
���
G/
��m�
 ���;�^	��T�	l���	�wD
���e.�&��w�
aPz#.3-�`} �t�6���f /
����'����0�t"6AssociationMissingKeyColumn<CannotChangePropertyReturnType�HCannotChangePropertyReturnTypeToNull�RCannotCreateEntityWithNoPrimaryKeyDefinedG>CodeGenSourceFilePathIsNotAFile14ColumnFacetValueOutOfRangej&ConstructorComments$CtorSummaryComment�RDbProviderServicesInformationLocationPath�4DefaultTargetVersionTooLow�$DuplicateClassNameT8DuplicateEntityContainerName�<DuplicateEntryInUserDictionary�*EdmSchemaFileNotFound�"EdmSchemaNotValid�.EmptyCtorSummaryCommentZEntityClient_DoesNotImplementIServiceProvider�BEntityClient_InvalidStoreProvider REntityClient_ReturnedNullOnProviderMethod�2EntityCodeGenTargetTooLow	FEntityModelGeneratorSchemaNotLoaded�	@EntitySetExistsWithDifferentCase�	FEntityStoreGeneratorSchemaNotLoadedp
JEntityTypeAndSetAccessibilityConflict�
TExcludedColumnWasAKeyColumnEntityIsInvalid�VExcludedColumnWasAKeyColumnEntityIsReadOnlyE6FactoryMethodSummaryComment�4FactoryParamCommentGeneral�DGeneratedFactoryMethodNameConflict
NGeneratedNavigationPropertyNameConflictc
LGeneratedPropertyAccessibilityConflict�
.GetViewAtMethodComments�,IndividualViewComments�FInvalidAttributeSuppliedForProperty�>InvalidAttributeSuppliedForTypeDInvalidEntityContainerNameArgumentNLInvalidGetStatementSuppliedForProperty�>InvalidInterfaceSuppliedForType�8InvalidMemberSuppliedForType,8InvalidNamespaceNameArgumenti<InvalidNonStoreEntityContainer�LInvalidSetStatementSuppliedForProperty�*InvalidStringArgument70InvalidTypeForPrimaryKeyx6ItemExistsWithDifferentCaseJNMetadataItemErrorsFoundDuringGeneration�>MissingComplexTypeDocumentation�(MissingDocumentation4MissingDocumentationNoNameE8MissingPropertyDocumentationkBModelGeneration_UnGeneratableType�"NamespaceComments�&NoPrimaryKeyDefined(NullAdditionalSchema�4ParameterDirectionNotValid�>PropertyExistsWithDifferentCasenDProviderFactoryReturnedNullFactory�(ProviderSchemaErrors?"ReservedNamespace�>Serialization_UnknownGlobalItem� SharedForeignKey�DSingleStoreEntityContainerExpected�:StonglyTypedAccessToNullValue<NTableReferencedByAssociationWasNotFoundr>TableReferencedByTvfWasNotFound�pTargetEntityFrameworkVersionToNewForEntityClassGenerator�DTargetVersionSchemaVersionMismatch�RTemplate_CaseInsensitiveEntitySetConflict	LTemplate_CaseInsensitiveMemberConflict�HTemplate_CaseInsensitiveTypeConflictDTemplate_CommentFactoryMethodParam�>Template_CommentNoDocumentation�PTemplate_ConflictingGeneratedNavPropName�BTemplate_ContextCommonCtorCommentqDTemplate_ContextDefaultCtorComment�BTemplate_CurrentlyRunningTemplate<Template_DuplicateTopLevelType':Template_FactoryMethodComment�DTemplate_FactoryMethodNameConflict�@Template_GenCommentAddToMethodCs@Template_GenCommentAddToMethodVb�DTemplate_GeneratedCodeCommentLine1B DTemplate_GeneratedCodeCommentLine2o DTemplate_GeneratedCodeCommentLine3� 6Template_RegionAddToMethods!@Template_RegionComplexProperties!!6Template_RegionComplexTypes5!6Template_RegionConstructorsC!.Template_RegionContextsQ!.Template_RegionEntities[!0Template_RegionEnumTypese!8Template_RegionFactoryMethodl!<Template_RegionFunctionImports|!FTemplate_RegionNavigationProperties�!DTemplate_RegionObjectSetProperties�!:Template_RegionPartialMethods�!DTemplate_RegionPrimitiveProperties�!8Template_RegionRelationships�!>Template_RegionSimpleProperties�!FTemplate_ReplaceVsItemTemplateToken"4Template_UnsupportedSchema�"TypeCommentsJ#RUnableToGenerateForeignKeyPropertiesForV1�#VUnableToGenerateFunctionImportParameterName
$,UnmappedFunctionImport�$&UnsupportedDataTypeB%8UnsupportedDataTypeForTarget�%<UnsupportedDataTypeUnknownType�&2UnsupportedDbRelationship'8UnsupportedForeignKeyPattern�'HUnsupportedFunctionParameterDataType�(ZUnsupportedFunctionParameterDataTypeForTarget�)BUnsupportedFunctionReturnDataType�*TUnsupportedFunctionReturnDataTypeForTarget.+RUnsupportedLocaleForPluralizationServices,XUnsupportedQueryViewInEntityContainerMappingv,�The association between '{0}' and '{1}' will not be created because the key column '{2}' was not found to be part of the table definition (see previous warnings).KThe return data type of property '{0}' on the type '{1}' cannot be changed.SThe return data type of property '{0}' on the type '{1}' cannot be changed to null.�The table/view '{0}' does not have a primary key defined and no valid primary key could be inferred. This table/view has been excluded. To use the entity, you will need to review your schema, add the correct keys, and uncomment it.7The parameter must specify a single file, not multiple.�The facet '{0}' with a value '{1}' is outside the range {2}-{3} specified by the facet description.  The column '{4}' in the table '{5}' was excluded.�The constructor stores the views for the extents and also the hash values generated based on the metadata and mapping closure and views.Initialize a new {0} object.DbProviderServices://{0}/{1}�The default target Entity Framework version requires the edmx schema version {0} or lower. The specified schema is version {1}. To avoid this warning specify the target Entity Framework version explicitly. You can do this by using the EdmGen.exe command-line tool with the targetVersion option, or by including the targetEntityFrameworkVersion parameter when calling the GenerateCode method.�The {0} '{1}' has the same name as the {2} '{1}'. Duplicate names are not allowed. You must change the name of either the {0} or the {2}.�An EntityContainer with the name '{0}' already exists in the EdmItemCollection containing the EntityContainer '{1}'. Please choose a different model EntityContainer name.BThe {0} value '{1}' already exists in the user-defined dictionary.Could not find file '{0}'.%The EDM Schema argument is not valid.zInitializes a new {0} object using the connection string found in the '{1}' section of the application configuration file.�The store provider factory type '{0}' does not implement the IServiceProvider interface. Use a store provider that implements this interface._The specified store provider '{0}' cannot be found in the configuration, or '{0}' is not valid.�A null was returned after calling the '{0}' method on a store provider instance of type '{1}'. The store provider might not be functioning correctly.�The EntityCodeGenerator is not for targeting EntityFrameworkVersions.Version1.  Consider using EntityClassGenerator or a template.PThe model metadata has not been generated yet. Call GenerateModelMetadata first.~The entity set '{0}' differs only in case from an existing entity set, and is not compatible with the current language option.PThe store metadata has not been generated yet. Call GenerateStoreMetadata first.�EntityType '{0}' has '{1}' accessibility and EntitySet '{2}' has a get property with '{3}' accessibility. The get property of the EntitySet must not have less restrictive access than the containing EntityType has.�The column '{0}' on the table/view '{1}' was excluded, and is a key column.  The table/view has been excluded.  Please fix the entity in the schema file, and uncomment.�The column '{0}' on the table/view '{1}' was excluded, and is a key column.  The remaining key(s) were used and table/view has been created as read-only.Create a new {0} object.Initial value of {0}.OThe member '{0}' on the type '{1}' conflicts with the generated factory method.�The NavigationProperty '{0}' on the type '{1}' is the source of a generated property '{2}' which conflicts with a member of the same name.�Property '{0}' has '{1}' Get property and '{2}' Set property accessibility specified. {1} and {2} modifiers cannot be combined within a single Property.0The method returns the view for the index given.return view for {0}>The custom attribute supplied for property '{0}' is not valid.:The custom attribute supplied for type '{0}' is not valid.TThe modelEntityContainerName parameter '{0}' contains characters that are not valid.FThe additional get statement supplied for property '{0}' is not valid.>The additional interface supplied for type '{0}' is not valid.;The additional member supplied for type '{0}' is not valid.IThe namespaceName parameter '{0}' contains characters that are not valid.9The EntityContainer '{0}' is not a store EntityContainer.FThe additional Set statement supplied for property '{0}' is not valid.?Parameter '{0}' is not valid. String arguments cannot be empty.�The table/view '{0}' has column '{1}' defined as a primary key, but the column type '{2}' is not a valid type for a key in the EDM. An attempt will be made to define the table/view as a read-only table/view.pThe {0} '{1}' differs only in case from an existing {0}, and is not compatible with the current language option.Errors Found During Generation:8There are no comments for ComplexType {0} in the schema.,There are no comments for {0} in the schema.$There are no comments in the schema.5There are no comments for property {0} in the schema.FThe GlobalItem of type '{0}' has no model generation patterns defined.-Original file name: {0}
Generation date: {1}
�The table/view '{0}' does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view.4The value in the parameter {0} at index {1} is null.�The function '{0}' has a parameter '{1}' that has a parameter direction value '{2}', which is not valid. Please use 'IN', 'OUT', or 'INOUT'.zThe property '{0}' differs only in case from an existing property, and is not compatible with the current language option.SThe '{0}' DbProviderFactory returned a null value from the CreateConnection method.CThe provider returned schema mapping information that is not valid.>The namespace '{0}' is a system namespace, and cannot be used.8The GlobalItem of type '{0}' is not a serializable type.�Foreign key constraint '{0}' has been omitted from the storage model. Column '{1}' of table '{2}' is a foreign key participating in multiple relationships. A one-to-one Entity Model will not validate since data inconsistency is possible.LThe StoreItemCollection collection must contain exactly one EntityContainer.4The value for column '{0}' in table '{1}' is DBNull.EThe table '{0}' is referenced by a relationship, but cannot be found.�The return table of the function '{0}' is not defined. Either all columns have been excluded or the table has no columns. The function has been excluded. To use the function, you will need to review your schema, specify the return type of the function, and uncomment it.�The EntityClassGenerator is only for use with EntityFrameworkVersions.Version1 and the schemas provided have newer versions of the Model schema.  Consider using EntityCodeGenerator or a template.wThe target Entity Framework version requires the edmx schema version {0} or lower. The specified schema is version {1}.�The EntitySet '{0}.{1}' differs only in case from an existing EntitySet, and is not compatible with the current language option.zThe Member '{0}.{1}' differs only in case from an existing Member, and is not compatible with the current language option.�The Type '{0}' is not unique.  This may be caused by the types only differing in case which is not compatible with the current language option."Initial value of the {0} property.$No Metadata Documentation available.�The NavigationProperty '{0}' on the type '{1}' is the source of a generated property '{2}' which conflicts with a member of the same name.Initialize a new {0} object.zInitializes a new {0} object using the connection string found in the '{1}' section of the application configuration file.Currently Running Template�The type name '{0}' is used for both an EntityContainer and a type.  Duplicates are not allowed, please change one of the names.Create a new {0} object.OThe member '{0}' on the type '{1}' conflicts with the generated factory method.�Deprecated Method for adding a new object to the {0} EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.�Deprecated Method for adding a new object to the {0} EntitySet. Consider using the .Add method of the associated ObjectSet(Of T) property instead.+   This code was generated from a template.Q   Manual changes to this file may cause unexpected behavior in your application.N   Manual changes to this file will be overwritten if the code is regenerated.
AddTo MethodsComplex PropertiesComplexTypesConstructorsContextsEntitiesEnumsFactory MethodFunction ImportsNavigation PropertiesObjectSet PropertiesPartial MethodsPrimitive PropertiesEDM Relationship MetadataSimple Properties�Please overwrite the replacement token '$edmxInputFile$' with the actual name of the .edmx file you would like to generate from.�The input file appears to be using a schema version not supported by this template. This may lead to compile errors. Please use 'Add New Generated Item' to add an updated template.^The type contains views for EntitySets and AssociationSets that were generated at design time.^Foreign keys may only be generated when targeting version 4.0 of the .NET Framework or higher.�Unable to generate function import parameter name for the parameter '{0}' of the store function '{1}'. The store function will be ignored and the function import will not be generated.{The function import '{0}' is not mapped to a store function. A function import needs to be mapped for successful execution.�The data type '{0}' is currently not supported for the target .NET Framework version; the column '{2}' in table '{1}' was excluded.�The data type '{0}' is not supported for the target .NET Framework version. The column '{2}' in the table '{1}' was excluded from the model. To use the data type '{0}', target the .NET Framework 4.5 or higher.mThe data type of the column '{0}' is currently not supported so the column '{0}' in table '{1}' was excluded.�The relationship '{0}' has columns that are not part of the key of the table on the primary side of the relationship. The relationship was excluded.�The relationship '{0}' uses the set of foreign keys '{1}' that are partially contained in the set of primary keys '{2}' of the table '{3}'.  The set of foreign keys must be fully contained in the set of primary keys, or fully not contained in the set of primary keys to be mapped to a model.�The function '{0}' has a parameter '{1}' at parameter index {2} that has a data type '{3}' which is currently not supported for the target .NET Framework version. The function was excluded.�The function '{0}' has the parameter '{1}' at the parameter index {2} that has the data type '{3}' which is not supported for the target .NET Framework version. The function was excluded from the model. To use the data type '{0}', target the .NET Framework 4.5 or higher.�The function '{0}' has a return data type '{1}' that is currently not supported for the target .NET Framework version. The function was excluded.�The function '{0}' returns the data type '{1}' that is not supported for the target .NET Framework version. The function was excluded from the model. To use the data type '{0}', target the .NET Framework 4.5 or higher.iThe culture '{0}' is not supported.   Pluralization is currently only supported for the English language.�The EntitySetMapping in EntityContainerMapping for entity container '{0}' contains a query view. Query views are not allowed in compile time view generation, so the view for this EntityContainerMapping will not be generated.)�// ------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version: 11.0.0.0
//  
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace TemplateCodeGenerators
{
    using System;
    using System.Linq;
    using System.IO;
    using System.Collections.Generic;
    using System.Data.Objects;
    using System.Data.Objects.DataClasses;
    using System.Xml;
    using System.Xml.Linq;
    using System.Globalization;
    using System.Reflection;
    using System.Data.Metadata.Edm;
    using System.Data.Mapping;
    using System.Data.Entity.Design;
    using System.CodeDom;
    using System.CodeDom.Compiler;
    using Microsoft.CSharp;
    using System.Text;
    
    /// <summary>
    /// Class to produce the template output
    /// </summary>

    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "11.0.0.0")]
    public partial class CSharpCodeGenTemplate : CSharpCodeGenTemplateBase
    {
        /// <summary>
        /// Create the template output
        /// </summary>
        public virtual string TransformText()
        {


// 
// 
// 
//
//  
//  
//  
//  
//  
//  
//  
//  
//
//  
//  
//  
//  





DefineMetadata();

UserSettings userSettings =
        new UserSettings
        {
            SourceCsdlPath = @"$edmxInputFile$",
            ReferenceCsdlPaths = new string[] {},
            FullyQualifySystemTypes = true,
            CreateContextAddToMethods = true,
            CamelCaseFields = false,
        };

ApplyUserSettings(userSettings);
if(Errors.HasErrors)
{
    return String.Empty;
}

MetadataLoader loader = new MetadataLoader(this);
MetadataTools ef = new MetadataTools(this);
CodeRegion region = new CodeRegion(this);
CodeGenerationTools code = new CodeGenerationTools(this){FullyQualifySystemTypes = userSettings.FullyQualifySystemTypes, CamelCaseFields = userSettings.CamelCaseFields};

ItemCollection = loader.CreateEdmItemCollection(SourceCsdlPath, ReferenceCsdlPaths.ToArray());
ModelNamespace = loader.GetModelNamespace(SourceCsdlPath);
string namespaceName = GetNamespaceName(code);
UpdateObjectNamespaceMap(namespaceName);


            this.Write("//------------------------------------------------------------------------------\r" +
                    "\n// <auto-generated>\r\n// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(GetResourceString("Template_GeneratedCodeCommentLine1")));


            this.Write("\r\n//\r\n// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(GetResourceString("Template_GeneratedCodeCommentLine2")));


            this.Write("\r\n// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(GetResourceString("Template_GeneratedCodeCommentLine3")));


            this.Write(@"
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.ComponentModel;
using System.Data.EntityClient;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml.Serialization;

[assembly: EdmSchemaAttribute()]
");


    ////////
    //////// 
    ////////
    region.Begin(GetResourceString("Template_RegionRelationships"));
    bool first = true;
    foreach (AssociationType association in GetSourceSchemaTypes<AssociationType>())
    {
        if (first)
        {
            WriteLine(string.Empty);
            first = false;
        }


            this.Write("[assembly: EdmRelationshipAttribute(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(association.NamespaceName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(association.Name));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(EndName(association, 0)));


            this.Write("\", ");

            this.Write(this.ToStringHelper.ToStringWithCulture(EndMultiplicity(association, 0, code)));


            this.Write(", typeof(");

            this.Write(this.ToStringHelper.ToStringWithCulture(EscapeEndTypeName(association, 0, code)));


            this.Write("), \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(EndName(association, 1)));


            this.Write("\", ");

            this.Write(this.ToStringHelper.ToStringWithCulture(EndMultiplicity(association, 1, code)));


            this.Write(", typeof(");

            this.Write(this.ToStringHelper.ToStringWithCulture(EscapeEndTypeName(association, 1, code)));


            this.Write(")");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.StringBefore(", ", association.IsForeignKey ? "true" : null)));


            this.Write(")]\r\n");


    }
    region.End();

    if (!String.IsNullOrEmpty(namespaceName))
    {


            this.Write("namespace ");

            this.Write(this.ToStringHelper.ToStringWithCulture(namespaceName));


            this.Write("\r\n{\r\n");


        PushIndent(CodeRegion.GetIndent(1));
    }

    ////////
    //////// 
    ////////

    region.Begin(GetResourceString("Template_RegionContexts"));
    foreach (EntityContainer container in GetSourceSchemaTypes<EntityContainer>())
    {


            this.Write("\r\n/// <summary>\r\n/// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(container)));


            this.Write("\r\n/// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(container, region.CurrentIndentLevel)));


            this.Write("\r\n");

            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForType(container)));


            this.Write(" partial class ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(container)));


            this.Write(" : ObjectContext\r\n{\r\n    #region ");

            this.Write(this.ToStringHelper.ToStringWithCulture(GetResourceString("Template_RegionConstructors")));


            this.Write("\r\n\r\n    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_ContextDefaultCtorComment"), container.Name, container.Name)));


            this.Write("\r\n    /// </summary>\r\n    public ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(container)));


            this.Write("() : base(\"name=");

            this.Write(this.ToStringHelper.ToStringWithCulture(container.Name));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(container.Name));


            this.Write("\")\r\n    {\r\n");


        WriteLazyLoadingEnabled(container);


            this.Write("        OnContextCreated();\r\n    }\r\n\r\n    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_ContextCommonCtorComment"), container.Name)));


            this.Write("\r\n    /// </summary>\r\n    public ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(container)));


            this.Write("(string connectionString) : base(connectionString, \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(container.Name));


            this.Write("\")\r\n    {\r\n");


        WriteLazyLoadingEnabled(container);


            this.Write("        OnContextCreated();\r\n    }\r\n\r\n    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_ContextCommonCtorComment"), container.Name)));


            this.Write("\r\n    /// </summary>\r\n    public ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(container)));


            this.Write("(EntityConnection connection) : base(connection, \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(container.Name));


            this.Write("\")\r\n    {\r\n");


        WriteLazyLoadingEnabled(container);


            this.Write("        OnContextCreated();\r\n    }\r\n\r\n    #endregion\r\n\r\n    #region ");

            this.Write(this.ToStringHelper.ToStringWithCulture(GetResourceString("Template_RegionPartialMethods")));


            this.Write("\r\n\r\n    partial void OnContextCreated();\r\n\r\n    #endregion\r\n\r\n");


        ////////
        //////// 
        ////////
        region.Begin(GetResourceString("Template_RegionObjectSetProperties"));
        foreach (EntitySet set in container.BaseEntitySets.OfType<EntitySet>())
        {
            VerifyEntityTypeAndSetAccessibilityCompatability(set);


            this.Write("\r\n    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(set)));


            this.Write("\r\n    /// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(set, region.CurrentIndentLevel)));


            this.Write("\r\n    ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(set))));



            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForReadOnlyProperty(set)));


            this.Write(" ObjectSet<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(set.ElementType, code)));


            this.Write("> ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(set)));


            this.Write("\r\n    {\r\n        get\r\n        {\r\n            if ((");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(set)));


            this.Write(" == null))\r\n            {\r\n                ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(set)));


            this.Write(" = base.CreateObjectSet<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(set.ElementType, code)));


            this.Write(">(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(set.Name));


            this.Write("\");\r\n            }\r\n            return ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(set)));


            this.Write(";\r\n        }\r\n    }\r\n    private ObjectSet<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(set.ElementType, code)));


            this.Write("> ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(set)));


            this.Write(";\r\n");


        }
        region.End();

        ////////
        //////// 
        ////////
        //////// 
        //////// 
        ////////
        //////// 
        //////// 
        //////// 
        ////////
        region.Begin(GetResourceString("Template_RegionAddToMethods"));
        IEnumerable<EntitySet> addToMethods = CreateContextAddToMethods.Value ? container.BaseEntitySets.OfType<EntitySet>() : Enumerable.Empty<EntitySet>();
        foreach (EntitySet set in addToMethods)
        {
            string parameterName = code.Escape(FixParameterName(set.ElementType.Name, code));


            this.Write("\r\n    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_GenCommentAddToMethodCs"), set.Name)));


            this.Write("\r\n    /// </summary>\r\n    ");

            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForType(set.ElementType)));


            this.Write(" void AddTo");

            this.Write(this.ToStringHelper.ToStringWithCulture(set.Name));


            this.Write("(");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(set.ElementType, code)));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameterName));


            this.Write(")\r\n    {\r\n        base.AddObject(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(set.Name));


            this.Write("\", ");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameterName));


            this.Write(");\r\n    }\r\n");


        }
        region.End();

        ////////
        //////// 
        ////////
        region.Begin(GetResourceString("Template_RegionFunctionImports"));
        foreach (EdmFunction edmFunction in container.FunctionImports)
        {

            IEnumerable<FunctionImportParameter> parameters = FunctionImportParameter.Create(edmFunction.Parameters, code, ef);
            string paramList = string.Join(", ", parameters.Select(p => p.FunctionParameterType + " " + p.FunctionParameterName).ToArray());
            TypeUsage returnType = edmFunction.ReturnParameters.Count == 0 ? null : ef.GetElementType(edmFunction.ReturnParameters[0].TypeUsage);


            this.Write("\r\n    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(edmFunction)));


            this.Write("\r\n    /// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel)));



            this.Write(this.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(p => new Tuple<string, string>(p.RawFunctionParameterName, SummaryComment(p.Source))), region.CurrentIndentLevel)));


            this.Write("\r\n    ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(edmFunction))));



            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForMethod(edmFunction)));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(returnType == null ? "int" : "ObjectResult<" + MultiSchemaEscape(returnType, code) + ">"));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(edmFunction)));


            this.Write("(");

            this.Write(this.ToStringHelper.ToStringWithCulture(paramList));


            this.Write(")\r\n    {\r\n");


            foreach (FunctionImportParameter parameter in parameters)
            {
                if (!parameter.NeedsLocalVariable)
                    continue;


            this.Write("        ObjectParameter ");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName));


            this.Write(";\r\n        if (");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null"));


            this.Write(")\r\n        {\r\n            ");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName));


            this.Write(" = new ObjectParameter(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameter.EsqlParameterName));


            this.Write("\", ");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameter.FunctionParameterName));


            this.Write(");\r\n        }\r\n        else\r\n        {\r\n            ");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName));


            this.Write(" = new ObjectParameter(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameter.EsqlParameterName));


            this.Write("\", typeof(");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameter.RawClrTypeName));


            this.Write("));\r\n        }\r\n\r\n");


        }


            this.Write("        return base.ExecuteFunction");

            this.Write(this.ToStringHelper.ToStringWithCulture(returnType == null ? "" : "<" + MultiSchemaEscape(returnType, code) + ">"));


            this.Write("(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(edmFunction.Name));


            this.Write("\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()))));


            this.Write(");\r\n    }\r\n");


           if(returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType)
           {


            this.Write("    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(edmFunction)));


            this.Write("\r\n    /// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel)));


            this.Write("\r\n    /// <param name=\"mergeOption\"></param>");

            this.Write(this.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(p => new Tuple<string, string>(p.RawFunctionParameterName, SummaryComment(p.Source))), region.CurrentIndentLevel)));


            this.Write("\r\n    ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(edmFunction))));



            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForMethod(edmFunction)));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(returnType == null ? "int" : "ObjectResult<" + MultiSchemaEscape(returnType, code) + ">"));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(edmFunction)));


            this.Write("(");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.StringAfter(paramList, ", ")));


            this.Write("MergeOption mergeOption)\r\n    {\r\n");


            foreach (FunctionImportParameter parameter in parameters)
            {
                if (!parameter.NeedsLocalVariable)
                    continue;


            this.Write("        ObjectParameter ");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName));


            this.Write(";\r\n        if (");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null"));


            this.Write(")\r\n        {\r\n            ");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName));


            this.Write(" = new ObjectParameter(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameter.EsqlParameterName));


            this.Write("\", ");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameter.FunctionParameterName));


            this.Write(");\r\n        }\r\n        else\r\n        {\r\n            ");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName));


            this.Write(" = new ObjectParameter(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameter.EsqlParameterName));


            this.Write("\", typeof(");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameter.RawClrTypeName));


            this.Write("));\r\n        }\r\n\r\n");


            }


            this.Write("        return base.");

            this.Write(this.ToStringHelper.ToStringWithCulture(returnType == null ? "ExecuteFunction" : "ExecuteFunction<" + MultiSchemaEscape(returnType, code) + ">"));


            this.Write("(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(edmFunction.Name));


            this.Write("\", mergeOption");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()))));


            this.Write(");\r\n    }\r\n");


        }
        }
        region.End();


            this.Write("}\r\n");


    }
    region.End();

    ////////
    //////// 
    ////////
    region.Begin(GetResourceString("Template_RegionEntities"));
    foreach (EntityType entity in GetSourceSchemaTypes<EntityType>().OrderBy(e => e.Name))
    {


            this.Write("\r\n/// <summary>\r\n/// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(entity)));


            this.Write("\r\n/// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(entity, region.CurrentIndentLevel)));


            this.Write("\r\n[EdmEntityTypeAttribute(NamespaceName=\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(entity.NamespaceName));


            this.Write("\", Name=\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(entity.Name));


            this.Write("\")]\r\n[Serializable()]\r\n[DataContractAttribute(IsReference=true)]\r\n");


        foreach (EntityType subType in ItemCollection.GetItems<EntityType>().Where(b => b.BaseType == entity))
        {


            this.Write("[KnownTypeAttribute(typeof(");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(subType, code)));


            this.Write("))]\r\n");


        }



            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForType(entity)));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(code.AbstractOption(entity))));


            this.Write("partial class ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(entity)));


            this.Write(" : ");

            this.Write(this.ToStringHelper.ToStringWithCulture(BaseTypeName(entity, code)));


            this.Write("\r\n{\r\n");


        if (!entity.Abstract)
        {
            WriteFactoryMethod(entity, code);
        }

        region.Begin(GetResourceString("Template_RegionPrimitiveProperties"));
        foreach (EdmProperty property in entity.Properties.Where(p => p.DeclaringType == entity && p.TypeUsage.EdmType is PrimitiveType))
        {
            VerifyGetterAndSetterAccessibilityCompatability(property);
            WritePrimitiveTypeProperty(property, code);
        }
        region.End();

        region.Begin(GetResourceString("Template_RegionComplexProperties"));
        foreach (EdmProperty property in entity.Properties.Where(p => p.DeclaringType == entity && p.TypeUsage.EdmType is ComplexType))
        {
            VerifyGetterAndSetterAccessibilityCompatability(property);
            WriteComplexTypeProperty(property, code);
        }
        region.End();


            this.Write("\r\n");


        ////////
        //////// 
        ////////
        region.Begin(GetResourceString("Template_RegionNavigationProperties"));
        foreach (NavigationProperty navProperty in entity.NavigationProperties.Where(n => n.DeclaringType == entity))
        {
            VerifyGetterAndSetterAccessibilityCompatability(navProperty);


            this.Write("\r\n    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(navProperty)));


            this.Write("\r\n    /// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(navProperty, region.CurrentIndentLevel)));


            this.Write("\r\n    [XmlIgnoreAttribute()]\r\n    [SoapIgnoreAttribute()]\r\n    [DataMemberAttribu" +
                    "te()]\r\n    [EdmRelationshipNavigationPropertyAttribute(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.NamespaceName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.Name));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name));


            this.Write("\")]\r\n");


            if (navProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
            {


            this.Write("    ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(navProperty))));



            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(navProperty)));


            this.Write(" EntityCollection<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write("> ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(navProperty)));


            this.Write("\r\n    {\r\n        ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(navProperty))));


            this.Write("get\r\n        {\r\n            return ((IEntityWithRelationships)this).RelationshipM" +
                    "anager.GetRelatedCollection<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write(">(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name));


            this.Write("\");\r\n        }\r\n        ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter(navProperty))));


            this.Write("set\r\n        {\r\n            if ((value != null))\r\n            {\r\n                " +
                    "((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection" +
                    "<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write(">(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name));


            this.Write("\", value);\r\n            }\r\n        }\r\n    }\r\n");


           }
           else
           {


            this.Write("    ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(navProperty))));



            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(navProperty)));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(navProperty)));


            this.Write("\r\n    {\r\n        ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(navProperty))));


            this.Write("get\r\n        {\r\n            return ((IEntityWithRelationships)this).RelationshipM" +
                    "anager.GetRelatedReference<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write(">(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name));


            this.Write("\").Value;\r\n        }\r\n        ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter(navProperty))));


            this.Write("set\r\n        {\r\n            ((IEntityWithRelationships)this).RelationshipManager." +
                    "GetRelatedReference<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write(">(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name));


            this.Write("\").Value = value;\r\n        }\r\n    }\r\n");


        string refPropertyName = navProperty.Name + "Reference";
        if (entity.Members.Any(m => m.Name == refPropertyName))
        {
           // 
            Errors.Add(new System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6017", String.Format(CultureInfo.CurrentCulture,
                    GetResourceString("Template_ConflictingGeneratedNavPropName"),
                        navProperty.Name, entity.FullName, refPropertyName)));
        }


            this.Write("    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(navProperty)));


            this.Write("\r\n    /// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(navProperty, region.CurrentIndentLevel)));


            this.Write("\r\n    [BrowsableAttribute(false)]\r\n    [DataMemberAttribute()]\r\n    ");

            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(navProperty)));


            this.Write(" EntityReference<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write("> ");

            this.Write(this.ToStringHelper.ToStringWithCulture(refPropertyName));


            this.Write("\r\n    {\r\n        ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(navProperty))));


            this.Write("get\r\n        {\r\n            return ((IEntityWithRelationships)this).RelationshipM" +
                    "anager.GetRelatedReference<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write(">(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name));


            this.Write("\");\r\n        }\r\n        ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter(navProperty))));


            this.Write("set\r\n        {\r\n            if ((value != null))\r\n            {\r\n                " +
                    "((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<" +
                    "");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write(">(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name));


            this.Write("\", value);\r\n            }\r\n        }\r\n    }\r\n");


            }
        }
        region.End();


            this.Write("}\r\n");


    }
    region.End();

    ////////
    //////// 
    ////////
    region.Begin(GetResourceString("Template_RegionComplexTypes"));
    foreach (ComplexType complex in GetSourceSchemaTypes<ComplexType>().OrderBy(c => c.Name))
    {


            this.Write("\r\n/// <summary>\r\n/// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(complex)));


            this.Write("\r\n/// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(complex, region.CurrentIndentLevel)));


            this.Write("\r\n[EdmComplexTypeAttribute(NamespaceName=\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(complex.NamespaceName));


            this.Write("\", Name=\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(complex.Name));


            this.Write("\")]\r\n[DataContractAttribute(IsReference=true)]\r\n[Serializable()]\r\n");

            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForType(complex)));


            this.Write(" partial class ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(complex)));


            this.Write(" : ComplexObject\r\n{\r\n");


        WriteFactoryMethod(complex, code);
        region.Begin(GetResourceString("Template_RegionPrimitiveProperties"));
        foreach (EdmProperty property in complex.Properties.Where(p => p.DeclaringType == complex && p.TypeUsage.EdmType is PrimitiveType))
        {
            VerifyGetterAndSetterAccessibilityCompatability(property);
            WritePrimitiveTypeProperty(property, code);
        }
        region.End();
        region.Begin(GetResourceString("Template_RegionComplexProperties"));
        foreach (EdmProperty property in complex.Properties.Where(p => p.DeclaringType == complex && p.TypeUsage.EdmType is ComplexType))
        {
            VerifyGetterAndSetterAccessibilityCompatability(property);
            WriteComplexTypeProperty(property, code);
        }
        region.End();


            this.Write("}\r\n");


    }
    region.End();


            this.Write("\r\n");


    if (!String.IsNullOrEmpty(namespaceName))
    {
        PopIndent();


            this.Write("}\r\n");


    }
    VerifyTypeUniqueness();


            return this.GenerationEnvironment.ToString();
        }



    ////////
    //////// 
    ////////

    ////////
    //////// 
    ////////
    private void WriteFactoryMethod(StructuralType structuralType, CodeGenerationTools code)
    {
        CodeRegion region = new CodeRegion(this, 1);

        string methodName = "Create" + structuralType.Name;
        UniqueIdentifierService uniqueIdentifier = new UniqueIdentifierService();
        string instanceName = code.Escape(uniqueIdentifier.AdjustIdentifier((code.CamelCase(structuralType.Name))));
        IEnumerable<FactoryMethodParameter> parameters = FactoryMethodParameter.CreateParameters(structuralType.Members.OfType<EdmProperty>().Where(p => IncludePropertyInFactoryMethod(structuralType, p)), uniqueIdentifier, MultiSchemaEscape, code);

        if (parameters.Count() == 0)
            return;

        if (structuralType.Members.Any(m => m.Name == methodName))
        {
            // 
            Errors.Add(new System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6029",
                String.Format(CultureInfo.CurrentCulture,
                        GetResourceString("Template_FactoryMethodNameConflict"), methodName, structuralType.FullName)));
        }

        region.Begin(GetResourceString("Template_RegionFactoryMethod"));



this.Write("\r\n    /// <summary>\r\n    /// ");



this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_FactoryMethodComment"), structuralType.Name)));



this.Write("\r\n    /// </summary>");



this.Write(this.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(p => new Tuple<string, string>(p.RawParameterName, p.ParameterComment)), region.CurrentIndentLevel)));



this.Write("\r\n    public static ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(structuralType)));



this.Write(" ");



this.Write(this.ToStringHelper.ToStringWithCulture(methodName));



this.Write("(");



this.Write(this.ToStringHelper.ToStringWithCulture(string.Join(", ", parameters.Select(p => p.ParameterType + " " + p.ParameterName).ToArray())));



this.Write(")\r\n    {\r\n        ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(structuralType)));



this.Write(" ");



this.Write(this.ToStringHelper.ToStringWithCulture(instanceName));



this.Write(" = new ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(structuralType)));



this.Write("();\r\n");




        foreach (FactoryMethodParameter parameter in parameters)
        {
            if (parameter.IsComplexType)
            {
                // 



this.Write("        ");



this.Write(this.ToStringHelper.ToStringWithCulture(instanceName));



this.Write(".");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(parameter.Source)));



this.Write(" = StructuralObject.VerifyComplexObjectIsNotNull(");



this.Write(this.ToStringHelper.ToStringWithCulture(parameter.ParameterName));



this.Write(", \"");



this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Source.Name));



this.Write("\");\r\n");




            }
            else
            {
                // 



this.Write("        ");



this.Write(this.ToStringHelper.ToStringWithCulture(instanceName));



this.Write(".");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(parameter.Source)));



this.Write(" = ");



this.Write(this.ToStringHelper.ToStringWithCulture(parameter.ParameterName));



this.Write(";\r\n");




            }
        }



this.Write("        return ");



this.Write(this.ToStringHelper.ToStringWithCulture(instanceName));



this.Write(";\r\n    }\r\n");




        region.End();
    }


    ////////
    //////// 
    ////////
    private void WritePrimitiveTypeProperty(EdmProperty primitiveProperty, CodeGenerationTools code)
    {
        MetadataTools ef = new MetadataTools(this);



this.Write("\r\n    /// <summary>\r\n    /// ");



this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(primitiveProperty)));



this.Write("\r\n    /// </summary>");



this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(primitiveProperty, 1)));



this.Write("\r\n    [EdmScalarPropertyAttribute(EntityKeyProperty=");



this.Write(this.ToStringHelper.ToStringWithCulture(code.CreateLiteral(ef.IsKey(primitiveProperty))));



this.Write(", IsNullable=");



this.Write(this.ToStringHelper.ToStringWithCulture(code.CreateLiteral(ef.IsNullable(primitiveProperty))));



this.Write(")]\r\n    [DataMemberAttribute()]\r\n    ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(primitiveProperty))));



this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(primitiveProperty)));



this.Write(" ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(primitiveProperty.TypeUsage)));



this.Write(" ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(primitiveProperty)));



this.Write("\r\n    {\r\n        ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(primitiveProperty))));



this.Write("get\r\n        {\r\n");



             if (ef.ClrType(primitiveProperty.TypeUsage) == typeof(byte[]))
                {



this.Write("            return StructuralObject.GetValidValue(");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(primitiveProperty)));



this.Write(");\r\n");




                }
                else
                {



this.Write("            return ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(primitiveProperty)));



this.Write(";\r\n");




                }



this.Write("        }\r\n        ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter((primitiveProperty)))));



this.Write("set\r\n        {\r\n");




        if (ef.IsKey(primitiveProperty))
            {
                if (ef.ClrType(primitiveProperty.TypeUsage) == typeof(byte[]))
                {



this.Write("            if (!StructuralObject.BinaryEquals(");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(primitiveProperty)));



this.Write(", value))\r\n");




                }
                else
                {



this.Write("            if (");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(primitiveProperty)));



this.Write(" != value)\r\n");




                }



this.Write("            {\r\n");




        PushIndent(CodeRegion.GetIndent(1));
            }



this.Write("            ");



this.Write(this.ToStringHelper.ToStringWithCulture(ChangingMethodName(primitiveProperty)));



this.Write("(value);\r\n            ReportPropertyChanging(\"");



this.Write(this.ToStringHelper.ToStringWithCulture(primitiveProperty.Name));



this.Write("\");\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(primitiveProperty)));



this.Write(" = StructuralObject.SetValidValue(value");



this.Write(this.ToStringHelper.ToStringWithCulture(OptionalNullableParameterForSetValidValue(primitiveProperty, code)));



this.Write(");\r\n            ReportPropertyChanged(\"");



this.Write(this.ToStringHelper.ToStringWithCulture(primitiveProperty.Name));



this.Write("\");\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(ChangedMethodName(primitiveProperty)));



this.Write("();\r\n");




        if (ef.IsKey(primitiveProperty))
            {
        PopIndent();



this.Write("            }\r\n");




            }



this.Write("        }\r\n    }\r\n    private ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(primitiveProperty.TypeUsage)));



this.Write(" ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(primitiveProperty)));



this.Write(this.ToStringHelper.ToStringWithCulture(code.StringBefore(" = ", code.CreateLiteral(primitiveProperty.DefaultValue))));



this.Write(";\r\n    partial void ");



this.Write(this.ToStringHelper.ToStringWithCulture(ChangingMethodName(primitiveProperty)));



this.Write("(");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(primitiveProperty.TypeUsage)));



this.Write(" value);\r\n    partial void ");



this.Write(this.ToStringHelper.ToStringWithCulture(ChangedMethodName(primitiveProperty)));



this.Write("();\r\n");




    }

    ////////
    //////// 
    ////////
    private void WriteComplexTypeProperty(EdmProperty complexProperty, CodeGenerationTools code)
    {



this.Write("\r\n    /// <summary>\r\n    /// ");



this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(complexProperty)));



this.Write("\r\n    /// </summary>");



this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(complexProperty, 1)));



this.Write("\r\n    [EdmComplexPropertyAttribute()]\r\n    [DesignerSerializationVisibility(Desig" +
        "nerSerializationVisibility.Content)]\r\n    [XmlElement(IsNullable=true)]\r\n    [So" +
        "apElement(IsNullable=true)]\r\n    [DataMemberAttribute()]\r\n    ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(complexProperty))));



this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(complexProperty)));



this.Write(" ");



this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(complexProperty.TypeUsage, code)));



this.Write(" ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(complexProperty)));



this.Write("\r\n    {\r\n        ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(complexProperty))));



this.Write("get\r\n        {\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)));



this.Write(" = GetValidValue(");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)));



this.Write(", \"");



this.Write(this.ToStringHelper.ToStringWithCulture(complexProperty.Name));



this.Write("\", false, ");



this.Write(this.ToStringHelper.ToStringWithCulture(InitializedTrackingField(complexProperty, code)));



this.Write(");\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(InitializedTrackingField(complexProperty, code)));



this.Write(" = true;\r\n            return ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)));



this.Write(";\r\n        }\r\n        ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter(complexProperty))));



this.Write("set\r\n        {\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(ChangingMethodName(complexProperty)));



this.Write("(value);\r\n            ReportPropertyChanging(\"");



this.Write(this.ToStringHelper.ToStringWithCulture(complexProperty.Name));



this.Write("\");\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)));



this.Write(" = SetValidValue(");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)));



this.Write(", value, \"");



this.Write(this.ToStringHelper.ToStringWithCulture(complexProperty.Name));



this.Write("\");\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(InitializedTrackingField(complexProperty, code)));



this.Write(" = true;\r\n            ReportPropertyChanged(\"");



this.Write(this.ToStringHelper.ToStringWithCulture(complexProperty.Name));



this.Write("\");\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(ChangedMethodName(complexProperty)));



this.Write("();\r\n        }\r\n    }\r\n    private ");



this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(complexProperty.TypeUsage, code)));



this.Write(" ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)));



this.Write(";\r\n    private bool ");



this.Write(this.ToStringHelper.ToStringWithCulture(InitializedTrackingField(complexProperty, code)));



this.Write(";\r\n    partial void ");



this.Write(this.ToStringHelper.ToStringWithCulture(ChangingMethodName(complexProperty)));



this.Write("(");



this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(complexProperty.TypeUsage, code)));



this.Write(" value);\r\n    partial void ");



this.Write(this.ToStringHelper.ToStringWithCulture(ChangedMethodName(complexProperty)));



this.Write("();\r\n");




    }

    private void WriteLazyLoadingEnabled(EntityContainer container)
    {
        string lazyLoadingAttributeValue = null;
        string lazyLoadingAttributeName = MetadataConstants.EDM_ANNOTATION_09_02 + ":LazyLoadingEnabled";
        if(MetadataTools.TryGetStringMetadataPropertySetting(container, lazyLoadingAttributeName, out lazyLoadingAttributeValue))
        {
            bool isLazyLoading = false;
            if(bool.TryParse(lazyLoadingAttributeValue, out isLazyLoading))
            {



this.Write("        this.ContextOptions.LazyLoadingEnabled = ");



this.Write(this.ToStringHelper.ToStringWithCulture(isLazyLoading.ToString().ToLowerInvariant()));



this.Write(";\r\n");




            }
        }
    }

////////
//////// 
////////
public string SourceCsdlPath{ get; set; }
public string ModelNamespace{ get; set; }
public EdmItemCollection ItemCollection{ get; set; }
public IEnumerable<string> ReferenceCsdlPaths{ get; set; }
public Nullable<bool> CreateContextAddToMethods{ get; set; }
public Dictionary<string, string> EdmToObjectNamespaceMap
{
    get { return _edmToObjectNamespaceMap; }
    set { _edmToObjectNamespaceMap = value; }
}
public Dictionary<string, string> _edmToObjectNamespaceMap = new Dictionary<string, string>();
public Double SourceEdmVersion
{
    get
    {
        if (ItemCollection != null)
        {
            return ItemCollection.EdmVersion;
        }

        return 0.0;
    }
}

////////
//////// 
////////
static System.Resources.ResourceManager ResourceManager
{
    get
    {
        if (_resourceManager == null)
        {
            System.Resources.ResourceManager resourceManager = new System.Resources.ResourceManager("System.Data.Entity.Design", typeof(System.Data.Entity.Design.MetadataItemCollectionFactory).Assembly);
            System.Threading.Interlocked.CompareExchange(ref _resourceManager, resourceManager, null);
        }
        return _resourceManager;
    }
}
static System.Resources.ResourceManager _resourceManager;






private static string GetResourceString(string resourceName)
{
    return ResourceManager.GetString(resourceName,
         null); // 
}



private void VerifyTypeUniqueness()
{
    HashSet<string> hash = new HashSet<string>();
    IEnumerable<GlobalItem> allTypes = GetSourceSchemaTypes<GlobalItem>().Where(i => i is StructuralType || i is EntityContainer);

    foreach (GlobalItem type in allTypes)
    {
        if (!hash.Add(GetGlobalItemName(type)))
        {
            // 
            Errors.Add(new System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6034",
             String.Format(CultureInfo.CurrentCulture,
                GetResourceString("Template_DuplicateTopLevelType"),
             GetGlobalItemName(type))));
        }
    }
}

protected string GetGlobalItemName(GlobalItem item)
{
    if (item is EdmType)
    {
        // 
        return ((EdmType)item).Name;
    }
    else
    {
        // 
        return ((EntityContainer)item).Name;
    }
}



void ApplyUserSettings(UserSettings userSettings)
{
    // 
    if (SourceCsdlPath == null)
    {
#if !PREPROCESSED_TEMPLATE
        if(userSettings.SourceCsdlPath == "$" + "edmxInputFile" + "$")
        {
            Errors.Add(new System.CodeDom.Compiler.CompilerError(Host.TemplateFile, -1, -1, "",
                GetResourceString("Template_ReplaceVsItemTemplateToken")));
            return;
        }

        SourceCsdlPath = Host.ResolvePath(userSettings.SourceCsdlPath);
#else
        SourceCsdlPath = userSettings.SourceCsdlPath;
#endif
    }

    // normalize the path, remove ..\ from it
    SourceCsdlPath = Path.GetFullPath(SourceCsdlPath);


    if (ReferenceCsdlPaths == null)
    {
        ReferenceCsdlPaths = userSettings.ReferenceCsdlPaths;
    }

    if (!CreateContextAddToMethods.HasValue)
    {
        CreateContextAddToMethods = userSettings.CreateContextAddToMethods;
    }

    DefaultSummaryComment = GetResourceString("Template_CommentNoDocumentation");
}

class UserSettings
{
    public string SourceCsdlPath{ get; set; }
    public string[] ReferenceCsdlPaths{ get; set; }
    public bool FullyQualifySystemTypes{ get; set; }
    public bool CreateContextAddToMethods{ get; set; }
    public bool CamelCaseFields{ get; set; }
}

string GetNamespaceName(CodeGenerationTools code)
{
    string namespaceName = code.VsNamespaceSuggestion();

#if PREPROCESSED_TEMPLATE
    if (String.IsNullOrEmpty(namespaceName))
    {
        namespaceName = GetObjectNamespace(ModelNamespace);
    }
#endif
    return namespaceName;
}

string MultiSchemaEscape(TypeUsage usage, CodeGenerationTools code)
{
    StructuralType structural = usage.EdmType as StructuralType;
    if (structural != null)
    {
        return MultiSchemaEscape(structural, code);
    }
    return code.Escape(usage);
}

string MultiSchemaEscape(StructuralType type, CodeGenerationTools code)
{
    if (type.NamespaceName != ModelNamespace)
    {
        return code.CreateFullName(code.EscapeNamespace(GetObjectNamespace(type.NamespaceName)), code.Escape(type));
    }

    return code.Escape(type);
}

string NewModifier(NavigationProperty navigationProperty)
{
    Type baseType = typeof(EntityObject);
    return NewModifier(baseType, navigationProperty.Name);
}

string NewModifier(EdmFunction edmFunction)
{
    Type baseType = typeof(ObjectContext);
    return NewModifier(baseType, edmFunction.Name);
}

string NewModifier(EntitySet set)
{
    Type baseType = typeof(ObjectContext);
    return NewModifier(baseType, set.Name);
}

string NewModifier(EdmProperty property)
{
    Type baseType;
    if (property.DeclaringType.BuiltInTypeKind == BuiltInTypeKind.EntityType)
    {
        baseType = typeof(EntityObject);
    }
    else
    {
        baseType = typeof(ComplexObject);
    }
    return NewModifier(baseType, property.Name);
}

string NewModifier(Type type, string memberName)
{
    if (HasBaseMemberWithMatchingName(type, memberName))
    {
        return "new";
    }
    return string.Empty;
}

static bool HasBaseMemberWithMatchingName(Type type, string memberName)
{
    BindingFlags bindingFlags = BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public
                | BindingFlags.Instance | BindingFlags.Static;
    return type.GetMembers(bindingFlags).Where(m => IsVisibleMember(m)).Any(m => m.Name == memberName);
}

string ChangingMethodName(EdmMember member)
{
    return string.Format(CultureInfo.InvariantCulture, "On{0}Changing", member.Name);
}

string ChangedMethodName(EdmMember member)
{
    return string.Format(CultureInfo.InvariantCulture, "On{0}Changed", member.Name);
}

string InitializedTrackingField(EdmProperty property, CodeGenerationTools code)
{
    string namePart = property.Name + "Initialized";
    if (code.CamelCaseFields)
    {
        namePart = code.CamelCase(namePart);
    }
    return "_" + namePart;
}

string OptionalNullableParameterForSetValidValue(EdmMember member, CodeGenerationTools code)
{
    MetadataTools ef = new MetadataTools(this);
    string list = string.Empty;
    if (((PrimitiveType)member.TypeUsage.EdmType).ClrEquivalentType.IsClass)
    {
        MetadataProperty storeGeneratedPatternProperty = null;
        bool isNullable = ef.IsNullable(member.TypeUsage) ||
            (member.MetadataProperties.TryGetValue(MetadataConstants.EDM_ANNOTATION_09_02 + ":StoreGeneratedPattern", false, out storeGeneratedPatternProperty) &&
             Object.Equals(storeGeneratedPatternProperty.Value, "Computed"));
        list += ", " + code.CreateLiteral(isNullable);
    }
    return list;
}

static bool IsVisibleMember(MemberInfo memberInfo)
{
    if (memberInfo is EventInfo)
    {
        EventInfo ei = (EventInfo)memberInfo;
        MethodInfo add = ei.GetAddMethod();
        MethodInfo remove = ei.GetRemoveMethod();
        return IsVisibleMethod(add) || IsVisibleMethod(remove);
    }
    else if (memberInfo is FieldInfo)
    {
        FieldInfo fi = (FieldInfo)memberInfo;
        return !fi.IsPrivate && !fi.IsAssembly;
    }
    else if (memberInfo is MethodBase)
    {
        MethodBase mb = (MethodBase)memberInfo;
        if (mb.IsSpecialName)
            return false;
        return IsVisibleMethod(mb);
    }
    else if (memberInfo is PropertyInfo)
    {
        PropertyInfo pi = (PropertyInfo)memberInfo;
        MethodInfo get = pi.GetGetMethod();
        MethodInfo set = pi.GetSetMethod();
        return IsVisibleMethod(get) || IsVisibleMethod(set);
    }

    return false;
}

static bool IsVisibleMethod(MethodBase methodBase)
{
    if (methodBase == null)
        return false;

    return !methodBase.IsPrivate && !methodBase.IsAssembly;
}

IEnumerable<T> GetSourceSchemaTypes<T>() where T : GlobalItem
{
    if (Path.GetExtension(SourceCsdlPath) != ".edmx")
    {
        return ItemCollection.GetItems<T>().Where(e => e.MetadataProperties.Any(mp => mp.Name == "SchemaSource" && (string)mp.Value == SourceCsdlPath));
    }
    else
    {
        return ItemCollection.GetItems<T>();
    }
}

string EndName(AssociationType association, int index)
{
    return association.AssociationEndMembers[index].Name;
}

string EndMultiplicity(AssociationType association, int index, CodeGenerationTools code)
{
    return code.CreateLiteral(association.AssociationEndMembers[index].RelationshipMultiplicity);
}

string EscapeEndTypeName(AssociationType association, int index, CodeGenerationTools code)
{
    EntityType entity = association.AssociationEndMembers[index].GetEntityType();
    return code.CreateFullName(code.EscapeNamespace(GetObjectNamespace(entity.NamespaceName)), code.Escape(entity));
}

string GetObjectNamespace(string csdlNamespaceName)
{
    string objectNamespace;
    if (EdmToObjectNamespaceMap.TryGetValue(csdlNamespaceName, out objectNamespace))
    {
        return objectNamespace;
    }

    return csdlNamespaceName;
}

void UpdateObjectNamespaceMap(string objectNamespace)
{
    if(objectNamespace != ModelNamespace && !EdmToObjectNamespaceMap.ContainsKey(ModelNamespace))
    {
        EdmToObjectNamespaceMap.Add(ModelNamespace, objectNamespace);
    }
}

static string FixParameterName(string name, CodeGenerationTools code)
{
    // 
    // 
    if (StringComparer.OrdinalIgnoreCase.Equals(name, "id"))
    {
        // 
        return "id";
    }
    return code.CamelCase(name);
}

string BaseTypeName(EntityType entity, CodeGenerationTools code)
{
    return entity.BaseType == null ? "EntityObject" : MultiSchemaEscape((StructuralType)entity.BaseType, code);
}

bool IncludePropertyInFactoryMethod(StructuralType factoryType, EdmProperty edmProperty)
{
    if (edmProperty.Nullable)
    {
        return false;
    }

    if (edmProperty.DefaultValue != null)
    {
        return false;
    }

    if ((Accessibility.ForReadOnlyProperty(edmProperty) != "public" && Accessibility.ForWriteOnlyProperty(edmProperty) != "public") ||
        (factoryType != edmProperty.DeclaringType && Accessibility.ForWriteOnlyProperty(edmProperty) == "private")
       )
    {
        // 
        return false;
    }

    return true;
}


class FactoryMethodParameter
{
    public EdmProperty Source;
    public string RawParameterName;
    public string ParameterName;
    public string ParameterType;
    public string ParameterComment;
    public bool IsComplexType;

    public static IEnumerable<FactoryMethodParameter> CreateParameters(IEnumerable<EdmProperty> properties, UniqueIdentifierService unique, Func<TypeUsage, CodeGenerationTools, string> multiSchemaEscape, CodeGenerationTools code)
    {
        List<FactoryMethodParameter> parameters = new List<FactoryMethodParameter>();
        foreach (EdmProperty property in properties)
        {
            FactoryMethodParameter parameter = new FactoryMethodParameter();
            parameter.Source = property;
            parameter.IsComplexType = property.TypeUsage.EdmType is ComplexType;
            parameter.RawParameterName = unique.AdjustIdentifier(FixParameterName(property.Name, code));
            parameter.ParameterName = code.Escape(parameter.RawParameterName);
            parameter.ParameterType = multiSchemaEscape(property.TypeUsage, code);
            parameter.ParameterComment = String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_CommentFactoryMethodParam"), property.Name);
            parameters.Add(parameter);
        }

        return parameters;
    }
}

string DefaultSummaryComment{ get; set; }

string SummaryComment(MetadataItem item)
{
    if (item.Documentation != null && item.Documentation.Summary != null)
    {
        return PrefixLinesOfMultilineComment(XMLCOMMENT_START + " ", XmlEntityize(item.Documentation.Summary));
    }

    if (DefaultSummaryComment != null)
    {
        return DefaultSummaryComment;
    }

    return string.Empty;
}

string LongDescriptionCommentElement(MetadataItem item, int indentLevel)
{
    if (item.Documentation != null && !String.IsNullOrEmpty(item.Documentation.LongDescription))
    {
        string comment = Environment.NewLine;
        string lineStart = CodeRegion.GetIndent(indentLevel) + XMLCOMMENT_START + " ";
        comment += lineStart + "<LongDescription>" + Environment.NewLine;
        comment += lineStart + PrefixLinesOfMultilineComment(lineStart, XmlEntityize(item.Documentation.LongDescription)) + Environment.NewLine;
        comment += lineStart + "</LongDescription>";
        return comment;
    }
    return string.Empty;
}

string PrefixLinesOfMultilineComment(string prefix, string comment)
{
    return comment.Replace(Environment.NewLine, Environment.NewLine + prefix);
}

string ParameterComments(IEnumerable<Tuple<string, string>> parameters, int indentLevel)
{
    System.Text.StringBuilder builder = new System.Text.StringBuilder();
    foreach (Tuple<string, string> parameter in parameters)
    {
        builder.AppendLine();
        builder.Append(CodeRegion.GetIndent(indentLevel));
        builder.Append(XMLCOMMENT_START);
        builder.Append(String.Format(CultureInfo.InvariantCulture, " <param name=\"{0}\">{1}</param>", parameter.Item1, parameter.Item2));
    }
    return builder.ToString();
}

string XmlEntityize(string text)
{
    if (string.IsNullOrEmpty(text))
    {
        return string.Empty;
    }

    text = text.Replace("&","&amp;");
    text = text.Replace("<","&lt;").Replace(">","&gt;");
    string id = Guid.NewGuid().ToString();
    text = text.Replace(Environment.NewLine, id);
    text = text.Replace("\r", "&#xD;").Replace("\n","&#xA;");
    text = text.Replace(id, Environment.NewLine);
    return text.Replace("\'","&apos;").Replace("\"","&quot;");
}

const string XMLCOMMENT_START = "///";
IEnumerable<EdmProperty> GetProperties(StructuralType type)
{
    if (type.BuiltInTypeKind == BuiltInTypeKind.EntityType)
    {
        return ((EntityType)type).Properties;
    }
    else
    {
        return ((ComplexType)type).Properties;
    }
}

protected void VerifyGetterAndSetterAccessibilityCompatability(EdmMember member)
{
    string rawGetterAccessibility = Accessibility.ForReadOnlyProperty(member);
    string rawSetterAccessibility = Accessibility.ForWriteOnlyProperty(member);

    if ((rawGetterAccessibility == "internal" && rawSetterAccessibility ==   "protected") ||
        (rawGetterAccessibility == "protected" && rawSetterAccessibility == "internal"))

    {
           Errors.Add(new System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6033", String.Format(CultureInfo.CurrentCulture,
                   GetResourceString("GeneratedPropertyAccessibilityConflict"),
                       member.Name, rawGetterAccessibility, rawSetterAccessibility)));
    }
}

private void VerifyEntityTypeAndSetAccessibilityCompatability(EntitySet set)
{
    string typeAccess = Accessibility.ForType(set.ElementType);
    string setAccess = Accessibility.ForReadOnlyProperty(set);

    if(typeAccess == "internal" && (setAccess == "public" || setAccess == "protected"))
    {
       Errors.Add(new System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6036", String.Format(CultureInfo.CurrentCulture,
               GetResourceString("EntityTypeAndSetAccessibilityConflict"),
                   set.ElementType.Name, typeAccess, set.Name, setAccess)));
    }
}

private void DefineMetadata()
{
    TemplateMetadata[MetadataConstants.TT_TEMPLATE_NAME] = "CSharpCodeGen";
    TemplateMetadata[MetadataConstants.TT_TEMPLATE_VERSION] = "4.0";
    TemplateMetadata[MetadataConstants.TT_MINIMUM_ENTITY_FRAMEWORK_VERSION] = "4.0";
}

////////
//////// 
////////
sealed class UniqueIdentifierService
{
    private readonly HashSet<string> _knownIdentifiers;

    public UniqueIdentifierService()
    {
        _knownIdentifiers = new HashSet<string>(StringComparer.Ordinal);
    }

    /// <summary>
    /// 
    /// 
    /// </summary>
    public string AdjustIdentifier(string identifier)
    {
        // 
        var numberOfConflicts = 0;
        var adjustedIdentifier = identifier;

        while (!_knownIdentifiers.Add(adjustedIdentifier))
        {
            ++numberOfConflicts;
            adjustedIdentifier = identifier + numberOfConflicts.ToString(CultureInfo.InvariantCulture);
        }

        return adjustedIdentifier;
    }
}




// Copyright (c) Microsoft Corporation.  All rights reserved.

public static Dictionary<string, string> TemplateMetadata = new Dictionary<string, string>();

/// <summary>
/// Responsible for helping to create source code that is
/// correctly formated and functional
/// </summary>
public class CodeGenerationTools
{
    private readonly DynamicTextTransformation _textTransformation;
    private readonly CSharpCodeProvider _code;
    private readonly MetadataTools _ef;

    /// <summary>
    /// Initializes a new CodeGenerationTools object with the TextTransformation (T4 generated class)
    /// that is currently running
    /// </summary>
    public CodeGenerationTools(object textTransformation)
    {
        if (textTransformation == null)
        {
            throw new ArgumentNullException("textTransformation");
        }

        _textTransformation = DynamicTextTransformation.Create(textTransformation);
        _code = new CSharpCodeProvider();
        _ef = new MetadataTools(_textTransformation);
        FullyQualifySystemTypes = false;
        CamelCaseFields = true;
    }

    /// <summary>
    /// When true, all types that are not being generated
    /// are fully qualified to keep them from conflicting with
    /// types that are being generated. Useful when you have
    /// something like a type being generated named System.
    ///
    /// Default is false.
    /// </summary>
    public bool FullyQualifySystemTypes { get; set; }

    /// <summary>
    /// When true, the field names are Camel Cased,
    /// otherwise they will preserve the case they
    /// start with.
    ///
    /// Default is true.
    /// </summary>
    public bool CamelCaseFields { get; set; }

    /// <summary>
    /// Returns the NamespaceName suggested by VS if running inside VS.  Otherwise, returns
    /// null.
    /// </summary>
    public string VsNamespaceSuggestion()
    {
        string suggestion = _textTransformation.Host.ResolveParameterValue("directiveId", "namespaceDirectiveProcessor", "namespaceHint");
        if (String.IsNullOrEmpty(suggestion))
        {
            return null;
        }

        return suggestion;
    }

    /// <summary>
    /// Returns a string that is safe for use as an identifier in C#.
    /// Keywords are escaped.
    /// </summary>
    public string Escape(string name)
    {
        if (name == null)
        {
            return null;
        }

        return _code.CreateEscapedIdentifier(name);
    }

    /// <summary>
    /// Returns the name of the TypeUsage's EdmType that is safe for
    /// use as an identifier.
    /// </summary>
    public string Escape(TypeUsage typeUsage)
    {
        if (typeUsage == null)
        {
            return null;
        }

        if (typeUsage.EdmType is ComplexType ||
            typeUsage.EdmType is EntityType)
        {
            return Escape(typeUsage.EdmType.Name);
        }
        else if (typeUsage.EdmType is SimpleType)
        {
            Type clrType = _ef.UnderlyingClrType(typeUsage.EdmType);
            string typeName = typeUsage.EdmType is EnumType ? Escape(typeUsage.EdmType.Name) : Escape(clrType);
            if (clrType.IsValueType && _ef.IsNullable(typeUsage))
            {
                return String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName);
            }

            return typeName;
        }
        else if (typeUsage.EdmType is CollectionType)
        {
            return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", Escape(((CollectionType)typeUsage.EdmType).TypeUsage));
        }

        throw new ArgumentException("typeUsage");
    }

    /// <summary>
    /// Returns the name of the EdmMember that is safe for
    /// use as an identifier.
    /// </summary>
    public string Escape(EdmMember member)
    {
        if (member == null)
        {
            return null;
        }

        return Escape(member.Name);
    }

    /// <summary>
    /// Returns the name of the EdmType that is safe for
    /// use as an identifier.
    /// </summary>
    public string Escape(EdmType type)
    {
        if (type == null)
        {
            return null;
        }

        return Escape(type.Name);
    }

    /// <summary>
    /// Returns the name of the EdmFunction that is safe for
    /// use as an identifier.
    /// </summary>
    public string Escape(EdmFunction function)
    {
        if (function == null)
        {
            return null;
        }

        return Escape(function.Name);
    }

    /// <summary>
    /// Returns the name of the EnumMember that is safe for
    /// use as an identifier.
    /// </summary>
    public string Escape(EnumMember member)
    {
        if (member == null)
        {
            return null;
        }

        return Escape(member.Name);
    }

    /// <summary>
    /// Returns the name of the EntityContainer that is safe for
    /// use as an identifier.
    /// </summary>
    public string Escape(EntityContainer container)
    {
        if (container == null)
        {
            return null;
        }

        return Escape(container.Name);
    }

    /// <summary>
    /// Returns the name of the EntitySet that is safe for
    /// use as an identifier.
    /// </summary>
    public string Escape(EntitySet set)
    {
        if (set == null)
        {
            return null;
        }

        return Escape(set.Name);
    }

    /// <summary>
    /// Returns the name of the StructuralType that is safe for
    /// use as an identifier.
    /// </summary>
    public string Escape(StructuralType type)
    {
        if (type == null)
        {
            return null;
        }

        return Escape(type.Name);
    }

    /// <summary>
    /// Returns the NamespaceName with each segment safe to
    /// use as an identifier.
    /// </summary>
    public string EscapeNamespace(string namespaceName)
    {
        if (String.IsNullOrEmpty(namespaceName))
        {
            return namespaceName;
        }

        string[] parts = namespaceName.Split('.');
        namespaceName = String.Empty;
        foreach (string part in parts)
        {
            if (namespaceName != String.Empty)
            {
                namespaceName += ".";
            }

            namespaceName += Escape(part);
        }

        return namespaceName;
    }

    /// <summary>
    /// Returns the name of the EdmMember formatted for
    /// use as a field identifier.
    ///
    /// This method changes behavior based on the CamelCaseFields
    /// setting.
    /// </summary>
    public string FieldName(EdmMember member)
    {
        if (member == null)
        {
            return null;
        }

        return FieldName(member.Name);
    }

    /// <summary>
    /// Returns the name of the EntitySet formatted for
    /// use as a field identifier.
    ///
    /// This method changes behavior based on the CamelCaseFields
    /// setting.
    /// </summary>
    public string FieldName(EntitySet set)
    {
        if (set == null)
        {
            return null;
        }

        return FieldName(set.Name);

    }

    private string FieldName(string name)
    {
        if (CamelCaseFields)
        {
            return "_" + CamelCase(name);
        }
        else
        {
            return "_" + name;
        }
    }

    /// <summary>
    /// Returns the name of the Type object formatted for
    /// use in source code.
    ///
    /// This method changes behavior based on the FullyQualifySystemTypes
    /// setting.
    /// </summary>
    public string Escape(Type clrType)
    {
        return Escape(clrType, FullyQualifySystemTypes);
    }

    /// <summary>
    /// Returns the name of the Type object formatted for
    /// use in source code.
    /// </summary>
    public string Escape(Type clrType, bool fullyQualifySystemTypes)
    {
        if(clrType == null)
        {
            return null;
        }

        string typeName;
        if (fullyQualifySystemTypes)
        {
            typeName = "global::" + clrType.FullName;
        }
        else
        {
            typeName = _code.GetTypeOutput(new CodeTypeReference(clrType));
        }
        return typeName;
    }

    /// <summary>
    /// Returns the abstract option if the entity is Abstract, otherwise returns String.Empty
    /// </summary>
    public string AbstractOption(EntityType entity)
    {
        if (entity.Abstract)
        {
            return "abstract";
        }
        return String.Empty;
    }

    /// <summary>
    /// Returns the passed in identifier with the first letter changed to lowercase
    /// </summary>
    public string CamelCase(string identifier)
    {
        if (String.IsNullOrEmpty(identifier))
        {
            return identifier;
        }

        if (identifier.Length == 1)
        {
            return identifier[0].ToString(CultureInfo.InvariantCulture).ToLowerInvariant();
        }

        return identifier[0].ToString(CultureInfo.InvariantCulture).ToLowerInvariant() + identifier.Substring(1);
    }

    /// <summary>
    /// If the value parameter is null or empty an empty string is returned,
    /// otherwise it retuns value with a single space concatenated on the end.
    /// </summary>
    public string SpaceAfter(string value)
    {
        return StringAfter(value, " ");
    }

    /// <summary>
    /// If the value parameter is null or empty an empty string is returned,
    /// otherwise it retuns value with a single space concatenated on the end.
    /// </summary>
    public string SpaceBefore(string value)
    {
        return StringBefore(" ", value);
    }

    /// <summary>
    /// If the value parameter is null or empty an empty string is returned,
    /// otherwise it retuns value with append concatenated on the end.
    /// </summary>
    public string StringAfter(string value, string append)
    {
        if (String.IsNullOrEmpty(value))
        {
            return String.Empty;
        }

            return value + append;
    }

    /// <summary>
    /// If the value parameter is null or empty an empty string is returned,
    /// otherwise it retuns value with prepend concatenated on the front.
    /// </summary>
    public string StringBefore(string prepend, string value)
    {
        if (String.IsNullOrEmpty(value))
        {
            return String.Empty;
        }

        return prepend + value;
    }

    /// <summary>
    /// Returns false and shows an error if the supplied type names aren't case-insensitively unique,
    /// otherwise returns true.
    /// </summary>
    public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable<string> types, string sourceFile)
    {
        return VerifyCaseInsensitiveUniqueness(types, t => string.Format(CultureInfo.CurrentCulture, GetResourceString("Template_CaseInsensitiveTypeConflict"), t), sourceFile);
    }

    /// <summary>
    /// Returns false and shows an error if the supplied strings aren't case-insensitively unique,
    /// otherwise returns true.
    /// </summary>
    private bool VerifyCaseInsensitiveUniqueness(IEnumerable<string> items, Func<string, string> formatMessage, string sourceFile)
    {
        HashSet<string> hash = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
        foreach (string item in items)
        {
            if (!hash.Add(item))
            {
                _textTransformation.Errors.Add(new System.CodeDom.Compiler.CompilerError(sourceFile, -1, -1, "6023", formatMessage(item)));
                return false;
            }
        }
        return true;
    }

    /// <summary>
    /// Returns the names of the items in the supplied collection that correspond to O-Space types.
    /// </summary>
    public IEnumerable<string> GetAllGlobalItems(EdmItemCollection itemCollection)
    {
        return itemCollection.GetItems<GlobalItem>().Where(i => i is EntityType || i is ComplexType || i is EnumType || i is EntityContainer).Select(g => GetGlobalItemName(g));
    }

    /// <summary>
    /// Returns the name of the supplied GlobalItem.
    /// </summary>
    public string GetGlobalItemName(GlobalItem item)
    {
        if (item is EdmType)
        {
            return ((EdmType)item).Name;
        }
        else
        {
            return ((EntityContainer)item).Name;
        }
    }

    /// <summary>
    /// Retuns as full of a name as possible, if a namespace is provided
    /// the namespace and name are combined with a period, otherwise just
    /// the name is returned.
    /// </summary>
    public string CreateFullName(string namespaceName, string name)
    {
        if (String.IsNullOrEmpty(namespaceName))
        {
            return name;
        }

        return namespaceName + "." + name;
    }

    /// <summary>
    /// Retuns a literal representing the supplied value.
    /// </summary>
    public string CreateLiteral(object value)
    {
        if (value == null)
        {
            return string.Empty;
        }

        Type type = value.GetType();
        if (type.IsEnum)
        {
            return type.FullName + "." + value.ToString();
        }
        if (type == typeof(Guid))
        {
            return string.Format(CultureInfo.InvariantCulture, "new Guid(\"{0}\")",
                                 ((Guid)value).ToString("D", CultureInfo.InvariantCulture));
        }
        else if (type == typeof(DateTime))
        {
            return string.Format(CultureInfo.InvariantCulture, "new DateTime({0}, DateTimeKind.Unspecified)",
                                 ((DateTime)value).Ticks);
        }
        else if (type == typeof(byte[]))
        {
            var arrayInit = string.Join(", ", ((byte[])value).Select(b => b.ToString(CultureInfo.InvariantCulture)).ToArray());
            return string.Format(CultureInfo.InvariantCulture, "new Byte[] {{{0}}}", arrayInit);
        }
        else if (type == typeof(DateTimeOffset))
        {
            var dto = (DateTimeOffset)value;
            return string.Format(CultureInfo.InvariantCulture, "new DateTimeOffset({0}, new TimeSpan({1}))",
                                 dto.Ticks, dto.Offset.Ticks);
        }
        else if (type == typeof(TimeSpan))
        {
            return string.Format(CultureInfo.InvariantCulture, "new TimeSpan({0})",
                                 ((TimeSpan)value).Ticks);
        }

        var expression = new CodePrimitiveExpression(value);
        var writer = new StringWriter();
        CSharpCodeProvider code = new CSharpCodeProvider();
        code.GenerateCodeFromExpression(expression, writer, new CodeGeneratorOptions());
        return writer.ToString();
    }

    /// <summary>
    /// Returns a resource string from the System.Data.Entity.Design assembly.
    /// </summary>
    public static string GetResourceString(string resourceName, CultureInfo culture = null)
    {
        if(_resourceManager == null)
        {
            _resourceManager = new System.Resources.ResourceManager("System.Data.Entity.Design",
                typeof(System.Data.Entity.Design.MetadataItemCollectionFactory).Assembly);
        }

        return _resourceManager.GetString(resourceName, culture);
    }
    static System.Resources.ResourceManager _resourceManager;

    private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName";

    /// <summary>
    /// Gets the entity, complex, or enum types for which code should be generated from the given item collection.
    /// Any types for which an ExternalTypeName annotation has been applied in the conceptual model
    /// metadata (CSDL) are filtered out of the returned list.
    /// </summary>
    /// <typeparam name="T">The type of item to return.</typeparam>
    /// <param name="itemCollection">The item collection to look in.</param>
    /// <returns>The items to generate.</returns>
    public IEnumerable<T> GetItemsToGenerate<T>(ItemCollection itemCollection) where T: GlobalItem
    {
        return itemCollection.GetItems<T>().Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName));
    }

    /// <summary>
    /// Returns the escaped type name to use for the given usage of a c-space type in o-space. This might be
    /// an external type name if the ExternalTypeName annotation has been specified in the
    /// conceptual model metadata (CSDL).
    /// </summary>
    /// <param name="typeUsage">The c-space type usage to get a name for.</param>
    /// <returns>The type name to use.</returns>
    public string GetTypeName(TypeUsage typeUsage)
    {
        return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null);
    }

    /// <summary>
    /// Returns the escaped type name to use for the given c-space type in o-space. This might be
    /// an external type name if the ExternalTypeName annotation has been specified in the
    /// conceptual model metadata (CSDL).
    /// </summary>
    /// <param name="edmType">The c-space type to get a name for.</param>
    /// <returns>The type name to use.</returns>
    public string GetTypeName(EdmType edmType)
    {
        return GetTypeName(edmType, isNullable: null, modelNamespace: null);
    }

    /// <summary>
    /// Returns the escaped type name to use for the given usage of an c-space type in o-space. This might be
    /// an external type name if the ExternalTypeName annotation has been specified in the
    /// conceptual model metadata (CSDL).
    /// </summary>
    /// <param name="typeUsage">The c-space type usage to get a name for.</param>
    /// <param name="modelNamespace">If not null and the type's namespace does not match this namespace, then a
    /// fully qualified name will be returned.</param>
    /// <returns>The type name to use.</returns>
    public string GetTypeName(TypeUsage typeUsage, string modelNamespace)
    {
        return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace);
    }

    /// <summary>
    /// Returns the escaped type name to use for the given c-space type in o-space. This might be
    /// an external type name if the ExternalTypeName annotation has been specified in the
    /// conceptual model metadata (CSDL).
    /// </summary>
    /// <param name="edmType">The c-space type to get a name for.</param>
    /// <param name="modelNamespace">If not null and the type's namespace does not match this namespace, then a
    /// fully qualified name will be returned.</param>
    /// <returns>The type name to use.</returns>
    public string GetTypeName(EdmType edmType, string modelNamespace)
    {
        return GetTypeName(edmType, isNullable: null, modelNamespace: modelNamespace);
    }

    /// <summary>
    /// Returns the escaped type name to use for the given c-space type in o-space. This might be
    /// an external type name if the ExternalTypeName annotation has been specified in the
    /// conceptual model metadata (CSDL).
    /// </summary>
    /// <param name="edmType">The c-space type to get a name for.</param>
    /// <param name="isNullable">Set this to true for nullable usage of this type.</param>
    /// <param name="modelNamespace">If not null and the type's namespace does not match this namespace, then a
    /// fully qualified name will be returned.</param>
    /// <returns>The type name to use.</returns>
    private string GetTypeName(EdmType edmType, bool? isNullable, string modelNamespace)
    {
        if (edmType == null)
        {
            return null;
        }

        var collectionType = edmType as CollectionType;
        if (collectionType != null)
        {
            return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", GetTypeName(collectionType.TypeUsage, modelNamespace));
        }

        // Try to get an external type name, and if that is null, then try to get escape the name from metadata,
        // possibly namespace-qualifying it.
        var typeName = Escape(edmType.MetadataProperties
                              .Where(p => p.Name == ExternalTypeNameAttributeName)
                              .Select(p => (string)p.Value)
                              .FirstOrDefault())
            ??
            (modelNamespace != null && edmType.NamespaceName != modelNamespace ?
             CreateFullName(EscapeNamespace(edmType.NamespaceName), Escape(edmType)) :
             Escape(edmType));

        if (edmType is StructuralType)
        {
            return typeName;
        }

        if (edmType is SimpleType)
        {
            var clrType = _ef.UnderlyingClrType(edmType);
            if (!(edmType is EnumType))
            {
                typeName = Escape(clrType);
            }

            return clrType.IsValueType && isNullable == true ?
                String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName) :
                typeName;
        }

        throw new ArgumentException("typeUsage");
    }
}

/// <summary>
/// Responsible for making the Entity Framework Metadata more
/// accessible for code generation.
/// </summary>
public class MetadataTools
{
    private readonly DynamicTextTransformation _textTransformation;

    /// <summary>
    /// Initializes an MetadataTools Instance  with the
    /// TextTransformation (T4 generated class) that is currently running
    /// </summary>
    public MetadataTools(object textTransformation)
    {
        if (textTransformation == null)
        {
            throw new ArgumentNullException("textTransformation");
        }

        _textTransformation = DynamicTextTransformation.Create(textTransformation);
    }

    /// <summary>
    /// This method returns the underlying CLR type of the o-space type corresponding to the supplied <paramref name="typeUsage"/>
    /// Note that for an enum type this means that the type backing the enum will be returned, not the enum type itself.
    /// </summary>
    public Type ClrType(TypeUsage typeUsage)
    {
        return UnderlyingClrType(typeUsage.EdmType);
    }

    /// <summary>
    /// This method returns the underlying CLR type given the c-space type.
    /// Note that for an enum type this means that the type backing the enum will be returned, not the enum type itself.
    /// </summary>
    public Type UnderlyingClrType(EdmType edmType)
    {
        var primitiveType = edmType as PrimitiveType;
        if (primitiveType != null)
        {
            return primitiveType.ClrEquivalentType;
        }

        var enumType = edmType as EnumType;
        if (enumType != null)
        {
            return enumType.UnderlyingType.ClrEquivalentType;
        }

        return typeof(object);
    }

    /// <summary>
    /// True if the EdmProperty is a key of its DeclaringType, False otherwise.
    /// </summary>
    public bool IsKey(EdmProperty property)
    {
        if (property != null && property.DeclaringType.BuiltInTypeKind == BuiltInTypeKind.EntityType)
        {
            return ((EntityType)property.DeclaringType).KeyMembers.Contains(property);
        }

        return false;
    }

    /// <summary>
    /// True if the EdmProperty TypeUsage is Nullable, False otherwise.
    /// </summary>
    public bool IsNullable(EdmProperty property)
    {
        return property != null && IsNullable(property.TypeUsage);
    }

    /// <summary>
    /// True if the TypeUsage is Nullable, False otherwise.
    /// </summary>
    public bool IsNullable(TypeUsage typeUsage)
    {
        Facet nullableFacet = null;
        if (typeUsage != null &&
            typeUsage.Facets.TryGetValue("Nullable", true, out nullableFacet))
        {
            return (bool)nullableFacet.Value;
        }

        return false;
    }

    /// <summary>
    /// If the passed in TypeUsage represents a collection this method returns final element
    /// type of the collection, otherwise it returns the value passed in.
    /// </summary>
    public TypeUsage GetElementType(TypeUsage typeUsage)
    {
        if (typeUsage == null)
        {
            return null;
        }

        if (typeUsage.EdmType is CollectionType)
        {
            return GetElementType(((CollectionType)typeUsage.EdmType).TypeUsage);
        }
        else
        {
            return typeUsage;
        }
    }

    /// <summary>
    /// Returns the NavigationProperty that is the other end of the same association set if it is
    /// available, otherwise it returns null.
    /// </summary>
    public NavigationProperty Inverse(NavigationProperty navProperty)
    {
        if(navProperty == null)
        {
            return null;
        }

        EntityType toEntity = navProperty.ToEndMember.GetEntityType();
        return toEntity.NavigationProperties
            .SingleOrDefault(n => Object.ReferenceEquals(n.RelationshipType, navProperty.RelationshipType) && !Object.ReferenceEquals(n, navProperty));
    }

    /// <summary>
    /// Given a property on the dependent end of a referential constraint, returns the corresponding property on the principal end.
    /// Requires: The association has a referential constraint, and the specified dependentProperty is one of the properties on the dependent end.
    /// </summary>
    public EdmProperty GetCorrespondingPrincipalProperty(NavigationProperty navProperty, EdmProperty dependentProperty)
    {
        if (navProperty == null)
        {
            throw new ArgumentNullException("navProperty");
        }

        if (dependentProperty == null)
        {
            throw new ArgumentNullException("dependentProperty");
        }

        ReadOnlyMetadataCollection<EdmProperty> fromProperties = GetPrincipalProperties(navProperty);
        ReadOnlyMetadataCollection<EdmProperty> toProperties = GetDependentProperties(navProperty);
        return fromProperties[toProperties.IndexOf(dependentProperty)];
    }

    /// <summary>
    /// Given a property on the principal end of a referential constraint, returns the corresponding property on the dependent end.
    /// Requires: The association has a referential constraint, and the specified principalProperty is one of the properties on the principal end.
    /// </summary>
    public EdmProperty GetCorrespondingDependentProperty(NavigationProperty navProperty, EdmProperty principalProperty)
    {
        if (navProperty == null)
        {
            throw new ArgumentNullException("navProperty");
        }

        if (principalProperty == null)
        {
            throw new ArgumentNullException("principalProperty");
        }

        ReadOnlyMetadataCollection<EdmProperty> fromProperties = GetPrincipalProperties(navProperty);
        ReadOnlyMetadataCollection<EdmProperty> toProperties = GetDependentProperties(navProperty);
        return toProperties[fromProperties.IndexOf(principalProperty)];
    }

    /// <summary>
    /// Gets the collection of properties that are on the principal end of a referential constraint for the specified navigation property.
    /// Requires: The association has a referential constraint.
    /// </summary>
    public ReadOnlyMetadataCollection<EdmProperty> GetPrincipalProperties(NavigationProperty navProperty)
    {
        if (navProperty == null)
        {
            throw new ArgumentNullException("navProperty");
        }

        return ((AssociationType)navProperty.RelationshipType).ReferentialConstraints[0].FromProperties;
    }

    /// <summary>
    /// Gets the collection of properties that are on the dependent end of a referential constraint for the specified navigation property.
    /// Requires: The association has a referential constraint.
    /// </summary>
    public ReadOnlyMetadataCollection<EdmProperty> GetDependentProperties(NavigationProperty navProperty)
    {
        if (navProperty == null)
        {
            throw new ArgumentNullException("navProperty");
        }

        return ((AssociationType)navProperty.RelationshipType).ReferentialConstraints[0].ToProperties;
    }

    /// <summary>
    /// True if this entity type requires the HandleCascadeDelete method defined and the method has
    /// not been defined on any base type
    /// </summary>
    public bool NeedsHandleCascadeDeleteMethod(ItemCollection itemCollection, EntityType entity)
    {
        bool needsMethod = ContainsCascadeDeleteAssociation(itemCollection, entity);
        // Check to make sure no base types have already declared this method
        EntityType baseType = entity.BaseType as EntityType;
        while(needsMethod && baseType != null)
        {
            needsMethod = !ContainsCascadeDeleteAssociation(itemCollection, baseType);
            baseType = baseType.BaseType as EntityType;
        }
        return needsMethod;
    }

    /// <summary>
    /// True if this entity type participates in any relationships where the other end has an OnDelete
    /// cascade delete defined, or if it is the dependent in any identifying relationships
    /// </summary>
    private bool ContainsCascadeDeleteAssociation(ItemCollection itemCollection, EntityType entity)
    {
        return itemCollection.GetItems<AssociationType>().Where(a =>
                ((RefType)a.AssociationEndMembers[0].TypeUsage.EdmType).ElementType == entity && IsCascadeDeletePrincipal(a.AssociationEndMembers[1]) ||
                ((RefType)a.AssociationEndMembers[1].TypeUsage.EdmType).ElementType == entity && IsCascadeDeletePrincipal(a.AssociationEndMembers[0])).Any();
    }

    /// <summary>
    /// True if the source end of the specified navigation property is the principal in an identifying relationship.
    /// or if the source end has cascade delete defined.
    /// </summary>
    public bool IsCascadeDeletePrincipal(NavigationProperty navProperty)
    {
        if (navProperty == null)
        {
            throw new ArgumentNullException("navProperty");
        }

        return IsCascadeDeletePrincipal((AssociationEndMember)navProperty.FromEndMember);
    }

    /// <summary>
    /// True if the specified association end is the principal in an identifying relationship.
    /// or if the association end has cascade delete defined.
    /// </summary>
    public bool IsCascadeDeletePrincipal(AssociationEndMember associationEnd)
    {
        if (associationEnd == null)
        {
            throw new ArgumentNullException("associationEnd");
        }

        return associationEnd.DeleteBehavior == OperationAction.Cascade || IsPrincipalEndOfIdentifyingRelationship(associationEnd);
    }

    /// <summary>
    /// True if the specified association end is the principal end in an identifying relationship.
    /// In order to be an identifying relationship, the association must have a referential constraint where all of the dependent properties are part of the dependent type's primary key.
    /// </summary>
    public bool IsPrincipalEndOfIdentifyingRelationship(AssociationEndMember associationEnd)
    {
        if (associationEnd == null)
        {
            throw new ArgumentNullException("associationEnd");
        }

        ReferentialConstraint refConstraint = ((AssociationType)associationEnd.DeclaringType).ReferentialConstraints.Where(rc => rc.FromRole == associationEnd).SingleOrDefault();
        if (refConstraint != null)
        {
            EntityType entity = refConstraint.ToRole.GetEntityType();
            return !refConstraint.ToProperties.Where(tp => !entity.KeyMembers.Contains(tp)).Any();
        }
        return false;
    }

    /// <summary>
    /// True if the specified association type is an identifying relationship.
    /// In order to be an identifying relationship, the association must have a referential constraint where all of the dependent properties are part of the dependent type's primary key.
    /// </summary>
    public bool IsIdentifyingRelationship(AssociationType association)
    {
        if (association == null)
        {
            throw new ArgumentNullException("association");
        }

        return IsPrincipalEndOfIdentifyingRelationship(association.AssociationEndMembers[0]) || IsPrincipalEndOfIdentifyingRelationship(association.AssociationEndMembers[1]);
    }

    /// <summary>
    /// requires: firstType is not null
    /// effects: if secondType is among the base types of the firstType, return true,
    /// otherwise returns false.
    /// when firstType is same as the secondType, return false.
    /// </summary>
    public bool IsSubtypeOf(EdmType firstType, EdmType secondType)
    {
        if (secondType == null)
        {
            return false;
        }

        // walk up firstType hierarchy list
        for (EdmType t = firstType.BaseType; t != null; t = t.BaseType)
        {
            if (t == secondType)
                return true;
        }
        return false;
    }

    /// <summary>
    /// Returns the subtype of the EntityType in the current itemCollection
    /// </summary>
    public IEnumerable<EntityType> GetSubtypesOf(EntityType type, ItemCollection itemCollection, bool includeAbstractTypes)
    {
        if (type != null)
        {
            IEnumerable<EntityType> typesInCollection = itemCollection.GetItems<EntityType>();
            foreach (EntityType typeInCollection in typesInCollection)
            {
                if (type.Equals(typeInCollection) == false && this.IsSubtypeOf(typeInCollection, type))
                {
                    if ( includeAbstractTypes || !typeInCollection.Abstract)
                    {
                        yield return typeInCollection;
                    }
               }
            }
        }
    }

    public static bool TryGetStringMetadataPropertySetting(MetadataItem item, string propertyName, out string value)
    {
        value = null;
        MetadataProperty property = item.MetadataProperties.FirstOrDefault(p => p.Name == propertyName);
        if (property != null)
        {
            value = (string)property.Value;
        }
        return value != null;
    }
}

/// <summary>
/// Responsible for loading an EdmItemCollection from a .edmx file or .csdl files
/// </summary>
public class MetadataLoader
{
    private readonly DynamicTextTransformation _textTransformation;

    /// <summary>
    /// Initializes an MetadataLoader Instance  with the
    /// TextTransformation (T4 generated class) that is currently running
    /// </summary>
    public MetadataLoader(object textTransformation)
    {
        if (textTransformation == null)
        {
            throw new ArgumentNullException("textTransformation");
        }

        _textTransformation = DynamicTextTransformation.Create(textTransformation);
    }

    /// <summary>
    /// Load the metadata for Edm, Store, and Mapping collections and register them
    /// with a new MetadataWorkspace, returns false if any of the parts can't be
    /// created, some of the ItemCollections may be registered and usable even if false is
    /// returned
    /// </summary>
    public bool TryLoadAllMetadata(string inputFile, out MetadataWorkspace metadataWorkspace)
    {
        metadataWorkspace = new MetadataWorkspace();

        EdmItemCollection edmItemCollection = CreateEdmItemCollection(inputFile);
        metadataWorkspace.RegisterItemCollection(edmItemCollection);

        StoreItemCollection storeItemCollection = null;
        if (TryCreateStoreItemCollection(inputFile, out storeItemCollection))
        {
            StorageMappingItemCollection storageMappingItemCollection = null;
            if (TryCreateStorageMappingItemCollection(inputFile, edmItemCollection, storeItemCollection, out storageMappingItemCollection))
            {
                metadataWorkspace.RegisterItemCollection(storeItemCollection);
                metadataWorkspace.RegisterItemCollection(storageMappingItemCollection);
                return true;
            }
        }

        return false;
    }

    /// <summary>
    /// Create an EdmItemCollection loaded with the metadata provided
    /// </summary>
    public EdmItemCollection CreateEdmItemCollection(string sourcePath, params string[] referenceSchemas)
    {
        EdmItemCollection edmItemCollection;
        if(TryCreateEdmItemCollection(sourcePath, referenceSchemas, out edmItemCollection))
        {
            return edmItemCollection;
        }

        return new EdmItemCollection();
    }

    /// <summary>
    /// Attempts to create a EdmItemCollection from the specified metadata file
    /// </summary>
    public bool TryCreateEdmItemCollection(string sourcePath, out EdmItemCollection edmItemCollection)
    {
        return TryCreateEdmItemCollection(sourcePath, null, out edmItemCollection);
    }

    /// <summary>
    /// Attempts to create a EdmItemCollection from the specified metadata file
    /// </summary>
    public bool TryCreateEdmItemCollection(string sourcePath, string[] referenceSchemas, out EdmItemCollection edmItemCollection)
    {
        edmItemCollection = null;

        if (!ValidateInputPath(sourcePath, _textTransformation))
        {
            return false;
        }

        if (referenceSchemas == null)
        {
            referenceSchemas = new string[0];
        }

        ItemCollection itemCollection = null;
        sourcePath = _textTransformation.Host.ResolvePath(sourcePath);
        EdmItemCollectionBuilder collectionBuilder = new EdmItemCollectionBuilder(_textTransformation, referenceSchemas.Select(s => _textTransformation.Host.ResolvePath(s)).Where(s => s != sourcePath));
        if (collectionBuilder.TryCreateItemCollection(sourcePath, out itemCollection))
        {
            edmItemCollection = (EdmItemCollection)itemCollection;
        }

        return edmItemCollection != null;
    }

    /// <summary>
    /// Attempts to create a StoreItemCollection from the specified metadata file
    /// </summary>
    public bool TryCreateStoreItemCollection(string sourcePath, out StoreItemCollection storeItemCollection)
    {
        storeItemCollection = null;

        if (!ValidateInputPath(sourcePath, _textTransformation))
        {
            return false;
        }

        ItemCollection itemCollection = null;
        StoreItemCollectionBuilder collectionBuilder = new StoreItemCollectionBuilder(_textTransformation);
        if (collectionBuilder.TryCreateItemCollection(_textTransformation.Host.ResolvePath(sourcePath), out itemCollection))
        {
            storeItemCollection = (StoreItemCollection)itemCollection;
        }
        return storeItemCollection != null;
    }

    /// <summary>
    /// Attempts to create a StorageMappingItemCollection from the specified metadata file, EdmItemCollection, and StoreItemCollection
    /// </summary>
    public bool TryCreateStorageMappingItemCollection(string sourcePath, EdmItemCollection edmItemCollection, StoreItemCollection storeItemCollection, out StorageMappingItemCollection storageMappingItemCollection)
    {
        storageMappingItemCollection = null;

        if (!ValidateInputPath(sourcePath, _textTransformation))
        {
            return false;
        }

        if (edmItemCollection == null)
        {
            throw new ArgumentNullException("edmItemCollection");
        }

        if (storeItemCollection == null)
        {
            throw new ArgumentNullException("storeItemCollection");
        }

        ItemCollection itemCollection = null;
        StorageMappingItemCollectionBuilder collectionBuilder = new StorageMappingItemCollectionBuilder(_textTransformation, edmItemCollection, storeItemCollection);
        if (collectionBuilder.TryCreateItemCollection(_textTransformation.Host.ResolvePath(sourcePath), out itemCollection))
        {
            storageMappingItemCollection = (StorageMappingItemCollection)itemCollection;
        }
        return storageMappingItemCollection != null;
    }

    /// <summary>
    /// Gets the Model Namespace from the provided schema file.
    /// </summary>
    public string GetModelNamespace(string sourcePath)
    {
        if (!ValidateInputPath(sourcePath, _textTransformation))
        {
            return String.Empty;
        }

        EdmItemCollectionBuilder builder = new EdmItemCollectionBuilder(_textTransformation);
        XElement model;
        if(builder.TryLoadRootElement(_textTransformation.Host.ResolvePath(sourcePath), out model))
        {
            XAttribute attribute = model.Attribute("Namespace");
            if (attribute != null)
            {
                return attribute.Value;
            }
        }

        return String.Empty;
    }

    /// <summary>
    /// Returns true if the specified file path is valid
    /// </summary>
    private static bool ValidateInputPath(string sourcePath, DynamicTextTransformation textTransformation)
    {
        if (String.IsNullOrEmpty(sourcePath))
        {
            throw new ArgumentException("sourcePath");
        }

        if(sourcePath == "$edmxInputFile$")
        {
            textTransformation.Errors.Add(new CompilerError(textTransformation.Host.TemplateFile ?? CodeGenerationTools.GetResourceString("Template_CurrentlyRunningTemplate"), -1, -1, string.Empty,
                CodeGenerationTools.GetResourceString("Template_ReplaceVsItemTemplateToken")));
            return false;
        }

        return true;
    }

    /// <summary>
    /// Base class for ItemCollectionBuilder classes that
    /// loads the specific types of metadata
    /// </summary>
    private abstract class ItemCollectionBuilder
    {
        private readonly DynamicTextTransformation _textTransformation;
        private readonly string _fileExtension;
        private readonly string _edmxSectionName;
        private readonly string  _rootElementName;

        /// <summary>
        /// FileExtension for individual (non-edmx) metadata file for this
        /// specific ItemCollection type
        /// </summary>
        public string FileExtension
        {
            get { return _fileExtension; }
        }

        /// <summary>
        /// The name of the XmlElement in the .edmx <Runtime> element
        /// to find this ItemCollection's metadata
        /// </summary>
        public string EdmxSectionName
        {
            get { return _edmxSectionName; }
        }

        /// <summary>
        /// The name of the root element of this ItemCollection's metadata
        /// </summary>
        public string RootElementName
        {
            get { return _rootElementName; }
        }

        /// <summary>
        /// Method to build the appropriate ItemCollection
        /// </summary>
        protected abstract ItemCollection CreateItemCollection(IEnumerable<XmlReader> readers, out IList<EdmSchemaError> errors);

        /// <summary>
        /// Ctor to setup the ItemCollectionBuilder members
        /// </summary>
        protected ItemCollectionBuilder(DynamicTextTransformation textTransformation, string fileExtension, string edmxSectionName, string rootElementName)
        {
            _textTransformation = textTransformation;
            _fileExtension = fileExtension;
            _edmxSectionName = edmxSectionName;
            _rootElementName = rootElementName;
        }

        /// <summary>
        /// Selects a namespace from the supplied constants.
        /// </summary>
        protected abstract string GetNamespace(SchemaConstants constants);

        /// <summary>
        /// Try to create an ItemCollection loaded with the metadata provided
        /// </summary>
        public bool TryCreateItemCollection(string sourcePath, out ItemCollection itemCollection)
        {
            itemCollection = null;

            if (!ValidateInputPath(sourcePath, _textTransformation))
            {
                return false;
            }

            XElement schemaElement = null;
            if (TryLoadRootElement(sourcePath, out schemaElement))
            {
                List<XmlReader> readers = new List<XmlReader>();
                try
                {
                    readers.Add(schemaElement.CreateReader());
                    IList<EdmSchemaError> errors = null;

                    ItemCollection tempItemCollection = CreateItemCollection(readers, out errors);
                    if (ProcessErrors(errors, sourcePath))
                    {
                        return false;
                    }

                    itemCollection = tempItemCollection;
                    return true;
                }
                finally
                {
                    foreach (XmlReader reader in readers)
                    {
                        ((IDisposable)reader).Dispose();
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// Tries to load the root element from the metadata file provided
        /// </summary>
        public bool TryLoadRootElement(string sourcePath, out XElement schemaElement)
        {
            schemaElement = null;
            string extension = Path.GetExtension(sourcePath);
            if (extension.Equals(".edmx", StringComparison.InvariantCultureIgnoreCase))
            {
                return TryLoadRootElementFromEdmx(sourcePath, out schemaElement);
            }
            else if(extension.Equals(FileExtension, StringComparison.InvariantCultureIgnoreCase))
            {
                // load from single metadata file (.csdl, .ssdl, or .msl)
                schemaElement = XElement.Load(sourcePath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo);
                return true;
            }

            return false;
        }

        /// <summary>
        /// Tries to load the root element from the provided edmxDocument
        /// </summary>
        private bool TryLoadRootElementFromEdmx(XElement edmxDocument, SchemaConstants schemaConstants, string sectionName, string rootElementName, out XElement rootElement)
        {
            rootElement = null;

            XNamespace edmxNs = schemaConstants.EdmxNamespace;
            XNamespace sectionNs = GetNamespace(schemaConstants);

            XElement runtime = edmxDocument.Element(edmxNs  + "Runtime");
            if (runtime == null)
            {
                return false;
            }

            XElement section = runtime.Element(edmxNs + sectionName);
            if (section == null)
            {
                return false;
            }

            string templateVersion;

            if (!TemplateMetadata.TryGetValue(MetadataConstants.TT_TEMPLATE_VERSION, out templateVersion))
            {
                templateVersion = MetadataConstants.DEFAULT_TEMPLATE_VERSION;
            }

            if (schemaConstants.MinimumTemplateVersion > new Version(templateVersion))
            {
                _textTransformation.Errors.Add(new CompilerError(
                    _textTransformation.Host.TemplateFile ?? CodeGenerationTools.GetResourceString("Template_CurrentlyRunningTemplate"), -1, -1, string.Empty,
                        CodeGenerationTools.GetResourceString("Template_UnsupportedSchema"))
                {IsWarning = true});
            }

            rootElement = section.Element(sectionNs + rootElementName);
            return rootElement != null;
        }

        /// <summary>
        /// Tries to load the root element from the provided .edmx metadata file
        /// </summary>
        private bool TryLoadRootElementFromEdmx(string edmxPath, out XElement rootElement)
        {
            rootElement = null;

            XElement element = XElement.Load(edmxPath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo);

            return TryLoadRootElementFromEdmx(element, MetadataConstants.V3_SCHEMA_CONSTANTS, EdmxSectionName, RootElementName, out rootElement)
                || TryLoadRootElementFromEdmx(element, MetadataConstants.V2_SCHEMA_CONSTANTS, EdmxSectionName, RootElementName, out rootElement)
                || TryLoadRootElementFromEdmx(element, MetadataConstants.V1_SCHEMA_CONSTANTS, EdmxSectionName, RootElementName, out rootElement);
        }

        /// <summary>
        /// Takes an Enumerable of EdmSchemaErrors, and adds them
        /// to the errors collection of the template class
        /// </summary>
        private bool ProcessErrors(IEnumerable<EdmSchemaError> errors, string sourceFilePath)
        {
            bool foundErrors = false;
            foreach (EdmSchemaError error in errors)
            {
                CompilerError newError = new CompilerError(error.SchemaLocation, error.Line, error.Column,
                                                 error.ErrorCode.ToString(CultureInfo.InvariantCulture),
                                                 error.Message);
                newError.IsWarning = error.Severity == EdmSchemaErrorSeverity.Warning;
                foundErrors |= error.Severity == EdmSchemaErrorSeverity.Error;
                if (error.SchemaLocation == null)
                {
                    newError.FileName = sourceFilePath;
                }
                _textTransformation.Errors.Add(newError);
            }

            return foundErrors;
        }
    }

    /// <summary>
    /// Builder class for creating a StorageMappingItemCollection
    /// </summary>
    private class StorageMappingItemCollectionBuilder : ItemCollectionBuilder
    {
        private readonly EdmItemCollection _edmItemCollection;
        private readonly StoreItemCollection _storeItemCollection;

        public StorageMappingItemCollectionBuilder(DynamicTextTransformation textTransformation, EdmItemCollection edmItemCollection, StoreItemCollection storeItemCollection)
            : base(textTransformation, MetadataConstants.MSL_EXTENSION, MetadataConstants.MSL_EDMX_SECTION_NAME, MetadataConstants.MSL_ROOT_ELEMENT_NAME)
        {
            _edmItemCollection = edmItemCollection;
            _storeItemCollection = storeItemCollection;
        }

        protected override ItemCollection CreateItemCollection(IEnumerable<XmlReader> readers, out IList<EdmSchemaError> errors)
        {
            return MetadataItemCollectionFactory.CreateStorageMappingItemCollection(_edmItemCollection, _storeItemCollection, readers, out errors);
        }

        /// <summary>
        /// Selects a namespace from the supplied constants.
        /// </summary>
        protected override string GetNamespace(SchemaConstants constants)
        {
            return constants.MslNamespace;
        }
    }

    /// <summary>
    /// Builder class for creating a StoreItemCollection
    /// </summary>
    private class StoreItemCollectionBuilder : ItemCollectionBuilder
    {
        public StoreItemCollectionBuilder(DynamicTextTransformation textTransformation)
            : base(textTransformation, MetadataConstants.SSDL_EXTENSION, MetadataConstants.SSDL_EDMX_SECTION_NAME, MetadataConstants.SSDL_ROOT_ELEMENT_NAME)
        {
        }

        protected override ItemCollection CreateItemCollection(IEnumerable<XmlReader> readers, out IList<EdmSchemaError> errors)
        {
            return MetadataItemCollectionFactory.CreateStoreItemCollection(readers, out errors);
        }

        /// <summary>
        /// Selects a namespace from the supplied constants.
        /// </summary>
        protected override string GetNamespace(SchemaConstants constants)
        {
            return constants.SsdlNamespace;
        }
    }

    /// <summary>
    /// Builder class for creating a EdmItemCollection
    /// </summary>
    private class EdmItemCollectionBuilder : ItemCollectionBuilder
    {
        private List<string> _referenceSchemas = new List<string>();

        public EdmItemCollectionBuilder(DynamicTextTransformation textTransformation)
            : base(textTransformation, MetadataConstants.CSDL_EXTENSION, MetadataConstants.CSDL_EDMX_SECTION_NAME, MetadataConstants.CSDL_ROOT_ELEMENT_NAME)
        {
        }

        public EdmItemCollectionBuilder(DynamicTextTransformation textTransformation, IEnumerable<string> referenceSchemas)
            : this(textTransformation)
        {
            _referenceSchemas.AddRange(referenceSchemas);
        }

        protected override ItemCollection CreateItemCollection(IEnumerable<XmlReader> readers, out IList<EdmSchemaError> errors)
        {
            List<XmlReader> ownedReaders = new List<XmlReader>();
            List<XmlReader> allReaders = new List<XmlReader>();
            try
            {
                allReaders.AddRange(readers);
                foreach (string path in _referenceSchemas.Distinct())
                {
                    XElement reference;
                    if(TryLoadRootElement(path, out reference))
                    {
                        XmlReader reader = reference.CreateReader();
                        allReaders.Add(reader);
                        ownedReaders.Add(reader);
                    }
                }

                return MetadataItemCollectionFactory.CreateEdmItemCollection(allReaders, out errors);
            }
            finally
            {
                foreach (XmlReader reader in ownedReaders)
                {
                    ((IDisposable)reader).Dispose();
                }
            }
        }

        /// <summary>
        /// Selects a namespace from the supplied constants.
        /// </summary>
        protected override string GetNamespace(SchemaConstants constants)
        {
            return constants.CsdlNamespace;
        }
    }
}

/// <summary>
/// Responsible for encapsulating the retrieval and translation of the CodeGeneration
/// annotations in the EntityFramework Metadata to a form that is useful in code generation.
/// </summary>
public static class Accessibility
{
    private const string GETTER_ACCESS = "http://schemas.microsoft.com/ado/2006/04/codegeneration:GetterAccess";
    private const string SETTER_ACCESS = "http://schemas.microsoft.com/ado/2006/04/codegeneration:SetterAccess";
    private const string TYPE_ACCESS = "http://schemas.microsoft.com/ado/2006/04/codegeneration:TypeAccess";
    private const string METHOD_ACCESS = "http://schemas.microsoft.com/ado/2006/04/codegeneration:MethodAccess";
    private const string ACCESS_PROTECTED = "Protected";
    private const string ACCESS_INTERNAL = "Internal";
    private const string ACCESS_PRIVATE = "Private";
    private static readonly Dictionary<string, int> AccessibilityRankIdLookup = new Dictionary<string, int>
        {
            { "private", 1},
            { "internal", 2},
            { "protected", 3},
            { "public", 4},
        };

    /// <summary>
    /// Gets the accessibility that should be applied to a type being generated from the provided GlobalItem.
    ///
    /// defaults to public if no annotation is found.
    /// </summary>
    public static string ForType(GlobalItem item)
    {
        if (item == null)
        {
            return null;
        }

        return GetAccessibility(item, TYPE_ACCESS);
    }

    /// <summary>
    /// Gets the accessibility that should be applied at the property level for a property being
    /// generated from the provided EdmMember.
    ///
    /// defaults to public if no annotation is found.
    /// </summary>
    public static string ForProperty(EdmMember member)
    {
        if (member == null)
        {
            return null;
        }

        string getterAccess, setterAccess, propertyAccess;
        CalculatePropertyAccessibility(member, out propertyAccess, out getterAccess, out setterAccess);
        return propertyAccess;
    }

    /// <summary>
    /// Gets the accessibility that should be applied at the property level for a Read-Only property being
    /// generated from the provided EdmMember.
    ///
    /// defaults to public if no annotation is found.
    /// </summary>
    public static string ForReadOnlyProperty(EdmMember member)
    {
        if (member == null)
        {
            return null;
        }

        return GetAccessibility(member, GETTER_ACCESS);
    }

    /// <summary>
    /// Gets the accessibility that should be applied at the property level for a property being
    /// generated from the provided EntitySet.
    ///
    /// defaults to public if no annotation is found.
    /// </summary>
    public static string ForReadOnlyProperty(EntitySet set)
    {
        if (set == null)
        {
            return null;
        }

        return GetAccessibility(set, GETTER_ACCESS);
    }

    /// <summary>
    /// Gets the accessibility that should be applied at the property level for a Write-Only property being
    /// generated from the provided EdmMember.
    ///
    /// defaults to public if no annotation is found.
    /// </summary>
    public static string ForWriteOnlyProperty(EdmMember member)
    {
        if (member == null)
        {
            return null;
        }

        return GetAccessibility(member, SETTER_ACCESS);
    }


    /// <summary>
    /// Gets the accessibility that should be applied at the get level for a property being
    /// generated from the provided EdmMember.
    ///
    /// defaults to empty if no annotation is found or the accessibility is the same as the property level.
    /// </summary>
    public static string ForGetter(EdmMember member)
    {
        if (member == null)
        {
            return null;
        }

        string getterAccess, setterAccess, propertyAccess;
        CalculatePropertyAccessibility(member, out propertyAccess, out getterAccess, out setterAccess);
        return getterAccess;
    }

    /// <summary>
    /// Gets the accessibility that should be applied at the set level for a property being
    /// generated from the provided EdmMember.
    ///
    /// defaults to empty if no annotation is found or the accessibility is the same as the property level.
    /// </summary>
    public static string ForSetter(EdmMember member)
    {
        if (member == null)
        {
            return null;
        }

        string getterAccess, setterAccess, propertyAccess;
        CalculatePropertyAccessibility(member, out propertyAccess, out getterAccess, out setterAccess);
        return setterAccess;
    }

    /// <summary>
    /// Gets the accessibility that should be applied to a method being generated from the provided EdmFunction.
    ///
    /// defaults to public if no annotation is found.
    /// </summary>
    public static string ForMethod(EdmFunction function)
    {
        if (function == null)
        {
            return null;
        }

        return GetAccessibility(function, METHOD_ACCESS);
    }

    private static void CalculatePropertyAccessibility(MetadataItem item,
        out string propertyAccessibility,
        out string getterAccessibility,
        out string setterAccessibility)
    {
        getterAccessibility = GetAccessibility(item, GETTER_ACCESS);
        int getterRank = AccessibilityRankIdLookup[getterAccessibility];

        setterAccessibility = GetAccessibility(item, SETTER_ACCESS);
        int setterRank = AccessibilityRankIdLookup[setterAccessibility];

        int propertyRank = Math.Max(getterRank, setterRank);
        if (setterRank == propertyRank)
        {
            setterAccessibility = String.Empty;
        }

        if (getterRank == propertyRank)
        {
            getterAccessibility = String.Empty;
        }

        propertyAccessibility = AccessibilityRankIdLookup.Where(v => v.Value == propertyRank).Select(v => v.Key).Single();
    }

    private static string GetAccessibility(MetadataItem item, string name)
    {
        string accessibility;
        if (MetadataTools.TryGetStringMetadataPropertySetting(item, name, out accessibility))
        {
            return TranslateUserAccessibilityToCSharpAccessibility(accessibility);
        }

        return "public";
    }

    private static string TranslateUserAccessibilityToCSharpAccessibility(string userAccessibility)
    {
        if (userAccessibility == ACCESS_PROTECTED)
        {
            return "protected";
        }
        else if (userAccessibility == ACCESS_INTERNAL)
        {
            return "internal";
        }
        else if (userAccessibility == ACCESS_PRIVATE)
        {
            return "private";
        }
        else
        {
            // default to public
            return "public";
        }
    }
}

/// <summary>
/// Responsible for creating source code regions in code when the loop inside
/// actually produces something.
/// </summary>
public class CodeRegion
{
    private const int STANDARD_INDENT_LENGTH = 4;

    private readonly DynamicTextTransformation _textTransformation;
    private int _beforeRegionLength;
    private int _emptyRegionLength;
    private int _regionIndentLevel = -1;

    /// <summary>
    /// Initializes an CodeRegion instance with the
    /// TextTransformation (T4 generated class) that is currently running
    /// </summary>
    public CodeRegion(object textTransformation)
    {
        if (textTransformation == null)
        {
            throw new ArgumentNullException("textTransformation");
        }

        _textTransformation = DynamicTextTransformation.Create(textTransformation);
    }

    /// <summary>
    /// Initializes an CodeRegion instance with the
    /// TextTransformation (T4 generated class) that is currently running,
    /// and the indent level to start the first region at.
    /// </summary>
    public CodeRegion(object textTransformation, int firstIndentLevel)
        : this(textTransformation)
    {
        if (firstIndentLevel < 0)
        {
            throw new ArgumentException("firstIndentLevel");
        }

        _regionIndentLevel = firstIndentLevel - 1;
    }

    /// <summary>
    /// Starts the begining of a region
    /// </summary>
    public void Begin(string regionName)
    {
        if (regionName == null)
        {
            throw new ArgumentNullException("regionName");
        }

        Begin(regionName, 1);
    }

    /// <summary>
    /// Start the begining of a region, indented
    /// the numbers of levels specified
    /// </summary>
    public void Begin(string regionName, int levelsToIncreaseIndent)
    {
        if (regionName == null)
        {
            throw new ArgumentNullException("regionName");
        }

        _beforeRegionLength = _textTransformation.GenerationEnvironment.Length;
        _regionIndentLevel += levelsToIncreaseIndent;
        _textTransformation.Write(GetIndent(_regionIndentLevel));
        _textTransformation.WriteLine("#region " + regionName);
        _emptyRegionLength = _textTransformation.GenerationEnvironment.Length;
    }

    /// <summary>
    /// Ends a region, or totaly removes it if nothing
    /// was generted since the begining of the region.
    /// </summary>
    public void End()
    {
        End(1);
    }

    /// <summary>
    /// Ends a region, or totaly removes it if nothing
    /// was generted since the begining of the region, also outdents
    /// the number of levels specified.
    /// </summary>
    public void End(int levelsToDecrease)
    {
        int indentLevel = _regionIndentLevel;
        _regionIndentLevel -= levelsToDecrease;

        if (_emptyRegionLength == _textTransformation.GenerationEnvironment.Length)
            _textTransformation.GenerationEnvironment.Length = _beforeRegionLength;
        else
        {
            _textTransformation.WriteLine(String.Empty);
            _textTransformation.Write(GetIndent(indentLevel));
            _textTransformation.WriteLine("#endregion");
            _textTransformation.WriteLine(String.Empty);
        }
    }

    /// <summary>
    /// Gets the current indent level that the next end region statement will be written
    /// at
    /// </summary>
    public int CurrentIndentLevel { get { return _regionIndentLevel; } }

    /// <summary>
    /// Get a string of spaces equivelent to the number of indents
    /// desired.
    /// </summary>
    public static string GetIndent(int indentLevel)
    {
        if (indentLevel < 0)
        {
            throw new ArgumentException("indentLevel");
        }

        return String.Empty.PadLeft(indentLevel * STANDARD_INDENT_LENGTH);
    }
}


/// <summary>
/// Responsible for collecting together the actual method parameters
/// and the parameters that need to be sent to the Execute method.
/// </summary>
public class FunctionImportParameter
{
    public FunctionParameter Source { get; set; }
    public string RawFunctionParameterName { get; set; }
    public string FunctionParameterName { get; set; }
    public string FunctionParameterType { get; set; }
    public string LocalVariableName { get; set; }
    public string RawClrTypeName { get; set; }
    public string ExecuteParameterName { get; set; }
    public string EsqlParameterName { get; set; }
    public bool NeedsLocalVariable { get; set; }
    public bool IsNullableOfT { get; set; }


    /// <summary>
    /// Creates a set of FunctionImportParameter objects from the parameters passed in.
    /// </summary>
    public static IEnumerable<FunctionImportParameter> Create(IEnumerable<FunctionParameter> parameters, CodeGenerationTools code, MetadataTools ef)
    {
        if (parameters == null)
        {
            throw new ArgumentNullException("parameters");
        }

        if (code == null)
        {
            throw new ArgumentNullException("code");
        }

        if (ef == null)
        {
            throw new ArgumentNullException("ef");
        }

        UniqueIdentifierService unique = new UniqueIdentifierService();
        List<FunctionImportParameter> importParameters = new List<FunctionImportParameter>();
        foreach (FunctionParameter parameter in parameters)
        {
            FunctionImportParameter importParameter = new FunctionImportParameter();
            importParameter.Source = parameter;
            importParameter.RawFunctionParameterName = unique.AdjustIdentifier(code.CamelCase(parameter.Name));
            importParameter.FunctionParameterName = code.Escape(importParameter.RawFunctionParameterName);
            if (parameter.Mode == ParameterMode.In)
            {
                TypeUsage typeUsage = parameter.TypeUsage;
                importParameter.NeedsLocalVariable = true;
                importParameter.FunctionParameterType = code.GetTypeName(typeUsage);
                importParameter.EsqlParameterName = parameter.Name;
                Type clrType = ef.UnderlyingClrType(parameter.TypeUsage.EdmType);
                importParameter.RawClrTypeName = typeUsage.EdmType is EnumType ? code.GetTypeName(typeUsage.EdmType) : code.Escape(clrType);
                importParameter.IsNullableOfT = clrType.IsValueType;
            }
            else
            {
                importParameter.NeedsLocalVariable = false;
                importParameter.FunctionParameterType = "ObjectParameter";
                importParameter.ExecuteParameterName = importParameter.FunctionParameterName;
            }
            importParameters.Add(importParameter);
        }

        // we save the local parameter uniquification for a second pass to make the visible parameters
        // as pretty and sensible as possible
        for (int i = 0; i < importParameters.Count; i++)
        {
            FunctionImportParameter importParameter = importParameters[i];
            if (importParameter.NeedsLocalVariable)
            {
                importParameter.LocalVariableName = unique.AdjustIdentifier(importParameter.RawFunctionParameterName + "Parameter");
                importParameter.ExecuteParameterName = importParameter.LocalVariableName;
            }
        }

        return importParameters;
    }

    //
    // Class to create unique variables within the same scope
    //
    private sealed class UniqueIdentifierService
    {
        private readonly HashSet<string> _knownIdentifiers;

        public UniqueIdentifierService()
        {
            _knownIdentifiers = new HashSet<string>(StringComparer.Ordinal);
        }

        /// <summary>
        /// Given an identifier, makes it unique within the scope by adding
        /// a suffix (1, 2, 3, ...), and returns the adjusted identifier.
        /// </summary>
        public string AdjustIdentifier(string identifier)
        {
            // find a unique name by adding suffix as necessary
            int numberOfConflicts = 0;
            string adjustedIdentifier = identifier;

            while (!_knownIdentifiers.Add(adjustedIdentifier))
            {
                ++numberOfConflicts;
                adjustedIdentifier = identifier + numberOfConflicts.ToString(CultureInfo.InvariantCulture);
            }

            return adjustedIdentifier;
        }
    }
}

/// <summary>
/// Responsible for marking the various sections of the generation,
/// so they can be split up into separate files
/// </summary>
public class EntityFrameworkTemplateFileManager
{
    /// <summary>
    /// Creates the VsEntityFrameworkTemplateFileManager if VS is detected, otherwise
    /// creates the file system version.
    /// </summary>
    public static EntityFrameworkTemplateFileManager Create(object textTransformation)
    {
        DynamicTextTransformation transformation = DynamicTextTransformation.Create(textTransformation);
        IDynamicHost host = transformation.Host;

#if !PREPROCESSED_TEMPLATE
        var hostServiceProvider = host.AsIServiceProvider();

        if (hostServiceProvider != null)
        {
            EnvDTE.DTE dte = (EnvDTE.DTE) hostServiceProvider.GetService(typeof(EnvDTE.DTE));

            if (dte != null)
            {
                return new VsEntityFrameworkTemplateFileManager(transformation);
            }
        }
#endif
        return new EntityFrameworkTemplateFileManager(transformation);
    }

    private sealed class Block
    {
        public String Name;
        public int Start, Length;
    }

    private readonly List<Block> files = new List<Block>();
    private readonly Block footer = new Block();
    private readonly Block header = new Block();
    private readonly DynamicTextTransformation _textTransformation;

    // reference to the GenerationEnvironment StringBuilder on the
    // TextTransformation object
    private readonly StringBuilder _generationEnvironment;

    private Block currentBlock;

    /// <summary>
    /// Initializes an EntityFrameworkTemplateFileManager Instance  with the
    /// TextTransformation (T4 generated class) that is currently running
    /// </summary>
    private EntityFrameworkTemplateFileManager(object textTransformation)
    {
        if (textTransformation == null)
        {
            throw new ArgumentNullException("textTransformation");
        }

        _textTransformation = DynamicTextTransformation.Create(textTransformation);
        _generationEnvironment = _textTransformation.GenerationEnvironment;
    }

    /// <summary>
    /// Marks the end of the last file if there was one, and starts a new
    /// and marks this point in generation as a new file.
    /// </summary>
    public void StartNewFile(string name)
    {
        if (name == null)
        {
            throw new ArgumentNullException("name");
        }

        CurrentBlock = new Block { Name = name };
    }

    public void StartFooter()
    {
        CurrentBlock = footer;
    }

    public void StartHeader()
    {
        CurrentBlock = header;
    }

    public void EndBlock()
    {
        if (CurrentBlock == null)
        {
            return;
        }

        CurrentBlock.Length = _generationEnvironment.Length - CurrentBlock.Start;

        if (CurrentBlock != header && CurrentBlock != footer)
        {
            files.Add(CurrentBlock);
        }

        currentBlock = null;
    }

    /// <summary>
    /// Produce the template output files.
    /// </summary>
    public virtual IEnumerable<string> Process(bool split = true)
    {
        var generatedFileNames = new List<string>();

        if (split)
        {
            EndBlock();

            var headerText = _generationEnvironment.ToString(header.Start, header.Length);
            var footerText = _generationEnvironment.ToString(footer.Start, footer.Length);
            var outputPath = Path.GetDirectoryName(_textTransformation.Host.TemplateFile);

            files.Reverse();

            foreach (var block in files)
            {
                var fileName = Path.Combine(outputPath, block.Name);
                var content = headerText + _generationEnvironment.ToString(block.Start, block.Length) + footerText;

                generatedFileNames.Add(fileName);
                CreateFile(fileName, content);
                _generationEnvironment.Remove(block.Start, block.Length);
            }
        }

        return generatedFileNames;
    }

    protected virtual void CreateFile(string fileName, string content)
    {
        if (IsFileContentDifferent(fileName, content))
        {
            File.WriteAllText(fileName, content);
        }
    }

    protected bool IsFileContentDifferent(String fileName, string newContent)
    {
        return !(File.Exists(fileName) && File.ReadAllText(fileName) == newContent);
    }

    private Block CurrentBlock
    {
        get { return currentBlock; }
        set
        {
            if (CurrentBlock != null)
            {
                EndBlock();
            }

            if (value != null)
            {
                value.Start = _generationEnvironment.Length;
            }

            currentBlock = value;
        }
    }

#if !PREPROCESSED_TEMPLATE
    private sealed class VsEntityFrameworkTemplateFileManager : EntityFrameworkTemplateFileManager
    {
        private EnvDTE.ProjectItem templateProjectItem;
        private EnvDTE.DTE dte;
        private Action<string> checkOutAction;
        private Action<IEnumerable<string>> projectSyncAction;

        /// <summary>
        /// Creates an instance of the VsEntityFrameworkTemplateFileManager class with the IDynamicHost instance
        /// </summary>
        public VsEntityFrameworkTemplateFileManager(object textTemplating)
            : base(textTemplating)
        {
            var hostServiceProvider = _textTransformation.Host.AsIServiceProvider();
            if (hostServiceProvider == null)
            {
                throw new ArgumentNullException("Could not obtain hostServiceProvider");
            }

            dte = (EnvDTE.DTE) hostServiceProvider.GetService(typeof(EnvDTE.DTE));
            if (dte == null)
            {
                throw new ArgumentNullException("Could not obtain DTE from host");
            }

            templateProjectItem = dte.Solution.FindProjectItem(_textTransformation.Host.TemplateFile);

            checkOutAction = fileName => dte.SourceControl.CheckOutItem(fileName);
            projectSyncAction = keepFileNames => ProjectSync(templateProjectItem, keepFileNames);
        }

        public override IEnumerable<string> Process(bool split)
        {
            if (templateProjectItem.ProjectItems == null)
            {
                return new List<string>();
            }

            var generatedFileNames = base.Process(split);

            projectSyncAction.EndInvoke(projectSyncAction.BeginInvoke(generatedFileNames, null, null));

            return generatedFileNames;
        }

        protected override void CreateFile(string fileName, string content)
        {
            if (IsFileContentDifferent(fileName, content))
            {
                CheckoutFileIfRequired(fileName);
                File.WriteAllText(fileName, content);
            }
        }

        private static void ProjectSync(EnvDTE.ProjectItem templateProjectItem, IEnumerable<string> keepFileNames)
        {
            var keepFileNameSet = new HashSet<string>(keepFileNames);
            var projectFiles = new Dictionary<string, EnvDTE.ProjectItem>();
            var originalOutput = Path.GetFileNameWithoutExtension(templateProjectItem.FileNames[0]);

            foreach (EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems)
            {
                projectFiles.Add(projectItem.FileNames[0], projectItem);
            }

            // Remove unused items from the project
            foreach (var pair in projectFiles)
            {
                if (!keepFileNames.Contains(pair.Key)
                    && !(Path.GetFileNameWithoutExtension(pair.Key) + ".").StartsWith(originalOutput + "."))
                {
                    pair.Value.Delete();
                }
            }

            // Add missing files to the project
            foreach (string fileName in keepFileNameSet)
            {
                if (!projectFiles.ContainsKey(fileName))
                {
                    templateProjectItem.ProjectItems.AddFromFile(fileName);
                }
            }
        }

        private void CheckoutFileIfRequired(string fileName)
        {
            if (dte.SourceControl == null
                || !dte.SourceControl.IsItemUnderSCC(fileName)
                    || dte.SourceControl.IsItemCheckedOut(fileName))
            {
                return;
            }

            // run on worker thread to prevent T4 calling back into VS
            checkOutAction.EndInvoke(checkOutAction.BeginInvoke(fileName, null, null));
        }
    }
#endif
}

/// <summary>
/// Responsible creating an instance that can be passed
/// to helper classes that need to access the TextTransformation
/// members.  It accesses member by name and signature rather than
/// by type.  This is necessary when the
/// template is being used in Preprocessed mode
/// and there is no common known type that can be
/// passed instead
/// </summary>
public class DynamicTextTransformation
{
    private object _instance;
    IDynamicHost _dynamicHost;

    private readonly MethodInfo _write;
    private readonly MethodInfo _writeLine;
    private readonly PropertyInfo _generationEnvironment;
    private readonly PropertyInfo _errors;
    private readonly PropertyInfo _host;

    /// <summary>
    /// Creates an instance of the DynamicTextTransformation class around the passed in
    /// TextTransformation shapped instance passed in, or if the passed in instance
    /// already is a DynamicTextTransformation, it casts it and sends it back.
    /// </summary>
    public static DynamicTextTransformation Create(object instance)
    {
        if (instance == null)
        {
            throw new ArgumentNullException("instance");
        }

        DynamicTextTransformation textTransformation = instance as DynamicTextTransformation;
        if (textTransformation != null)
        {
            return textTransformation;
        }

        return new DynamicTextTransformation(instance);
    }

    private DynamicTextTransformation(object instance)
    {
        _instance = instance;
        Type type = _instance.GetType();
        _write = type.GetMethod("Write", new Type[] { typeof(string) });
        _writeLine = type.GetMethod("WriteLine", new Type[] { typeof(string) });
        _generationEnvironment = type.GetProperty("GenerationEnvironment", BindingFlags.Instance | BindingFlags.NonPublic);
        _host = type.GetProperty("Host");
        _errors = type.GetProperty("Errors");
    }

    /// <summary>
    /// Gets the value of the wrapped TextTranformation instance's GenerationEnvironment property
    /// </summary>
    public StringBuilder GenerationEnvironment { get { return (StringBuilder)_generationEnvironment.GetValue(_instance, null); } }

    /// <summary>
    /// Gets the value of the wrapped TextTranformation instance's Errors property
    /// </summary>
    public System.CodeDom.Compiler.CompilerErrorCollection Errors { get { return (System.CodeDom.Compiler.CompilerErrorCollection)_errors.GetValue(_instance, null); } }

    /// <summary>
    /// Calls the wrapped TextTranformation instance's Write method.
    /// </summary>
    public void Write(string text)
    {
        _write.Invoke(_instance, new object[] { text });
    }

    /// <summary>
    /// Calls the wrapped TextTranformation instance's WriteLine method.
    /// </summary>
    public void WriteLine(string text)
    {
        _writeLine.Invoke(_instance, new object[] { text });
    }

    /// <summary>
    /// Gets the value of the wrapped TextTranformation instance's Host property
    /// if available (shows up when hostspecific is set to true in the template directive) and returns
    /// the appropriate implementation of IDynamicHost
    /// </summary>
    public IDynamicHost Host
    {
        get
        {
            if (_dynamicHost == null)
            {
                if(_host == null)
                {
                    _dynamicHost = new NullHost();
                }
                else
                {
                    _dynamicHost = new DynamicHost(_host.GetValue(_instance, null));
                }
            }
            return _dynamicHost;
        }
    }
}


/// <summary>
/// Reponsible for abstracting the use of Host between times
/// when it is available and not
/// </summary>
public interface IDynamicHost
{
    /// <summary>
    /// An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue
    /// </summary>
    string ResolveParameterValue(string id, string name, string otherName);

    /// <summary>
    /// An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath
    /// </summary>
    string ResolvePath(string path);

    /// <summary>
    /// An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile
    /// </summary>
    string TemplateFile { get; }

    /// <summary>
    /// Returns the Host instance cast as an IServiceProvider
    /// </summary>
    IServiceProvider AsIServiceProvider();
}

/// <summary>
/// Reponsible for implementing the IDynamicHost as a dynamic
/// shape wrapper over the Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost interface
/// rather than type dependent wrapper.  We don't use the
/// interface type so that the code can be run in preprocessed mode
/// on a .net framework only installed machine.
/// </summary>
public class DynamicHost : IDynamicHost
{
    private readonly object _instance;
    private readonly MethodInfo _resolveParameterValue;
    private readonly MethodInfo _resolvePath;
    private readonly PropertyInfo _templateFile;

    /// <summary>
    /// Creates an instance of the DynamicHost class around the passed in
    /// Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost shapped instance passed in.
    /// </summary>
    public DynamicHost(object instance)
    {
        _instance = instance;
        Type type = _instance.GetType();
        _resolveParameterValue = type.GetMethod("ResolveParameterValue", new Type[] { typeof(string), typeof(string), typeof(string) });
        _resolvePath = type.GetMethod("ResolvePath", new Type[] { typeof(string) });
        _templateFile = type.GetProperty("TemplateFile");

    }

    /// <summary>
    /// A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue
    /// </summary>
    public string ResolveParameterValue(string id, string name, string otherName)
    {
        return (string)_resolveParameterValue.Invoke(_instance, new object[] { id, name, otherName });
    }

    /// <summary>
    /// A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath
    /// </summary>
    public string ResolvePath(string path)
    {
        return (string)_resolvePath.Invoke(_instance, new object[] { path });
    }

    /// <summary>
    /// A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile
    /// </summary>
    public string TemplateFile
    {
        get
        {
            return (string)_templateFile.GetValue(_instance, null);
        }
    }

    /// <summary>
    /// Returns the Host instance cast as an IServiceProvider
    /// </summary>
    public IServiceProvider AsIServiceProvider()
    {
        return _instance as IServiceProvider;
    }
}

/// <summary>
/// Reponsible for implementing the IDynamicHost when the
/// Host property is not available on the TextTemplating type. The Host
/// property only exists when the hostspecific attribute of the template
/// directive is set to true.
/// </summary>
public class NullHost : IDynamicHost
{
    /// <summary>
    /// An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue
    /// that simply retuns null.
    /// </summary>
    public string ResolveParameterValue(string id, string name, string otherName)
    {
        return null;
    }

    /// <summary>
    /// An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath
    /// that simply retuns the path passed in.
    /// </summary>
    public string ResolvePath(string path)
    {
        return path;
    }

    /// <summary>
    /// An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile
    /// that returns null.
    /// </summary>
    public string TemplateFile
    {
        get
        {
            return null;
        }
    }

    /// <summary>
    /// Returns null.
    /// </summary>
    public IServiceProvider AsIServiceProvider()
    {
        return null;
    }
}

/// <summary>
/// Responsible for encapsulating the constants defined in Metadata
/// </summary>
public static class MetadataConstants
{
    public const string CSDL_EXTENSION = ".csdl";

    public const string CSDL_EDMX_SECTION_NAME = "ConceptualModels";
    public const string CSDL_ROOT_ELEMENT_NAME = "Schema";
    public const string EDM_ANNOTATION_09_02 = "http://schemas.microsoft.com/ado/2009/02/edm/annotation";

    public const string SSDL_EXTENSION = ".ssdl";

    public const string SSDL_EDMX_SECTION_NAME = "StorageModels";
    public const string SSDL_ROOT_ELEMENT_NAME = "Schema";

    public const string MSL_EXTENSION = ".msl";

    public const string MSL_EDMX_SECTION_NAME = "Mappings";
    public const string MSL_ROOT_ELEMENT_NAME = "Mapping";

    public const string TT_TEMPLATE_NAME = "TemplateName";
    public const string TT_TEMPLATE_VERSION = "TemplateVersion";
    public const string TT_MINIMUM_ENTITY_FRAMEWORK_VERSION = "MinimumEntityFrameworkVersion";

    public const string DEFAULT_TEMPLATE_VERSION = "4.0";

    public static readonly SchemaConstants V1_SCHEMA_CONSTANTS = new SchemaConstants(
        "http://schemas.microsoft.com/ado/2007/06/edmx",
        "http://schemas.microsoft.com/ado/2006/04/edm",
        "http://schemas.microsoft.com/ado/2006/04/edm/ssdl",
        "urn:schemas-microsoft-com:windows:storage:mapping:CS",
        new Version("3.5"));

    public static readonly SchemaConstants V2_SCHEMA_CONSTANTS = new SchemaConstants(
        "http://schemas.microsoft.com/ado/2008/10/edmx",
        "http://schemas.microsoft.com/ado/2008/09/edm",
        "http://schemas.microsoft.com/ado/2009/02/edm/ssdl",
        "http://schemas.microsoft.com/ado/2008/09/mapping/cs",
        new Version("4.0"));

    public static readonly SchemaConstants V3_SCHEMA_CONSTANTS = new SchemaConstants(
        "http://schemas.microsoft.com/ado/2009/11/edmx",
        "http://schemas.microsoft.com/ado/2009/11/edm",
        "http://schemas.microsoft.com/ado/2009/11/edm/ssdl",
        "http://schemas.microsoft.com/ado/2009/11/mapping/cs",
        new Version("5.0"));
}

public struct SchemaConstants
{
    public SchemaConstants(string edmxNamespace, string csdlNamespace, string ssdlNamespace, string mslNamespace, Version minimumTemplateVersion) : this()
    {
        EdmxNamespace = edmxNamespace;
        CsdlNamespace = csdlNamespace;
        SsdlNamespace = ssdlNamespace;
        MslNamespace = mslNamespace;
        MinimumTemplateVersion = minimumTemplateVersion;
    }

    public string EdmxNamespace { get; private set; }
    public string CsdlNamespace { get; private set; }
    public string SsdlNamespace { get; private set; }
    public string MslNamespace { get; private set; }
    public Version MinimumTemplateVersion { get; private set; }
}


    }


    #region Base class
    /// <summary>
    /// Base class for this transformation
    /// </summary>
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "11.0.0.0")]
    public class CSharpCodeGenTemplateBase
    {
        #region Fields
        private global::System.Text.StringBuilder generationEnvironmentField;
        private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField;
        private global::System.Collections.Generic.List<int> indentLengthsField;
        private string currentIndentField = "";
        private bool endsWithNewline;
        private global::System.Collections.Generic.IDictionary<string, object> sessionField;
        #endregion
        #region Properties
        /// <summary>
        /// The string builder that generation-time code is using to assemble generated output
        /// </summary>
        protected System.Text.StringBuilder GenerationEnvironment
        {
            get
            {
                if ((this.generationEnvironmentField == null))
                {
                    this.generationEnvironmentField = new global::System.Text.StringBuilder();
                }
                return this.generationEnvironmentField;
            }
            set
            {
                this.generationEnvironmentField = value;
            }
        }
        /// <summary>
        /// The error collection for the generation process
        /// </summary>
        public System.CodeDom.Compiler.CompilerErrorCollection Errors
        {
            get
            {
                if ((this.errorsField == null))
                {
                    this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection();
                }
                return this.errorsField;
            }
        }
        /// <summary>
        /// A list of the lengths of each indent that was added with PushIndent
        /// </summary>
        private System.Collections.Generic.List<int> indentLengths
        {
            get
            {
                if ((this.indentLengthsField == null))
                {
                    this.indentLengthsField = new global::System.Collections.Generic.List<int>();
                }
                return this.indentLengthsField;
            }
        }
        /// <summary>
        /// Gets the current indent we use when adding lines to the output
        /// </summary>
        public string CurrentIndent
        {
            get
            {
                return this.currentIndentField;
            }
        }
        /// <summary>
        /// Current transformation session
        /// </summary>
        public virtual global::System.Collections.Generic.IDictionary<string, object> Session
        {
            get
            {
                return this.sessionField;
            }
            set
            {
                this.sessionField = value;
            }
        }
        #endregion
        #region Transform-time helpers
        /// <summary>
        /// Write text directly into the generated output
        /// </summary>
        public void Write(string textToAppend)
        {
            if (string.IsNullOrEmpty(textToAppend))
            {
                return;
            }
            // If we're starting off, or if the previous text ended with a newline,
            // we have to append the current indent first.
            if (((this.GenerationEnvironment.Length == 0) 
                        || this.endsWithNewline))
            {
                this.GenerationEnvironment.Append(this.currentIndentField);
                this.endsWithNewline = false;
            }
            // Check if the current text ends with a newline
            if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
            {
                this.endsWithNewline = true;
            }
            // This is an optimization. If the current indent is "", then we don't have to do any
            // of the more complex stuff further down.
            if ((this.currentIndentField.Length == 0))
            {
                this.GenerationEnvironment.Append(textToAppend);
                return;
            }
            // Everywhere there is a newline in the text, add an indent after it
            textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
            // If the text ends with a newline, then we should strip off the indent added at the very end
            // because the appropriate indent will be added when the next time Write() is called
            if (this.endsWithNewline)
            {
                this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
            }
            else
            {
                this.GenerationEnvironment.Append(textToAppend);
            }
        }
        /// <summary>
        /// Write text directly into the generated output
        /// </summary>
        public void WriteLine(string textToAppend)
        {
            this.Write(textToAppend);
            this.GenerationEnvironment.AppendLine();
            this.endsWithNewline = true;
        }
        /// <summary>
        /// Write formatted text directly into the generated output
        /// </summary>
        public void Write(string format, params object[] args)
        {
            this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
        }
        /// <summary>
        /// Write formatted text directly into the generated output
        /// </summary>
        public void WriteLine(string format, params object[] args)
        {
            this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
        }
        /// <summary>
        /// Raise an error
        /// </summary>
        public void Error(string message)
        {
            System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
            error.ErrorText = message;
            this.Errors.Add(error);
        }
        /// <summary>
        /// Raise a warning
        /// </summary>
        public void Warning(string message)
        {
            System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
            error.ErrorText = message;
            error.IsWarning = true;
            this.Errors.Add(error);
        }
        /// <summary>
        /// Increase the indent
        /// </summary>
        public void PushIndent(string indent)
        {
            if ((indent == null))
            {
                throw new global::System.ArgumentNullException("indent");
            }
            this.currentIndentField = (this.currentIndentField + indent);
            this.indentLengths.Add(indent.Length);
        }
        /// <summary>
        /// Remove the last indent that was added with PushIndent
        /// </summary>
        public string PopIndent()
        {
            string returnValue = "";
            if ((this.indentLengths.Count > 0))
            {
                int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
                this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
                if ((indentLength > 0))
                {
                    returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
                    this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
                }
            }
            return returnValue;
        }
        /// <summary>
        /// Remove any indentation
        /// </summary>
        public void ClearIndent()
        {
            this.indentLengths.Clear();
            this.currentIndentField = "";
        }
        #endregion
        #region ToString Helpers
        /// <summary>
        /// Utility class to produce culture-oriented representation of an object as a string.
        /// </summary>
        public class ToStringInstanceHelper
        {
            private System.IFormatProvider formatProviderField  = global::System.Globalization.CultureInfo.InvariantCulture;
            /// <summary>
            /// Gets or sets format provider to be used by ToStringWithCulture method.
            /// </summary>
            public System.IFormatProvider FormatProvider
            {
                get
                {
                    return this.formatProviderField ;
                }
                set
                {
                    if ((value != null))
                    {
                        this.formatProviderField  = value;
                    }
                }
            }
            /// <summary>
            /// This is called from the compile/run appdomain to convert objects within an expression block to a string
            /// </summary>
            public string ToStringWithCulture(object objectToConvert)
            {
                if ((objectToConvert == null))
                {
                    throw new global::System.ArgumentNullException("objectToConvert");
                }
                System.Type t = objectToConvert.GetType();
                System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
                            typeof(System.IFormatProvider)});
                if ((method == null))
                {
                    return objectToConvert.ToString();
                }
                else
                {
                    return ((string)(method.Invoke(objectToConvert, new object[] {
                                this.formatProviderField })));
                }
            }
        }
        private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper();
        /// <summary>
        /// Helper to produce culture-oriented representation of an object as a string
        /// </summary>
        public ToStringInstanceHelper ToStringHelper
        {
            get
            {
                return this.toStringHelperField;
            }
        }
        #endregion
    }
    #endregion
}
��// ------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version: 11.0.0.0
//  
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace TemplateCodeGenerators
{
    using System;
    using System.Linq;
    using System.IO;
    using System.Collections.Generic;
    using System.Data.Objects;
    using System.Data.Objects.DataClasses;
    using System.Xml;
    using System.Xml.Linq;
    using System.Globalization;
    using System.Reflection;
    using System.Data.Metadata.Edm;
    using System.Data.Mapping;
    using System.Data.Entity.Design;
    using System.CodeDom;
    using System.CodeDom.Compiler;
    using Microsoft.CSharp;
    using System.Text;
    
    /// <summary>
    /// Class to produce the template output
    /// </summary>

    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "11.0.0.0")]
    public partial class CSharpCodeGenTemplateV50 : CSharpCodeGenTemplateV50Base
    {
        /// <summary>
        /// Create the template output
        /// </summary>
        public virtual string TransformText()
        {


// 
// 
// 
//
//  
//  
//  
//  
//  
//  
//  
//  
//
//  
//  
//  
//  





DefineMetadata();

UserSettings userSettings =
    new UserSettings
    {
        SourceCsdlPath = @"$edmxInputFile$",
        ReferenceCsdlPaths = new string[] {},
        FullyQualifySystemTypes = true,
        CreateContextAddToMethods = true,
        CamelCaseFields = false,
    };

ApplyUserSettings(userSettings);
if(Errors.HasErrors)
{
    return String.Empty;
}

MetadataLoader loader = new MetadataLoader(this);
MetadataTools ef = new MetadataTools(this);
CodeRegion region = new CodeRegion(this);
CodeGenerationTools code = new CodeGenerationTools(this){FullyQualifySystemTypes = userSettings.FullyQualifySystemTypes, CamelCaseFields = userSettings.CamelCaseFields};

ItemCollection = loader.CreateEdmItemCollection(SourceCsdlPath, ReferenceCsdlPaths.ToArray());
ModelNamespace = loader.GetModelNamespace(SourceCsdlPath);
string namespaceName = GetNamespaceName(code);
UpdateObjectNamespaceMap(namespaceName);


            this.Write("//------------------------------------------------------------------------------\r" +
                    "\n// <auto-generated>\r\n// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine1")));


            this.Write("\r\n//\r\n// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine2")));


            this.Write("\r\n// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine3")));


            this.Write(@"
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.ComponentModel;
using System.Data.EntityClient;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml.Serialization;

[assembly: EdmSchemaAttribute()]
");


    ////////
    //////// 
    ////////
    region.Begin(CodeGenerationTools.GetResourceString("Template_RegionRelationships"));
    bool first = true;
    foreach (AssociationType association in GetSourceSchemaTypes<AssociationType>())
    {
        if (first)
        {
            WriteLine(string.Empty);
            first = false;
        }


            this.Write("[assembly: EdmRelationshipAttribute(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(association.NamespaceName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(association.Name));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(EndName(association, 0)));


            this.Write("\", ");

            this.Write(this.ToStringHelper.ToStringWithCulture(EndMultiplicity(association, 0, code)));


            this.Write(", typeof(");

            this.Write(this.ToStringHelper.ToStringWithCulture(EscapeEndTypeName(association, 0, code)));


            this.Write("), \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(EndName(association, 1)));


            this.Write("\", ");

            this.Write(this.ToStringHelper.ToStringWithCulture(EndMultiplicity(association, 1, code)));


            this.Write(", typeof(");

            this.Write(this.ToStringHelper.ToStringWithCulture(EscapeEndTypeName(association, 1, code)));


            this.Write(")");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.StringBefore(", ", association.IsForeignKey ? "true" : null)));


            this.Write(")]\r\n");


    }
    region.End();

    if (!String.IsNullOrEmpty(namespaceName))
    {


            this.Write("namespace ");

            this.Write(this.ToStringHelper.ToStringWithCulture(namespaceName));


            this.Write("\r\n{\r\n");


        PushIndent(CodeRegion.GetIndent(1));
    }

    ////////
    //////// 
    ////////

    region.Begin(CodeGenerationTools.GetResourceString("Template_RegionContexts"));
    foreach (EntityContainer container in GetSourceSchemaTypes<EntityContainer>())
    {


            this.Write("\r\n/// <summary>\r\n/// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(container)));


            this.Write("\r\n/// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(container, region.CurrentIndentLevel)));


            this.Write("\r\n");

            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForType(container)));


            this.Write(" partial class ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(container)));


            this.Write(" : ObjectContext\r\n{\r\n    #region ");

            this.Write(this.ToStringHelper.ToStringWithCulture(CodeGenerationTools.GetResourceString("Template_RegionConstructors")));


            this.Write("\r\n\r\n    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_ContextDefaultCtorComment"), container.Name, container.Name)));


            this.Write("\r\n    /// </summary>\r\n    public ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(container)));


            this.Write("() : base(\"name=");

            this.Write(this.ToStringHelper.ToStringWithCulture(container.Name));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(container.Name));


            this.Write("\")\r\n    {\r\n");


        WriteLazyLoadingEnabled(container);


            this.Write("        OnContextCreated();\r\n    }\r\n\r\n    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_ContextCommonCtorComment"), container.Name)));


            this.Write("\r\n    /// </summary>\r\n    public ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(container)));


            this.Write("(string connectionString) : base(connectionString, \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(container.Name));


            this.Write("\")\r\n    {\r\n");


        WriteLazyLoadingEnabled(container);


            this.Write("        OnContextCreated();\r\n    }\r\n\r\n    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_ContextCommonCtorComment"), container.Name)));


            this.Write("\r\n    /// </summary>\r\n    public ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(container)));


            this.Write("(EntityConnection connection) : base(connection, \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(container.Name));


            this.Write("\")\r\n    {\r\n");


        WriteLazyLoadingEnabled(container);


            this.Write("        OnContextCreated();\r\n    }\r\n\r\n    #endregion\r\n\r\n    #region ");

            this.Write(this.ToStringHelper.ToStringWithCulture(CodeGenerationTools.GetResourceString("Template_RegionPartialMethods")));


            this.Write("\r\n\r\n    partial void OnContextCreated();\r\n\r\n    #endregion\r\n\r\n");


        ////////
        //////// 
        ////////
        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionObjectSetProperties"));
        foreach (EntitySet set in container.BaseEntitySets.OfType<EntitySet>())
        {
            VerifyEntityTypeAndSetAccessibilityCompatability(set);


            this.Write("\r\n    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(set)));


            this.Write("\r\n    /// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(set, region.CurrentIndentLevel)));


            this.Write("\r\n    ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(set))));



            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForReadOnlyProperty(set)));


            this.Write(" ObjectSet<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(set.ElementType, code)));


            this.Write("> ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(set)));


            this.Write("\r\n    {\r\n        get\r\n        {\r\n            if ((");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(set)));


            this.Write(" == null))\r\n            {\r\n                ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(set)));


            this.Write(" = base.CreateObjectSet<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(set.ElementType, code)));


            this.Write(">(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(set.Name));


            this.Write("\");\r\n            }\r\n            return ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(set)));


            this.Write(";\r\n        }\r\n    }\r\n    private ObjectSet<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(set.ElementType, code)));


            this.Write("> ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(set)));


            this.Write(";\r\n");


        }
        region.End();

        ////////
        //////// 
        ////////
        //////// 
        //////// 
        ////////
        //////// 
        //////// 
        //////// 
        ////////
        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionAddToMethods"));
        IEnumerable<EntitySet> addToMethods = CreateContextAddToMethods.Value ? container.BaseEntitySets.OfType<EntitySet>() : Enumerable.Empty<EntitySet>();
        foreach (EntitySet set in addToMethods)
        {
            string parameterName = code.Escape(FixParameterName(set.ElementType.Name, code));


            this.Write("\r\n    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_GenCommentAddToMethodCs"), set.Name)));


            this.Write("\r\n    /// </summary>\r\n    ");

            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForType(set.ElementType)));


            this.Write(" void AddTo");

            this.Write(this.ToStringHelper.ToStringWithCulture(set.Name));


            this.Write("(");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(set.ElementType, code)));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameterName));


            this.Write(")\r\n    {\r\n        base.AddObject(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(set.Name));


            this.Write("\", ");

            this.Write(this.ToStringHelper.ToStringWithCulture(parameterName));


            this.Write(");\r\n    }\r\n");


        }
        region.End();

        ////////
        //////// 
        ////////
        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionFunctionImports"));
        foreach (EdmFunction edmFunction in container.FunctionImports)
        {

            IEnumerable<FunctionImportParameter> parameters = FunctionImportParameter.Create(edmFunction.Parameters, code, ef);
            string paramList = string.Join(", ", parameters.Select(p => p.FunctionParameterType + " " + p.FunctionParameterName).ToArray());
            TypeUsage returnType = edmFunction.ReturnParameters.Count == 0 ? null : ef.GetElementType(edmFunction.ReturnParameters[0].TypeUsage);
            if (edmFunction.IsComposableAttribute)
            {


            this.Write("\r\n    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(edmFunction)));


            this.Write("\r\n    /// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel)));



            this.Write(this.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(p => new Tuple<string, string>(p.RawFunctionParameterName, SummaryComment(p.Source))), region.CurrentIndentLevel)));


            this.Write("\r\n    [EdmFunction(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(edmFunction.NamespaceName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(edmFunction.Name));


            this.Write("\")]\r\n    ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(edmFunction))));



            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForMethod(edmFunction)));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture("IQueryable<" + MultiSchemaEscape(returnType, code) + ">"));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(edmFunction)));


            this.Write("(");

            this.Write(this.ToStringHelper.ToStringWithCulture(paramList));


            this.Write(")\r\n    {\r\n");


                WriteFunctionParameters(parameters);


            this.Write("        return base.CreateQuery<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(returnType, code)));


            this.Write(">(\"[");

            this.Write(this.ToStringHelper.ToStringWithCulture(edmFunction.NamespaceName));


            this.Write("].[");

            this.Write(this.ToStringHelper.ToStringWithCulture(edmFunction.Name));


            this.Write("](");

            this.Write(this.ToStringHelper.ToStringWithCulture(string.Join(", ", parameters.Select(p => "@" + p.EsqlParameterName).ToArray())));


            this.Write(")\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()))));


            this.Write(");\r\n    }\r\n");


            }
            else
            {


            this.Write("\r\n    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(edmFunction)));


            this.Write("\r\n    /// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel)));



            this.Write(this.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(p => new Tuple<string, string>(p.RawFunctionParameterName, SummaryComment(p.Source))), region.CurrentIndentLevel)));


            this.Write("\r\n    ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(edmFunction))));



            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForMethod(edmFunction)));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(returnType == null ? "int" : "ObjectResult<" + MultiSchemaEscape(returnType, code) + ">"));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(edmFunction)));


            this.Write("(");

            this.Write(this.ToStringHelper.ToStringWithCulture(paramList));


            this.Write(")\r\n    {\r\n");


                WriteFunctionParameters(parameters);


            this.Write("        return base.ExecuteFunction");

            this.Write(this.ToStringHelper.ToStringWithCulture(returnType == null ? "" : "<" + MultiSchemaEscape(returnType, code) + ">"));


            this.Write("(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(edmFunction.Name));


            this.Write("\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()))));


            this.Write(");\r\n    }\r\n");


                if(returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType)
                {


            this.Write("    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(edmFunction)));


            this.Write("\r\n    /// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel)));


            this.Write("\r\n    /// <param name=\"mergeOption\"></param>");

            this.Write(this.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(p => new Tuple<string, string>(p.RawFunctionParameterName, SummaryComment(p.Source))), region.CurrentIndentLevel)));


            this.Write("\r\n    ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(edmFunction))));



            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForMethod(edmFunction)));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(returnType == null ? "int" : "ObjectResult<" + MultiSchemaEscape(returnType, code) + ">"));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(edmFunction)));


            this.Write("(");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.StringAfter(paramList, ", ")));


            this.Write("MergeOption mergeOption)\r\n    {\r\n");


                    WriteFunctionParameters(parameters);


            this.Write("        return base.");

            this.Write(this.ToStringHelper.ToStringWithCulture(returnType == null ? "ExecuteFunction" : "ExecuteFunction<" + MultiSchemaEscape(returnType, code) + ">"));


            this.Write("(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(edmFunction.Name));


            this.Write("\", mergeOption");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()))));


            this.Write(");\r\n    }\r\n");


                }
            }
        }
        region.End();


            this.Write("}\r\n");


    }
    region.End();

    ////////
    //////// 
    ////////
    region.Begin(CodeGenerationTools.GetResourceString("Template_RegionEntities"));
    foreach (EntityType entity in GetSourceSchemaTypes<EntityType>().OrderBy(e => e.Name))
    {


            this.Write("\r\n/// <summary>\r\n/// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(entity)));


            this.Write("\r\n/// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(entity, region.CurrentIndentLevel)));


            this.Write("\r\n[EdmEntityTypeAttribute(NamespaceName=\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(entity.NamespaceName));


            this.Write("\", Name=\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(entity.Name));


            this.Write("\")]\r\n[Serializable()]\r\n[DataContractAttribute(IsReference=true)]\r\n");


        foreach (EntityType subType in ItemCollection.GetItems<EntityType>().Where(b => b.BaseType == entity))
        {


            this.Write("[KnownTypeAttribute(typeof(");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(subType, code)));


            this.Write("))]\r\n");


        }



            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForType(entity)));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(code.AbstractOption(entity))));


            this.Write("partial class ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(entity)));


            this.Write(" : ");

            this.Write(this.ToStringHelper.ToStringWithCulture(BaseTypeName(entity, code)));


            this.Write("\r\n{\r\n");


        if (!entity.Abstract)
        {
            WriteFactoryMethod(entity, code);
        }

        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionSimpleProperties"));
        foreach (EdmProperty property in entity.Properties.Where(p => p.DeclaringType == entity && p.TypeUsage.EdmType is SimpleType))
        {
            VerifyGetterAndSetterAccessibilityCompatability(property);
            WriteSimpleTypeProperty(property, code);
        }
        region.End();

        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionComplexProperties"));
        foreach (EdmProperty property in entity.Properties.Where(p => p.DeclaringType == entity && p.TypeUsage.EdmType is ComplexType))
        {
            VerifyGetterAndSetterAccessibilityCompatability(property);
            WriteComplexTypeProperty(property, code);
        }
        region.End();

        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionNavigationProperties"));
        foreach (NavigationProperty navProperty in entity.NavigationProperties.Where(n => n.DeclaringType == entity))
        {
            VerifyGetterAndSetterAccessibilityCompatability(navProperty);


            this.Write("\r\n    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(navProperty)));


            this.Write("\r\n    /// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(navProperty, region.CurrentIndentLevel)));


            this.Write("\r\n    [XmlIgnoreAttribute()]\r\n    [SoapIgnoreAttribute()]\r\n    [DataMemberAttribu" +
                    "te()]\r\n    [EdmRelationshipNavigationPropertyAttribute(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.NamespaceName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.Name));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name));


            this.Write("\")]\r\n");


            if (navProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
            {


            this.Write("    ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(navProperty))));



            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(navProperty)));


            this.Write(" EntityCollection<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write("> ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(navProperty)));


            this.Write("\r\n    {\r\n        ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(navProperty))));


            this.Write("get\r\n        {\r\n            return ((IEntityWithRelationships)this).RelationshipM" +
                    "anager.GetRelatedCollection<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write(">(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name));


            this.Write("\");\r\n        }\r\n        ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter(navProperty))));


            this.Write("set\r\n        {\r\n            if ((value != null))\r\n            {\r\n                " +
                    "((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection" +
                    "<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write(">(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name));


            this.Write("\", value);\r\n            }\r\n        }\r\n    }\r\n");


           }
           else
           {


            this.Write("    ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(navProperty))));



            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(navProperty)));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write(" ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(navProperty)));


            this.Write("\r\n    {\r\n        ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(navProperty))));


            this.Write("get\r\n        {\r\n            return ((IEntityWithRelationships)this).RelationshipM" +
                    "anager.GetRelatedReference<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write(">(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name));


            this.Write("\").Value;\r\n        }\r\n        ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter(navProperty))));


            this.Write("set\r\n        {\r\n            ((IEntityWithRelationships)this).RelationshipManager." +
                    "GetRelatedReference<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write(">(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name));


            this.Write("\").Value = value;\r\n        }\r\n    }\r\n");


        string refPropertyName = navProperty.Name + "Reference";
        if (entity.Members.Any(m => m.Name == refPropertyName))
        {
           // 
            Errors.Add(new System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6017", String.Format(CultureInfo.CurrentCulture,
                    CodeGenerationTools.GetResourceString("Template_ConflictingGeneratedNavPropName"),
                        navProperty.Name, entity.FullName, refPropertyName)));
        }


            this.Write("    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(navProperty)));


            this.Write("\r\n    /// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(navProperty, region.CurrentIndentLevel)));


            this.Write("\r\n    [BrowsableAttribute(false)]\r\n    [DataMemberAttribute()]\r\n    ");

            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(navProperty)));


            this.Write(" EntityReference<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write("> ");

            this.Write(this.ToStringHelper.ToStringWithCulture(refPropertyName));


            this.Write("\r\n    {\r\n        ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(navProperty))));


            this.Write("get\r\n        {\r\n            return ((IEntityWithRelationships)this).RelationshipM" +
                    "anager.GetRelatedReference<");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write(">(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name));


            this.Write("\");\r\n        }\r\n        ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter(navProperty))));


            this.Write("set\r\n        {\r\n            if ((value != null))\r\n            {\r\n                " +
                    "((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<" +
                    "");

            this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)));


            this.Write(">(\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName));


            this.Write("\", \"");

            this.Write(this.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name));


            this.Write("\", value);\r\n            }\r\n        }\r\n    }\r\n");


            }
        }
        region.End();


            this.Write("}\r\n");


    }
    region.End();

    ////////
    //////// 
    ////////
    region.Begin(CodeGenerationTools.GetResourceString("Template_RegionComplexTypes"));
    foreach (ComplexType complex in GetSourceSchemaTypes<ComplexType>().OrderBy(c => c.Name))
    {


            this.Write("\r\n/// <summary>\r\n/// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(complex)));


            this.Write("\r\n/// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(complex, region.CurrentIndentLevel)));


            this.Write("\r\n[EdmComplexTypeAttribute(NamespaceName=\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(complex.NamespaceName));


            this.Write("\", Name=\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(complex.Name));


            this.Write("\")]\r\n[DataContractAttribute(IsReference=true)]\r\n[Serializable()]\r\n");

            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForType(complex)));


            this.Write(" partial class ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(complex)));


            this.Write(" : ComplexObject\r\n{\r\n");


        WriteFactoryMethod(complex, code);
        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionSimpleProperties"));
        foreach (EdmProperty property in complex.Properties.Where(p => p.DeclaringType == complex && p.TypeUsage.EdmType is SimpleType))
        {
            VerifyGetterAndSetterAccessibilityCompatability(property);
            WriteSimpleTypeProperty(property, code);
        }
        region.End();

        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionComplexProperties"));
        foreach (EdmProperty property in complex.Properties.Where(p => p.DeclaringType == complex && p.TypeUsage.EdmType is ComplexType))
        {
            VerifyGetterAndSetterAccessibilityCompatability(property);
            WriteComplexTypeProperty(property, code);
        }
        region.End();


            this.Write("}\r\n");


    }
    region.End();

    ////////
    //////// 
    ////////
    region.Begin(CodeGenerationTools.GetResourceString("Template_RegionEnumTypes"));
    foreach (EnumType enumType in GetSourceSchemaTypes<EnumType>().OrderBy(c => c.Name))
    {


            this.Write("\r\n/// <summary>\r\n/// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(enumType)));


            this.Write("\r\n/// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(enumType, region.CurrentIndentLevel)));


            this.Write("\r\n[EdmEnumTypeAttribute(NamespaceName=\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(enumType.NamespaceName));


            this.Write("\", Name=\"");

            this.Write(this.ToStringHelper.ToStringWithCulture(enumType.Name));


            this.Write("\")]\r\n[DataContractAttribute()]\r\n");


        if (enumType.IsFlags)
        {


            this.Write("[FlagsAttribute()]\r\n");


        }



            this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForType(enumType)));


            this.Write(" enum ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(enumType)));


            this.Write(" : ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(enumType.UnderlyingType.ClrEquivalentType, fullyQualifySystemTypes: false)));


            this.Write("\r\n{\r\n");


        foreach (EnumMember member in enumType.Members)
        {


            this.Write("    /// <summary>\r\n    /// ");

            this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(member)));


            this.Write("\r\n    /// </summary>");

            this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(member, region.CurrentIndentLevel + 1)));


            this.Write("\r\n    [EnumMemberAttribute()]\r\n    ");

            this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(member)));


            this.Write(" = ");

            this.Write(this.ToStringHelper.ToStringWithCulture(member.Value));


            this.Write(",\r\n\r\n");


        }

        // 
        if (enumType.Members.Any())
        {
            this.GenerationEnvironment.Remove(
                this.GenerationEnvironment.Length - (CurrentIndent.Length + 5), CurrentIndent.Length + 3);
        }


            this.Write("}\r\n");


    }
    region.End();

    if (!String.IsNullOrEmpty(namespaceName))
    {
        PopIndent();


            this.Write("}\r\n");


    }

    if (!VerifyTypeUniqueness(GetSourceSchemaTypes<GlobalItem>()
                                  .Where(i => i is StructuralType || i is EnumType || i is EntityContainer)
                                  .Select(i => code.GetGlobalItemName(i))))
    {
        return string.Empty;
    }


            return this.GenerationEnvironment.ToString();
        }



    ////////
    //////// 
    ////////

    ////////
    //////// 
    ////////
    private void WriteFactoryMethod(StructuralType structuralType, CodeGenerationTools code)
    {
        CodeRegion region = new CodeRegion(this, 1);

        string methodName = "Create" + structuralType.Name;
        UniqueIdentifierService uniqueIdentifier = new UniqueIdentifierService();
        string instanceName = code.Escape(uniqueIdentifier.AdjustIdentifier((code.CamelCase(structuralType.Name))));
        IEnumerable<FactoryMethodParameter> parameters = FactoryMethodParameter.CreateParameters(structuralType.Members.OfType<EdmProperty>().Where(p => IncludePropertyInFactoryMethod(structuralType, p)), uniqueIdentifier, MultiSchemaEscape, code);

        if (parameters.Count() == 0)
            return;

        if (structuralType.Members.Any(m => m.Name == methodName))
        {
            // 
            Errors.Add(new System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6029",
                String.Format(CultureInfo.CurrentCulture,
                        CodeGenerationTools.GetResourceString("Template_FactoryMethodNameConflict"), methodName, structuralType.FullName)));
        }

        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionFactoryMethod"));



this.Write("\r\n    /// <summary>\r\n    /// ");



this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_FactoryMethodComment"), structuralType.Name)));



this.Write("\r\n    /// </summary>");



this.Write(this.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(p => new Tuple<string, string>(p.RawParameterName, p.ParameterComment)), region.CurrentIndentLevel)));



this.Write("\r\n    public static ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(structuralType)));



this.Write(" ");



this.Write(this.ToStringHelper.ToStringWithCulture(methodName));



this.Write("(");



this.Write(this.ToStringHelper.ToStringWithCulture(string.Join(", ", parameters.Select(p => p.ParameterType + " " + p.ParameterName).ToArray())));



this.Write(")\r\n    {\r\n        ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(structuralType)));



this.Write(" ");



this.Write(this.ToStringHelper.ToStringWithCulture(instanceName));



this.Write(" = new ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(structuralType)));



this.Write("();\r\n");




        foreach (FactoryMethodParameter parameter in parameters)
        {
            if (parameter.IsComplexType)
            {
                // 



this.Write("        ");



this.Write(this.ToStringHelper.ToStringWithCulture(instanceName));



this.Write(".");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(parameter.Source)));



this.Write(" = StructuralObject.VerifyComplexObjectIsNotNull(");



this.Write(this.ToStringHelper.ToStringWithCulture(parameter.ParameterName));



this.Write(", \"");



this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Source.Name));



this.Write("\");\r\n");




            }
            else
            {
                // 



this.Write("        ");



this.Write(this.ToStringHelper.ToStringWithCulture(instanceName));



this.Write(".");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(parameter.Source)));



this.Write(" = ");



this.Write(this.ToStringHelper.ToStringWithCulture(parameter.ParameterName));



this.Write(";\r\n");




            }
        }



this.Write("        return ");



this.Write(this.ToStringHelper.ToStringWithCulture(instanceName));



this.Write(";\r\n    }\r\n");




        region.End();
    }


    ////////
    //////// 
    ////////
    private void WriteSimpleTypeProperty(EdmProperty simpleProperty, CodeGenerationTools code)
    {
        MetadataTools ef = new MetadataTools(this);



this.Write("\r\n    /// <summary>\r\n    /// ");



this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(simpleProperty)));



this.Write("\r\n    /// </summary>");



this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(simpleProperty, 1)));



this.Write("\r\n    [EdmScalarPropertyAttribute(EntityKeyProperty=");



this.Write(this.ToStringHelper.ToStringWithCulture(code.CreateLiteral(ef.IsKey(simpleProperty))));



this.Write(", IsNullable=");



this.Write(this.ToStringHelper.ToStringWithCulture(code.CreateLiteral(ef.IsNullable(simpleProperty))));



this.Write(")]\r\n    [DataMemberAttribute()]\r\n    ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(simpleProperty))));



this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(simpleProperty)));



this.Write(" ");



this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(simpleProperty.TypeUsage, code)));



this.Write(" ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(simpleProperty)));



this.Write("\r\n    {\r\n        ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(simpleProperty))));



this.Write("get\r\n        {\r\n");



             if (ef.ClrType(simpleProperty.TypeUsage) == typeof(byte[]))
                {



this.Write("            return StructuralObject.GetValidValue(");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(simpleProperty)));



this.Write(");\r\n");




                }
                else
                {



this.Write("            return ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(simpleProperty)));



this.Write(";\r\n");




                }



this.Write("        }\r\n        ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter((simpleProperty)))));



this.Write("set\r\n        {\r\n");




        if (ef.IsKey(simpleProperty))
            {
                if (ef.ClrType(simpleProperty.TypeUsage) == typeof(byte[]))
                {



this.Write("            if (!StructuralObject.BinaryEquals(");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(simpleProperty)));



this.Write(", value))\r\n");




                }
                else
                {



this.Write("            if (");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(simpleProperty)));



this.Write(" != value)\r\n");




                }



this.Write("            {\r\n");




        PushIndent(CodeRegion.GetIndent(1));
            }



this.Write("            ");



this.Write(this.ToStringHelper.ToStringWithCulture(ChangingMethodName(simpleProperty)));



this.Write("(value);\r\n            ReportPropertyChanging(\"");



this.Write(this.ToStringHelper.ToStringWithCulture(simpleProperty.Name));



this.Write("\");\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(simpleProperty)));



this.Write(" = ");



this.Write(this.ToStringHelper.ToStringWithCulture(CastToEnumType(simpleProperty.TypeUsage, code)));



this.Write("StructuralObject.SetValidValue(");



this.Write(this.ToStringHelper.ToStringWithCulture(CastToUnderlyingType(simpleProperty.TypeUsage, code)));



this.Write("value");



this.Write(this.ToStringHelper.ToStringWithCulture(OptionalNullableParameterForSetValidValue(simpleProperty, code)));



this.Write(", \"");



this.Write(this.ToStringHelper.ToStringWithCulture(simpleProperty.Name));



this.Write("\");\r\n            ReportPropertyChanged(\"");



this.Write(this.ToStringHelper.ToStringWithCulture(simpleProperty.Name));



this.Write("\");\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(ChangedMethodName(simpleProperty)));



this.Write("();\r\n");




        if (ef.IsKey(simpleProperty))
            {
        PopIndent();



this.Write("            }\r\n");




            }



this.Write("        }\r\n    }\r\n    private ");



this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(simpleProperty.TypeUsage, code)));



this.Write(" ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(simpleProperty)));



this.Write(this.ToStringHelper.ToStringWithCulture(code.StringBefore(" = ", code.CreateLiteral(simpleProperty.DefaultValue))));



this.Write(";\r\n    partial void ");



this.Write(this.ToStringHelper.ToStringWithCulture(ChangingMethodName(simpleProperty)));



this.Write("(");



this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(simpleProperty.TypeUsage, code)));



this.Write(" value);\r\n    partial void ");



this.Write(this.ToStringHelper.ToStringWithCulture(ChangedMethodName(simpleProperty)));



this.Write("();\r\n");




    }

    ////////
    //////// 
    ////////
    private void WriteComplexTypeProperty(EdmProperty complexProperty, CodeGenerationTools code)
    {



this.Write("\r\n    /// <summary>\r\n    /// ");



this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(complexProperty)));



this.Write("\r\n    /// </summary>");



this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(complexProperty, 1)));



this.Write("\r\n    [EdmComplexPropertyAttribute()]\r\n    [DesignerSerializationVisibility(Desig" +
        "nerSerializationVisibility.Content)]\r\n    [XmlElement(IsNullable=true)]\r\n    [So" +
        "apElement(IsNullable=true)]\r\n    [DataMemberAttribute()]\r\n    ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(complexProperty))));



this.Write(this.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(complexProperty)));



this.Write(" ");



this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(complexProperty.TypeUsage, code)));



this.Write(" ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.Escape(complexProperty)));



this.Write("\r\n    {\r\n        ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(complexProperty))));



this.Write("get\r\n        {\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)));



this.Write(" = GetValidValue(");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)));



this.Write(", \"");



this.Write(this.ToStringHelper.ToStringWithCulture(complexProperty.Name));



this.Write("\", false, ");



this.Write(this.ToStringHelper.ToStringWithCulture(InitializedTrackingField(complexProperty, code)));



this.Write(");\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(InitializedTrackingField(complexProperty, code)));



this.Write(" = true;\r\n            return ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)));



this.Write(";\r\n        }\r\n        ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter(complexProperty))));



this.Write("set\r\n        {\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(ChangingMethodName(complexProperty)));



this.Write("(value);\r\n            ReportPropertyChanging(\"");



this.Write(this.ToStringHelper.ToStringWithCulture(complexProperty.Name));



this.Write("\");\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)));



this.Write(" = SetValidValue(");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)));



this.Write(", value, \"");



this.Write(this.ToStringHelper.ToStringWithCulture(complexProperty.Name));



this.Write("\");\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(InitializedTrackingField(complexProperty, code)));



this.Write(" = true;\r\n            ReportPropertyChanged(\"");



this.Write(this.ToStringHelper.ToStringWithCulture(complexProperty.Name));



this.Write("\");\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(ChangedMethodName(complexProperty)));



this.Write("();\r\n        }\r\n    }\r\n    private ");



this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(complexProperty.TypeUsage, code)));



this.Write(" ");



this.Write(this.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)));



this.Write(";\r\n    private bool ");



this.Write(this.ToStringHelper.ToStringWithCulture(InitializedTrackingField(complexProperty, code)));



this.Write(";\r\n    partial void ");



this.Write(this.ToStringHelper.ToStringWithCulture(ChangingMethodName(complexProperty)));



this.Write("(");



this.Write(this.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(complexProperty.TypeUsage, code)));



this.Write(" value);\r\n    partial void ");



this.Write(this.ToStringHelper.ToStringWithCulture(ChangedMethodName(complexProperty)));



this.Write("();\r\n");




    }

    private void WriteFunctionParameters(IEnumerable<FunctionImportParameter> parameters)
    {
        foreach (FunctionImportParameter parameter in parameters)
        {
            if (!parameter.NeedsLocalVariable)
            {
                continue;
            }



this.Write("        ObjectParameter ");



this.Write(this.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName));



this.Write(";\r\n        if (");



this.Write(this.ToStringHelper.ToStringWithCulture(parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null"));



this.Write(")\r\n        {\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName));



this.Write(" = new ObjectParameter(\"");



this.Write(this.ToStringHelper.ToStringWithCulture(parameter.EsqlParameterName));



this.Write("\", ");



this.Write(this.ToStringHelper.ToStringWithCulture(parameter.FunctionParameterName));



this.Write(");\r\n        }\r\n        else\r\n        {\r\n            ");



this.Write(this.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName));



this.Write(" = new ObjectParameter(\"");



this.Write(this.ToStringHelper.ToStringWithCulture(parameter.EsqlParameterName));



this.Write("\", typeof(");



this.Write(this.ToStringHelper.ToStringWithCulture(parameter.RawClrTypeName));



this.Write("));\r\n        }\r\n\r\n");




        }
    }

    private void WriteLazyLoadingEnabled(EntityContainer container)
    {
        string lazyLoadingAttributeValue = null;
        string lazyLoadingAttributeName = MetadataConstants.EDM_ANNOTATION_09_02 + ":LazyLoadingEnabled";
        if(MetadataTools.TryGetStringMetadataPropertySetting(container, lazyLoadingAttributeName, out lazyLoadingAttributeValue))
        {
            bool isLazyLoading = false;
            if(bool.TryParse(lazyLoadingAttributeValue, out isLazyLoading))
            {



this.Write("        this.ContextOptions.LazyLoadingEnabled = ");



this.Write(this.ToStringHelper.ToStringWithCulture(isLazyLoading.ToString().ToLowerInvariant()));



this.Write(";\r\n");




            }
        }
    }

////////
//////// 
////////
public string SourceCsdlPath{ get; set; }
public string ModelNamespace{ get; set; }
public EdmItemCollection ItemCollection{ get; set; }
public IEnumerable<string> ReferenceCsdlPaths{ get; set; }
public Nullable<bool> CreateContextAddToMethods{ get; set; }
public Dictionary<string, string> EdmToObjectNamespaceMap
{
    get { return _edmToObjectNamespaceMap; }
    set { _edmToObjectNamespaceMap = value; }
}
public Dictionary<string, string> _edmToObjectNamespaceMap = new Dictionary<string, string>();
public Double SourceEdmVersion
{
    get
    {
        if (ItemCollection != null)
        {
            return ItemCollection.EdmVersion;
        }

        return 0.0;
    }
}

private bool VerifyTypeUniqueness(IEnumerable<string> types)
{
    HashSet<string> hash = new HashSet<string>();
    foreach (string type in types)
    {
        if (!hash.Add(type))
        {
            // 
            Errors.Add(new System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6034",
                String.Format(CultureInfo.CurrentCulture,
                    CodeGenerationTools.GetResourceString("Template_DuplicateTopLevelType"),
                    type)));
            return false;
        }
    }
    return true;
}

void ApplyUserSettings(UserSettings userSettings)
{
    // 
    if (SourceCsdlPath == null)
    {
#if !PREPROCESSED_TEMPLATE
        if(userSettings.SourceCsdlPath == "$" + "edmxInputFile" + "$")
        {
            Errors.Add(new System.CodeDom.Compiler.CompilerError(Host.TemplateFile, -1, -1, "",
                CodeGenerationTools.GetResourceString("Template_ReplaceVsItemTemplateToken")));
            return;
        }

        SourceCsdlPath = Host.ResolvePath(userSettings.SourceCsdlPath);
#else
        SourceCsdlPath = userSettings.SourceCsdlPath;
#endif
    }

    // normalize the path, remove ..\ from it
    SourceCsdlPath = Path.GetFullPath(SourceCsdlPath);


    if (ReferenceCsdlPaths == null)
    {
        ReferenceCsdlPaths = userSettings.ReferenceCsdlPaths;
    }

    if (!CreateContextAddToMethods.HasValue)
    {
        CreateContextAddToMethods = userSettings.CreateContextAddToMethods;
    }

    DefaultSummaryComment = CodeGenerationTools.GetResourceString("Template_CommentNoDocumentation");
}

class UserSettings
{
    public string SourceCsdlPath{ get; set; }
    public string[] ReferenceCsdlPaths{ get; set; }
    public bool FullyQualifySystemTypes{ get; set; }
    public bool CreateContextAddToMethods{ get; set; }
    public bool CamelCaseFields{ get; set; }
}

string GetNamespaceName(CodeGenerationTools code)
{
    string namespaceName = code.VsNamespaceSuggestion();

#if PREPROCESSED_TEMPLATE
    if (String.IsNullOrEmpty(namespaceName))
    {
        namespaceName = GetObjectNamespace(ModelNamespace);
    }
#endif
    return namespaceName;
}

string MultiSchemaEscape(TypeUsage usage, CodeGenerationTools code)
{
    MetadataTools ef = new MetadataTools(this);
    if (usage.EdmType != null)
    {
        if (usage.EdmType is StructuralType)
        {
            return MultiSchemaEscape(usage.EdmType, code);
        }
        else if (usage.EdmType is EnumType)
        {
            string typeName = MultiSchemaEscape(usage.EdmType, code);
            if (ef.IsNullable(usage))
            {
                return String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName);
            }

            return typeName;
        }
    }

    return code.Escape(usage);
}

string MultiSchemaEscape(EdmType type, CodeGenerationTools code)
{
    if (type.NamespaceName != ModelNamespace)
    {
        return code.CreateFullName(code.EscapeNamespace(GetObjectNamespace(type.NamespaceName)), code.Escape(type));
    }

    return code.Escape(type);
}

string NewModifier(NavigationProperty navigationProperty)
{
    Type baseType = typeof(EntityObject);
    return NewModifier(baseType, navigationProperty.Name);
}

string NewModifier(EdmFunction edmFunction)
{
    Type baseType = typeof(ObjectContext);
    return NewModifier(baseType, edmFunction.Name);
}

string NewModifier(EntitySet set)
{
    Type baseType = typeof(ObjectContext);
    return NewModifier(baseType, set.Name);
}

string NewModifier(EdmProperty property)
{
    Type baseType;
    if (property.DeclaringType.BuiltInTypeKind == BuiltInTypeKind.EntityType)
    {
        baseType = typeof(EntityObject);
    }
    else
    {
        baseType = typeof(ComplexObject);
    }
    return NewModifier(baseType, property.Name);
}

string NewModifier(Type type, string memberName)
{
    if (HasBaseMemberWithMatchingName(type, memberName))
    {
        return "new";
    }
    return string.Empty;
}

static bool HasBaseMemberWithMatchingName(Type type, string memberName)
{
    BindingFlags bindingFlags = BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public
                | BindingFlags.Instance | BindingFlags.Static;
    return type.GetMembers(bindingFlags).Where(m => IsVisibleMember(m)).Any(m => m.Name == memberName);
}

string CastToEnumType(TypeUsage typeUsage, CodeGenerationTools code)
{
    EnumType type = typeUsage.EdmType as EnumType;
    if (type == null)
        return string.Empty;

    return "(" + MultiSchemaEscape(typeUsage, code) + ")";
}

string CastToUnderlyingType(TypeUsage typeUsage, CodeGenerationTools code)
{
    MetadataTools ef = new MetadataTools(this);
    EnumType type = typeUsage.EdmType as EnumType;
    if (type == null)
    {
        return string.Empty;
    }

    string clrType = code.Escape(type.UnderlyingType.ClrEquivalentType, fullyQualifySystemTypes: false);

    if (ef.IsNullable(typeUsage))
    {
        clrType = String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", clrType);
    }

    return "(" + clrType + ")";
}

string ChangingMethodName(EdmMember member)
{
    return string.Format(CultureInfo.InvariantCulture, "On{0}Changing", member.Name);
}

string ChangedMethodName(EdmMember member)
{
    return string.Format(CultureInfo.InvariantCulture, "On{0}Changed", member.Name);
}

string InitializedTrackingField(EdmProperty property, CodeGenerationTools code)
{
    string namePart = property.Name + "Initialized";
    if (code.CamelCaseFields)
    {
        namePart = code.CamelCase(namePart);
    }
    return "_" + namePart;
}

string OptionalNullableParameterForSetValidValue(EdmMember member, CodeGenerationTools code)
{
    MetadataTools ef = new MetadataTools(this);
    string list = string.Empty;
    PrimitiveType type = member.TypeUsage.EdmType as PrimitiveType;
    if (type != null && type.ClrEquivalentType.IsClass)
    {
        MetadataProperty storeGeneratedPatternProperty = null;
        bool isNullable = ef.IsNullable(member.TypeUsage) ||
            (member.MetadataProperties.TryGetValue(MetadataConstants.EDM_ANNOTATION_09_02 + ":StoreGeneratedPattern", false, out storeGeneratedPatternProperty) &&
             Object.Equals(storeGeneratedPatternProperty.Value, "Computed"));
        list += ", " + code.CreateLiteral(isNullable);
    }
    return list;
}

static bool IsVisibleMember(MemberInfo memberInfo)
{
    if (memberInfo is EventInfo)
    {
        EventInfo ei = (EventInfo)memberInfo;
        MethodInfo add = ei.GetAddMethod();
        MethodInfo remove = ei.GetRemoveMethod();
        return IsVisibleMethod(add) || IsVisibleMethod(remove);
    }
    else if (memberInfo is FieldInfo)
    {
        FieldInfo fi = (FieldInfo)memberInfo;
        return !fi.IsPrivate && !fi.IsAssembly;
    }
    else if (memberInfo is MethodBase)
    {
        MethodBase mb = (MethodBase)memberInfo;
        if (mb.IsSpecialName)
            return false;
        return IsVisibleMethod(mb);
    }
    else if (memberInfo is PropertyInfo)
    {
        PropertyInfo pi = (PropertyInfo)memberInfo;
        MethodInfo get = pi.GetGetMethod();
        MethodInfo set = pi.GetSetMethod();
        return IsVisibleMethod(get) || IsVisibleMethod(set);
    }

    return false;
}

static bool IsVisibleMethod(MethodBase methodBase)
{
    if (methodBase == null)
        return false;

    return !methodBase.IsPrivate && !methodBase.IsAssembly;
}

IEnumerable<T> GetSourceSchemaTypes<T>() where T : GlobalItem
{
    if (Path.GetExtension(SourceCsdlPath) != ".edmx")
    {
        return ItemCollection.GetItems<T>().Where(e => e.MetadataProperties.Any(mp => mp.Name == "SchemaSource" && (string)mp.Value == SourceCsdlPath));
    }
    else
    {
        return ItemCollection.GetItems<T>();
    }
}

string EndName(AssociationType association, int index)
{
    return association.AssociationEndMembers[index].Name;
}

string EndMultiplicity(AssociationType association, int index, CodeGenerationTools code)
{
    return code.CreateLiteral(association.AssociationEndMembers[index].RelationshipMultiplicity);
}

string EscapeEndTypeName(AssociationType association, int index, CodeGenerationTools code)
{
    EntityType entity = association.AssociationEndMembers[index].GetEntityType();
    return code.CreateFullName(code.EscapeNamespace(GetObjectNamespace(entity.NamespaceName)), code.Escape(entity));
}

string GetObjectNamespace(string csdlNamespaceName)
{
    string objectNamespace;
    if (EdmToObjectNamespaceMap.TryGetValue(csdlNamespaceName, out objectNamespace))
    {
        return objectNamespace;
    }

    return csdlNamespaceName;
}

void UpdateObjectNamespaceMap(string objectNamespace)
{
    if(objectNamespace != ModelNamespace && !EdmToObjectNamespaceMap.ContainsKey(ModelNamespace))
    {
        EdmToObjectNamespaceMap.Add(ModelNamespace, objectNamespace);
    }
}

static string FixParameterName(string name, CodeGenerationTools code)
{
    // 
    // 
    if (StringComparer.OrdinalIgnoreCase.Equals(name, "id"))
    {
        // 
        return "id";
    }
    return code.CamelCase(name);
}

string BaseTypeName(EntityType entity, CodeGenerationTools code)
{
    return entity.BaseType == null ? "EntityObject" : MultiSchemaEscape(entity.BaseType, code);
}

bool IncludePropertyInFactoryMethod(StructuralType factoryType, EdmProperty edmProperty)
{
    if (edmProperty.Nullable)
    {
        return false;
    }

    if (edmProperty.DefaultValue != null)
    {
        return false;
    }

    if ((Accessibility.ForReadOnlyProperty(edmProperty) != "public" && Accessibility.ForWriteOnlyProperty(edmProperty) != "public") ||
        (factoryType != edmProperty.DeclaringType && Accessibility.ForWriteOnlyProperty(edmProperty) == "private")
       )
    {
        // 
        return false;
    }

    return true;
}

class FactoryMethodParameter
{
    public EdmProperty Source;
    public string RawParameterName;
    public string ParameterName;
    public string ParameterType;
    public string ParameterComment;
    public bool IsComplexType;

    public static IEnumerable<FactoryMethodParameter> CreateParameters(IEnumerable<EdmProperty> properties, UniqueIdentifierService unique, Func<TypeUsage, CodeGenerationTools, string> multiSchemaEscape, CodeGenerationTools code)
    {
        List<FactoryMethodParameter> parameters = new List<FactoryMethodParameter>();
        foreach (EdmProperty property in properties)
        {
            FactoryMethodParameter parameter = new FactoryMethodParameter();
            parameter.Source = property;
            parameter.IsComplexType = property.TypeUsage.EdmType is ComplexType;
            parameter.RawParameterName = unique.AdjustIdentifier(FixParameterName(property.Name, code));
            parameter.ParameterName = code.Escape(parameter.RawParameterName);
            parameter.ParameterType = multiSchemaEscape(property.TypeUsage, code);
            parameter.ParameterComment = String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_CommentFactoryMethodParam"), property.Name);
            parameters.Add(parameter);
        }

        return parameters;
    }
}

string DefaultSummaryComment{ get; set; }

string SummaryComment(MetadataItem item)
{
    if (item.Documentation != null && item.Documentation.Summary != null)
    {
        return PrefixLinesOfMultilineComment(XMLCOMMENT_START + " ", XmlEntityize(item.Documentation.Summary));
    }

    if (DefaultSummaryComment != null)
    {
        return DefaultSummaryComment;
    }

    return string.Empty;
}

string LongDescriptionCommentElement(MetadataItem item, int indentLevel)
{
    if (item.Documentation != null && !String.IsNullOrEmpty(item.Documentation.LongDescription))
    {
        string comment = Environment.NewLine;
        string lineStart = CodeRegion.GetIndent(indentLevel) + XMLCOMMENT_START + " ";
        comment += lineStart + "<LongDescription>" + Environment.NewLine;
        comment += lineStart + PrefixLinesOfMultilineComment(lineStart, XmlEntityize(item.Documentation.LongDescription)) + Environment.NewLine;
        comment += lineStart + "</LongDescription>";
        return comment;
    }
    return string.Empty;
}

string PrefixLinesOfMultilineComment(string prefix, string comment)
{
    return comment.Replace(Environment.NewLine, Environment.NewLine + prefix);
}

string ParameterComments(IEnumerable<Tuple<string, string>> parameters, int indentLevel)
{
    System.Text.StringBuilder builder = new System.Text.StringBuilder();
    foreach (Tuple<string, string> parameter in parameters)
    {
        builder.AppendLine();
        builder.Append(CodeRegion.GetIndent(indentLevel));
        builder.Append(XMLCOMMENT_START);
        builder.Append(String.Format(CultureInfo.InvariantCulture, " <param name=\"{0}\">{1}</param>", parameter.Item1, parameter.Item2));
    }
    return builder.ToString();
}

string XmlEntityize(string text)
{
    if (string.IsNullOrEmpty(text))
    {
        return string.Empty;
    }

    text = text.Replace("&","&amp;");
    text = text.Replace("<","&lt;").Replace(">","&gt;");
    string id = Guid.NewGuid().ToString();
    text = text.Replace(Environment.NewLine, id);
    text = text.Replace("\r", "&#xD;").Replace("\n","&#xA;");
    text = text.Replace(id, Environment.NewLine);
    return text.Replace("\'","&apos;").Replace("\"","&quot;");
}

const string XMLCOMMENT_START = "///";
IEnumerable<EdmProperty> GetProperties(StructuralType type)
{
    if (type.BuiltInTypeKind == BuiltInTypeKind.EntityType)
    {
        return ((EntityType)type).Properties;
    }
    else
    {
        return ((ComplexType)type).Properties;
    }
}

protected void VerifyGetterAndSetterAccessibilityCompatability(EdmMember member)
{
    string rawGetterAccessibility = Accessibility.ForReadOnlyProperty(member);
    string rawSetterAccessibility = Accessibility.ForWriteOnlyProperty(member);

    if ((rawGetterAccessibility == "internal" && rawSetterAccessibility ==   "protected") ||
        (rawGetterAccessibility == "protected" && rawSetterAccessibility == "internal"))

    {
           Errors.Add(new System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6033", String.Format(CultureInfo.CurrentCulture,
                   CodeGenerationTools.GetResourceString("GeneratedPropertyAccessibilityConflict"),
                       member.Name, rawGetterAccessibility, rawSetterAccessibility)));
    }
}

private void VerifyEntityTypeAndSetAccessibilityCompatability(EntitySet set)
{
    string typeAccess = Accessibility.ForType(set.ElementType);
    string setAccess = Accessibility.ForReadOnlyProperty(set);

    if(typeAccess == "internal" && (setAccess == "public" || setAccess == "protected"))
    {
       Errors.Add(new System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6036", String.Format(CultureInfo.CurrentCulture,
               CodeGenerationTools.GetResourceString("EntityTypeAndSetAccessibilityConflict"),
                   set.ElementType.Name, typeAccess, set.Name, setAccess)));
    }
}

private void DefineMetadata()
{
    TemplateMetadata[MetadataConstants.TT_TEMPLATE_NAME] = "CSharpCodeGen";
    TemplateMetadata[MetadataConstants.TT_TEMPLATE_VERSION] = "5.0";
    TemplateMetadata[MetadataConstants.TT_MINIMUM_ENTITY_FRAMEWORK_VERSION] = "5.0";
}

sealed class UniqueIdentifierService
{
    private readonly HashSet<string> _knownIdentifiers;

    public UniqueIdentifierService()
    {
        _knownIdentifiers = new HashSet<string>(StringComparer.Ordinal);
    }

    /// <summary>
    /// 
    /// 
    /// </summary>
    public string AdjustIdentifier(string identifier)
    {
        // 
        var numberOfConflicts = 0;
        var adjustedIdentifier = identifier;

        while (!_knownIdentifiers.Add(adjustedIdentifier))
        {
            ++numberOfConflicts;
            adjustedIdentifier = identifier + numberOfConflicts.ToString(CultureInfo.InvariantCulture);
        }

        return adjustedIdentifier;
    }
}




// Copyright (c) Microsoft Corporation.  All rights reserved.

public static Dictionary<string, string> TemplateMetadata = new Dictionary<string, string>();

/// <summary>
/// Responsible for helping to create source code that is
/// correctly formated and functional
/// </summary>
public class CodeGenerationTools
{
    private readonly DynamicTextTransformation _textTransformation;
    private readonly CSharpCodeProvider _code;
    private readonly MetadataTools _ef;

    /// <summary>
    /// Initializes a new CodeGenerationTools object with the TextTransformation (T4 generated class)
    /// that is currently running
    /// </summary>
    public CodeGenerationTools(object textTransformation)
    {
        if (textTransformation == null)
        {
            throw new ArgumentNullException("textTransformation");
        }

        _textTransformation = DynamicTextTransformation.Create(textTransformation);
        _code = new CSharpCodeProvider();
        _ef = new MetadataTools(_textTransformation);
        FullyQualifySystemTypes = false;
        CamelCaseFields = true;
    }

    /// <summary>
    /// When true, all types that are not being generated
    /// are fully qualified to keep them from conflicting with
    /// types that are being generated. Useful when you have
    /// something like a type being generated named System.
    ///
    /// Default is false.
    /// </summary>
    public bool FullyQualifySystemTypes { get; set; }

    /// <summary>
    /// When true, the field names are Camel Cased,
    /// otherwise they will preserve the case they
    /// start with.
    ///
    /// Default is true.
    /// </summary>
    public bool CamelCaseFields { get; set; }

    /// <summary>
    /// Returns the NamespaceName suggested by VS if running inside VS.  Otherwise, returns
    /// null.
    /// </summary>
    public string VsNamespaceSuggestion()
    {
        string suggestion = _textTransformation.Host.ResolveParameterValue("directiveId", "namespaceDirectiveProcessor", "namespaceHint");
        if (String.IsNullOrEmpty(suggestion))
        {
            return null;
        }

        return suggestion;
    }

    /// <summary>
    /// Returns a string that is safe for use as an identifier in C#.
    /// Keywords are escaped.
    /// </summary>
    public string Escape(string name)
    {
        if (name == null)
        {
            return null;
        }

        return _code.CreateEscapedIdentifier(name);
    }

    /// <summary>
    /// Returns the name of the TypeUsage's EdmType that is safe for
    /// use as an identifier.
    /// </summary>
    public string Escape(TypeUsage typeUsage)
    {
        if (typeUsage == null)
        {
            return null;
        }

        if (typeUsage.EdmType is ComplexType ||
            typeUsage.EdmType is EntityType)
        {
            return Escape(typeUsage.EdmType.Name);
        }
        else if (typeUsage.EdmType is SimpleType)
        {
            Type clrType = _ef.UnderlyingClrType(typeUsage.EdmType);
            string typeName = typeUsage.EdmType is EnumType ? Escape(typeUsage.EdmType.Name) : Escape(clrType);
            if (clrType.IsValueType && _ef.IsNullable(typeUsage))
            {
                return String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName);
            }

            return typeName;
        }
        else if (typeUsage.EdmType is CollectionType)
        {
            return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", Escape(((CollectionType)typeUsage.EdmType).TypeUsage));
        }

        throw new ArgumentException("typeUsage");
    }

    /// <summary>
    /// Returns the name of the EdmMember that is safe for
    /// use as an identifier.
    /// </summary>
    public string Escape(EdmMember member)
    {
        if (member == null)
        {
            return null;
        }

        return Escape(member.Name);
    }

    /// <summary>
    /// Returns the name of the EdmType that is safe for
    /// use as an identifier.
    /// </summary>
    public string Escape(EdmType type)
    {
        if (type == null)
        {
            return null;
        }

        return Escape(type.Name);
    }

    /// <summary>
    /// Returns the name of the EdmFunction that is safe for
    /// use as an identifier.
    /// </summary>
    public string Escape(EdmFunction function)
    {
        if (function == null)
        {
            return null;
        }

        return Escape(function.Name);
    }

    /// <summary>
    /// Returns the name of the EnumMember that is safe for
    /// use as an identifier.
    /// </summary>
    public string Escape(EnumMember member)
    {
        if (member == null)
        {
            return null;
        }

        return Escape(member.Name);
    }

    /// <summary>
    /// Returns the name of the EntityContainer that is safe for
    /// use as an identifier.
    /// </summary>
    public string Escape(EntityContainer container)
    {
        if (container == null)
        {
            return null;
        }

        return Escape(container.Name);
    }

    /// <summary>
    /// Returns the name of the EntitySet that is safe for
    /// use as an identifier.
    /// </summary>
    public string Escape(EntitySet set)
    {
        if (set == null)
        {
            return null;
        }

        return Escape(set.Name);
    }

    /// <summary>
    /// Returns the name of the StructuralType that is safe for
    /// use as an identifier.
    /// </summary>
    public string Escape(StructuralType type)
    {
        if (type == null)
        {
            return null;
        }

        return Escape(type.Name);
    }

    /// <summary>
    /// Returns the NamespaceName with each segment safe to
    /// use as an identifier.
    /// </summary>
    public string EscapeNamespace(string namespaceName)
    {
        if (String.IsNullOrEmpty(namespaceName))
        {
            return namespaceName;
        }

        string[] parts = namespaceName.Split('.');
        namespaceName = String.Empty;
        foreach (string part in parts)
        {
            if (namespaceName != String.Empty)
            {
                namespaceName += ".";
            }

            namespaceName += Escape(part);
        }

        return namespaceName;
    }

    /// <summary>
    /// Returns the name of the EdmMember formatted for
    /// use as a field identifier.
    ///
    /// This method changes behavior based on the CamelCaseFields
    /// setting.
    /// </summary>
    public string FieldName(EdmMember member)
    {
        if (member == null)
        {
            return null;
        }

        return FieldName(member.Name);
    }

    /// <summary>
    /// Returns the name of the EntitySet formatted for
    /// use as a field identifier.
    ///
    /// This method changes behavior based on the CamelCaseFields
    /// setting.
    /// </summary>
    public string FieldName(EntitySet set)
    {
        if (set == null)
        {
            return null;
        }

        return FieldName(set.Name);

    }

    private string FieldName(string name)
    {
        if (CamelCaseFields)
        {
            return "_" + CamelCase(name);
        }
        else
        {
            return "_" + name;
        }
    }

    /// <summary>
    /// Returns the name of the Type object formatted for
    /// use in source code.
    ///
    /// This method changes behavior based on the FullyQualifySystemTypes
    /// setting.
    /// </summary>
    public string Escape(Type clrType)
    {
        return Escape(clrType, FullyQualifySystemTypes);
    }

    /// <summary>
    /// Returns the name of the Type object formatted for
    /// use in source code.
    /// </summary>
    public string Escape(Type clrType, bool fullyQualifySystemTypes)
    {
        if(clrType == null)
        {
            return null;
        }

        string typeName;
        if (fullyQualifySystemTypes)
        {
            typeName = "global::" + clrType.FullName;
        }
        else
        {
            typeName = _code.GetTypeOutput(new CodeTypeReference(clrType));
        }
        return typeName;
    }

    /// <summary>
    /// Returns the abstract option if the entity is Abstract, otherwise returns String.Empty
    /// </summary>
    public string AbstractOption(EntityType entity)
    {
        if (entity.Abstract)
        {
            return "abstract";
        }
        return String.Empty;
    }

    /// <summary>
    /// Returns the passed in identifier with the first letter changed to lowercase
    /// </summary>
    public string CamelCase(string identifier)
    {
        if (String.IsNullOrEmpty(identifier))
        {
            return identifier;
        }

        if (identifier.Length == 1)
        {
            return identifier[0].ToString(CultureInfo.InvariantCulture).ToLowerInvariant();
        }

        return identifier[0].ToString(CultureInfo.InvariantCulture).ToLowerInvariant() + identifier.Substring(1);
    }

    /// <summary>
    /// If the value parameter is null or empty an empty string is returned,
    /// otherwise it retuns value with a single space concatenated on the end.
    /// </summary>
    public string SpaceAfter(string value)
    {
        return StringAfter(value, " ");
    }

    /// <summary>
    /// If the value parameter is null or empty an empty string is returned,
    /// otherwise it retuns value with a single space concatenated on the end.
    /// </summary>
    public string SpaceBefore(string value)
    {
        return StringBefore(" ", value);
    }

    /// <summary>
    /// If the value parameter is null or empty an empty string is returned,
    /// otherwise it retuns value with append concatenated on the end.
    /// </summary>
    public string StringAfter(string value, string append)
    {
        if (String.IsNullOrEmpty(value))
        {
            return String.Empty;
        }

            return value + append;
    }

    /// <summary>
    /// If the value parameter is null or empty an empty string is returned,
    /// otherwise it retuns value with prepend concatenated on the front.
    /// </summary>
    public string StringBefore(string prepend, string value)
    {
        if (String.IsNullOrEmpty(value))
        {
            return String.Empty;
        }

        return prepend + value;
    }

    /// <summary>
    /// Returns false and shows an error if the supplied type names aren't case-insensitively unique,
    /// otherwise returns true.
    /// </summary>
    public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable<string> types, string sourceFile)
    {
        return VerifyCaseInsensitiveUniqueness(types, t => string.Format(CultureInfo.CurrentCulture, GetResourceString("Template_CaseInsensitiveTypeConflict"), t), sourceFile);
    }

    /// <summary>
    /// Returns false and shows an error if the supplied strings aren't case-insensitively unique,
    /// otherwise returns true.
    /// </summary>
    private bool VerifyCaseInsensitiveUniqueness(IEnumerable<string> items, Func<string, string> formatMessage, string sourceFile)
    {
        HashSet<string> hash = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
        foreach (string item in items)
        {
            if (!hash.Add(item))
            {
                _textTransformation.Errors.Add(new System.CodeDom.Compiler.CompilerError(sourceFile, -1, -1, "6023", formatMessage(item)));
                return false;
            }
        }
        return true;
    }

    /// <summary>
    /// Returns the names of the items in the supplied collection that correspond to O-Space types.
    /// </summary>
    public IEnumerable<string> GetAllGlobalItems(EdmItemCollection itemCollection)
    {
        return itemCollection.GetItems<GlobalItem>().Where(i => i is EntityType || i is ComplexType || i is EnumType || i is EntityContainer).Select(g => GetGlobalItemName(g));
    }

    /// <summary>
    /// Returns the name of the supplied GlobalItem.
    /// </summary>
    public string GetGlobalItemName(GlobalItem item)
    {
        if (item is EdmType)
        {
            return ((EdmType)item).Name;
        }
        else
        {
            return ((EntityContainer)item).Name;
        }
    }

    /// <summary>
    /// Retuns as full of a name as possible, if a namespace is provided
    /// the namespace and name are combined with a period, otherwise just
    /// the name is returned.
    /// </summary>
    public string CreateFullName(string namespaceName, string name)
    {
        if (String.IsNullOrEmpty(namespaceName))
        {
            return name;
        }

        return namespaceName + "." + name;
    }

    /// <summary>
    /// Retuns a literal representing the supplied value.
    /// </summary>
    public string CreateLiteral(object value)
    {
        if (value == null)
        {
            return string.Empty;
        }

        Type type = value.GetType();
        if (type.IsEnum)
        {
            return type.FullName + "." + value.ToString();
        }
        if (type == typeof(Guid))
        {
            return string.Format(CultureInfo.InvariantCulture, "new Guid(\"{0}\")",
                                 ((Guid)value).ToString("D", CultureInfo.InvariantCulture));
        }
        else if (type == typeof(DateTime))
        {
            return string.Format(CultureInfo.InvariantCulture, "new DateTime({0}, DateTimeKind.Unspecified)",
                                 ((DateTime)value).Ticks);
        }
        else if (type == typeof(byte[]))
        {
            var arrayInit = string.Join(", ", ((byte[])value).Select(b => b.ToString(CultureInfo.InvariantCulture)).ToArray());
            return string.Format(CultureInfo.InvariantCulture, "new Byte[] {{{0}}}", arrayInit);
        }
        else if (type == typeof(DateTimeOffset))
        {
            var dto = (DateTimeOffset)value;
            return string.Format(CultureInfo.InvariantCulture, "new DateTimeOffset({0}, new TimeSpan({1}))",
                                 dto.Ticks, dto.Offset.Ticks);
        }
        else if (type == typeof(TimeSpan))
        {
            return string.Format(CultureInfo.InvariantCulture, "new TimeSpan({0})",
                                 ((TimeSpan)value).Ticks);
        }

        var expression = new CodePrimitiveExpression(value);
        var writer = new StringWriter();
        CSharpCodeProvider code = new CSharpCodeProvider();
        code.GenerateCodeFromExpression(expression, writer, new CodeGeneratorOptions());
        return writer.ToString();
    }

    /// <summary>
    /// Returns a resource string from the System.Data.Entity.Design assembly.
    /// </summary>
    public static string GetResourceString(string resourceName, CultureInfo culture = null)
    {
        if(_resourceManager == null)
        {
            _resourceManager = new System.Resources.ResourceManager("System.Data.Entity.Design",
                typeof(System.Data.Entity.Design.MetadataItemCollectionFactory).Assembly);
        }

        return _resourceManager.GetString(resourceName, culture);
    }
    static System.Resources.ResourceManager _resourceManager;

    private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName";

    /// <summary>
    /// Gets the entity, complex, or enum types for which code should be generated from the given item collection.
    /// Any types for which an ExternalTypeName annotation has been applied in the conceptual model
    /// metadata (CSDL) are filtered out of the returned list.
    /// </summary>
    /// <typeparam name="T">The type of item to return.</typeparam>
    /// <param name="itemCollection">The item collection to look in.</param>
    /// <returns>The items to generate.</returns>
    public IEnumerable<T> GetItemsToGenerate<T>(ItemCollection itemCollection) where T: GlobalItem
    {
        return itemCollection.GetItems<T>().Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName));
    }

    /// <summary>
    /// Returns the escaped type name to use for the given usage of a c-space type in o-space. This might be
    /// an external type name if the ExternalTypeName annotation has been specified in the
    /// conceptual model metadata (CSDL).
    /// </summary>
    /// <param name="typeUsage">The c-space type usage to get a name for.</param>
    /// <returns>The type name to use.</returns>
    public string GetTypeName(TypeUsage typeUsage)
    {
        return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null);
    }

    /// <summary>
    /// Returns the escaped type name to use for the given c-space type in o-space. This might be
    /// an external type name if the ExternalTypeName annotation has been specified in the
    /// conceptual model metadata (CSDL).
    /// </summary>
    /// <param name="edmType">The c-space type to get a name for.</param>
    /// <returns>The type name to use.</returns>
    public string GetTypeName(EdmType edmType)
    {
        return GetTypeName(edmType, isNullable: null, modelNamespace: null);
    }

    /// <summary>
    /// Returns the escaped type name to use for the given usage of an c-space type in o-space. This might be
    /// an external type name if the ExternalTypeName annotation has been specified in the
    /// conceptual model metadata (CSDL).
    /// </summary>
    /// <param name="typeUsage">The c-space type usage to get a name for.</param>
    /// <param name="modelNamespace">If not null and the type's namespace does not match this namespace, then a
    /// fully qualified name will be returned.</param>
    /// <returns>The type name to use.</returns>
    public string GetTypeName(TypeUsage typeUsage, string modelNamespace)
    {
        return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace);
    }

    /// <summary>
    /// Returns the escaped type name to use for the given c-space type in o-space. This might be
    /// an external type name if the ExternalTypeName annotation has been specified in the
    /// conceptual model metadata (CSDL).
    /// </summary>
    /// <param name="edmType">The c-space type to get a name for.</param>
    /// <param name="modelNamespace">If not null and the type's namespace does not match this namespace, then a
    /// fully qualified name will be returned.</param>
    /// <returns>The type name to use.</returns>
    public string GetTypeName(EdmType edmType, string modelNamespace)
    {
        return GetTypeName(edmType, isNullable: null, modelNamespace: modelNamespace);
    }

    /// <summary>
    /// Returns the escaped type name to use for the given c-space type in o-space. This might be
    /// an external type name if the ExternalTypeName annotation has been specified in the
    /// conceptual model metadata (CSDL).
    /// </summary>
    /// <param name="edmType">The c-space type to get a name for.</param>
    /// <param name="isNullable">Set this to true for nullable usage of this type.</param>
    /// <param name="modelNamespace">If not null and the type's namespace does not match this namespace, then a
    /// fully qualified name will be returned.</param>
    /// <returns>The type name to use.</returns>
    private string GetTypeName(EdmType edmType, bool? isNullable, string modelNamespace)
    {
        if (edmType == null)
        {
            return null;
        }

        var collectionType = edmType as CollectionType;
        if (collectionType != null)
        {
            return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", GetTypeName(collectionType.TypeUsage, modelNamespace));
        }

        // Try to get an external type name, and if that is null, then try to get escape the name from metadata,
        // possibly namespace-qualifying it.
        var typeName = Escape(edmType.MetadataProperties
                              .Where(p => p.Name == ExternalTypeNameAttributeName)
                              .Select(p => (string)p.Value)
                              .FirstOrDefault())
            ??
            (modelNamespace != null && edmType.NamespaceName != modelNamespace ?
             CreateFullName(EscapeNamespace(edmType.NamespaceName), Escape(edmType)) :
             Escape(edmType));

        if (edmType is StructuralType)
        {
            return typeName;
        }

        if (edmType is SimpleType)
        {
            var clrType = _ef.UnderlyingClrType(edmType);
            if (!(edmType is EnumType))
            {
                typeName = Escape(clrType);
            }

            return clrType.IsValueType && isNullable == true ?
                String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName) :
                typeName;
        }

        throw new ArgumentException("typeUsage");
    }
}

/// <summary>
/// Responsible for making the Entity Framework Metadata more
/// accessible for code generation.
/// </summary>
public class MetadataTools
{
    private readonly DynamicTextTransformation _textTransformation;

    /// <summary>
    /// Initializes an MetadataTools Instance  with the
    /// TextTransformation (T4 generated class) that is currently running
    /// </summary>
    public MetadataTools(object textTransformation)
    {
        if (textTransformation == null)
        {
            throw new ArgumentNullException("textTransformation");
        }

        _textTransformation = DynamicTextTransformation.Create(textTransformation);
    }

    /// <summary>
    /// This method returns the underlying CLR type of the o-space type corresponding to the supplied <paramref name="typeUsage"/>
    /// Note that for an enum type this means that the type backing the enum will be returned, not the enum type itself.
    /// </summary>
    public Type ClrType(TypeUsage typeUsage)
    {
        return UnderlyingClrType(typeUsage.EdmType);
    }

    /// <summary>
    /// This method returns the underlying CLR type given the c-space type.
    /// Note that for an enum type this means that the type backing the enum will be returned, not the enum type itself.
    /// </summary>
    public Type UnderlyingClrType(EdmType edmType)
    {
        var primitiveType = edmType as PrimitiveType;
        if (primitiveType != null)
        {
            return primitiveType.ClrEquivalentType;
        }

        var enumType = edmType as EnumType;
        if (enumType != null)
        {
            return enumType.UnderlyingType.ClrEquivalentType;
        }

        return typeof(object);
    }

    /// <summary>
    /// True if the EdmProperty is a key of its DeclaringType, False otherwise.
    /// </summary>
    public bool IsKey(EdmProperty property)
    {
        if (property != null && property.DeclaringType.BuiltInTypeKind == BuiltInTypeKind.EntityType)
        {
            return ((EntityType)property.DeclaringType).KeyMembers.Contains(property);
        }

        return false;
    }

    /// <summary>
    /// True if the EdmProperty TypeUsage is Nullable, False otherwise.
    /// </summary>
    public bool IsNullable(EdmProperty property)
    {
        return property != null && IsNullable(property.TypeUsage);
    }

    /// <summary>
    /// True if the TypeUsage is Nullable, False otherwise.
    /// </summary>
    public bool IsNullable(TypeUsage typeUsage)
    {
        Facet nullableFacet = null;
        if (typeUsage != null &&
            typeUsage.Facets.TryGetValue("Nullable", true, out nullableFacet))
        {
            return (bool)nullableFacet.Value;
        }

        return false;
    }

    /// <summary>
    /// If the passed in TypeUsage represents a collection this method returns final element
    /// type of the collection, otherwise it returns the value passed in.
    /// </summary>
    public TypeUsage GetElementType(TypeUsage typeUsage)
    {
        if (typeUsage == null)
        {
            return null;
        }

        if (typeUsage.EdmType is CollectionType)
        {
            return GetElementType(((CollectionType)typeUsage.EdmType).TypeUsage);
        }
        else
        {
            return typeUsage;
        }
    }

    /// <summary>
    /// Returns the NavigationProperty that is the other end of the same association set if it is
    /// available, otherwise it returns null.
    /// </summary>
    public NavigationProperty Inverse(NavigationProperty navProperty)
    {
        if(navProperty == null)
        {
            return null;
        }

        EntityType toEntity = navProperty.ToEndMember.GetEntityType();
        return toEntity.NavigationProperties
            .SingleOrDefault(n => Object.ReferenceEquals(n.RelationshipType, navProperty.RelationshipType) && !Object.ReferenceEquals(n, navProperty));
    }

    /// <summary>
    /// Given a property on the dependent end of a referential constraint, returns the corresponding property on the principal end.
    /// Requires: The association has a referential constraint, and the specified dependentProperty is one of the properties on the dependent end.
    /// </summary>
    public EdmProperty GetCorrespondingPrincipalProperty(NavigationProperty navProperty, EdmProperty dependentProperty)
    {
        if (navProperty == null)
        {
            throw new ArgumentNullException("navProperty");
        }

        if (dependentProperty == null)
        {
            throw new ArgumentNullException("dependentProperty");
        }

        ReadOnlyMetadataCollection<EdmProperty> fromProperties = GetPrincipalProperties(navProperty);
        ReadOnlyMetadataCollection<EdmProperty> toProperties = GetDependentProperties(navProperty);
        return fromProperties[toProperties.IndexOf(dependentProperty)];
    }

    /// <summary>
    /// Given a property on the principal end of a referential constraint, returns the corresponding property on the dependent end.
    /// Requires: The association has a referential constraint, and the specified principalProperty is one of the properties on the principal end.
    /// </summary>
    public EdmProperty GetCorrespondingDependentProperty(NavigationProperty navProperty, EdmProperty principalProperty)
    {
        if (navProperty == null)
        {
            throw new ArgumentNullException("navProperty");
        }

        if (principalProperty == null)
        {
            throw new ArgumentNullException("principalProperty");
        }

        ReadOnlyMetadataCollection<EdmProperty> fromProperties = GetPrincipalProperties(navProperty);
        ReadOnlyMetadataCollection<EdmProperty> toProperties = GetDependentProperties(navProperty);
        return toProperties[fromProperties.IndexOf(principalProperty)];
    }

    /// <summary>
    /// Gets the collection of properties that are on the principal end of a referential constraint for the specified navigation property.
    /// Requires: The association has a referential constraint.
    /// </summary>
    public ReadOnlyMetadataCollection<EdmProperty> GetPrincipalProperties(NavigationProperty navProperty)
    {
        if (navProperty == null)
        {
            throw new ArgumentNullException("navProperty");
        }

        return ((AssociationType)navProperty.RelationshipType).ReferentialConstraints[0].FromProperties;
    }

    /// <summary>
    /// Gets the collection of properties that are on the dependent end of a referential constraint for the specified navigation property.
    /// Requires: The association has a referential constraint.
    /// </summary>
    public ReadOnlyMetadataCollection<EdmProperty> GetDependentProperties(NavigationProperty navProperty)
    {
        if (navProperty == null)
        {
            throw new ArgumentNullException("navProperty");
        }

        return ((AssociationType)navProperty.RelationshipType).ReferentialConstraints[0].ToProperties;
    }

    /// <summary>
    /// True if this entity type requires the HandleCascadeDelete method defined and the method has
    /// not been defined on any base type
    /// </summary>
    public bool NeedsHandleCascadeDeleteMethod(ItemCollection itemCollection, EntityType entity)
    {
        bool needsMethod = ContainsCascadeDeleteAssociation(itemCollection, entity);
        // Check to make sure no base types have already declared this method
        EntityType baseType = entity.BaseType as EntityType;
        while(needsMethod && baseType != null)
        {
            needsMethod = !ContainsCascadeDeleteAssociation(itemCollection, baseType);
            baseType = baseType.BaseType as EntityType;
        }
        return needsMethod;
    }

    /// <summary>
    /// True if this entity type participates in any relationships where the other end has an OnDelete
    /// cascade delete defined, or if it is the dependent in any identifying relationships
    /// </summary>
    private bool ContainsCascadeDeleteAssociation(ItemCollection itemCollection, EntityType entity)
    {
        return itemCollection.GetItems<AssociationType>().Where(a =>
                ((RefType)a.AssociationEndMembers[0].TypeUsage.EdmType).ElementType == entity && IsCascadeDeletePrincipal(a.AssociationEndMembers[1]) ||
                ((RefType)a.AssociationEndMembers[1].TypeUsage.EdmType).ElementType == entity && IsCascadeDeletePrincipal(a.AssociationEndMembers[0])).Any();
    }

    /// <summary>
    /// True if the source end of the specified navigation property is the principal in an identifying relationship.
    /// or if the source end has cascade delete defined.
    /// </summary>
    public bool IsCascadeDeletePrincipal(NavigationProperty navProperty)
    {
        if (navProperty == null)
        {
            throw new ArgumentNullException("navProperty");
        }

        return IsCascadeDeletePrincipal((AssociationEndMember)navProperty.FromEndMember);
    }

    /// <summary>
    /// True if the specified association end is the principal in an identifying relationship.
    /// or if the association end has cascade delete defined.
    /// </summary>
    public bool IsCascadeDeletePrincipal(AssociationEndMember associationEnd)
    {
        if (associationEnd == null)
        {
            throw new ArgumentNullException("associationEnd");
        }

        return associationEnd.DeleteBehavior == OperationAction.Cascade || IsPrincipalEndOfIdentifyingRelationship(associationEnd);
    }

    /// <summary>
    /// True if the specified association end is the principal end in an identifying relationship.
    /// In order to be an identifying relationship, the association must have a referential constraint where all of the dependent properties are part of the dependent type's primary key.
    /// </summary>
    public bool IsPrincipalEndOfIdentifyingRelationship(AssociationEndMember associationEnd)
    {
        if (associationEnd == null)
        {
            throw new ArgumentNullException("associationEnd");
        }

        ReferentialConstraint refConstraint = ((AssociationType)associationEnd.DeclaringType).ReferentialConstraints.Where(rc => rc.FromRole == associationEnd).SingleOrDefault();
        if (refConstraint != null)
        {
            EntityType entity = refConstraint.ToRole.GetEntityType();
            return !refConstraint.ToProperties.Where(tp => !entity.KeyMembers.Contains(tp)).Any();
        }
        return false;
    }

    /// <summary>
    /// True if the specified association type is an identifying relationship.
    /// In order to be an identifying relationship, the association must have a referential constraint where all of the dependent properties are part of the dependent type's primary key.
    /// </summary>
    public bool IsIdentifyingRelationship(AssociationType association)
    {
        if (association == null)
        {
            throw new ArgumentNullException("association");
        }

        return IsPrincipalEndOfIdentifyingRelationship(association.AssociationEndMembers[0]) || IsPrincipalEndOfIdentifyingRelationship(association.AssociationEndMembers[1]);
    }

    /// <summary>
    /// requires: firstType is not null
    /// effects: if secondType is among the base types of the firstType, return true,
    /// otherwise returns false.
    /// when firstType is same as the secondType, return false.
    /// </summary>
    public bool IsSubtypeOf(EdmType firstType, EdmType secondType)
    {
        if (secondType == null)
        {
            return false;
        }

        // walk up firstType hierarchy list
        for (EdmType t = firstType.BaseType; t != null; t = t.BaseType)
        {
            if (t == secondType)
                return true;
        }
        return false;
    }

    /// <summary>
    /// Returns the subtype of the EntityType in the current itemCollection
    /// </summary>
    public IEnumerable<EntityType> GetSubtypesOf(EntityType type, ItemCollection itemCollection, bool includeAbstractTypes)
    {
        if (type != null)
        {
            IEnumerable<EntityType> typesInCollection = itemCollection.GetItems<EntityType>();
            foreach (EntityType typeInCollection in typesInCollection)
            {
                if (type.Equals(typeInCollection) == false && this.IsSubtypeOf(typeInCollection, type))
                {
                    if ( includeAbstractTypes || !typeInCollection.Abstract)
                    {
                        yield return typeInCollection;
                    }
               }
            }
        }
    }

    public static bool TryGetStringMetadataPropertySetting(MetadataItem item, string propertyName, out string value)
    {
        value = null;
        MetadataProperty property = item.MetadataProperties.FirstOrDefault(p => p.Name == propertyName);
        if (property != null)
        {
            value = (string)property.Value;
        }
        return value != null;
    }
}

/// <summary>
/// Responsible for loading an EdmItemCollection from a .edmx file or .csdl files
/// </summary>
public class MetadataLoader
{
    private readonly DynamicTextTransformation _textTransformation;

    /// <summary>
    /// Initializes an MetadataLoader Instance  with the
    /// TextTransformation (T4 generated class) that is currently running
    /// </summary>
    public MetadataLoader(object textTransformation)
    {
        if (textTransformation == null)
        {
            throw new ArgumentNullException("textTransformation");
        }

        _textTransformation = DynamicTextTransformation.Create(textTransformation);
    }

    /// <summary>
    /// Load the metadata for Edm, Store, and Mapping collections and register them
    /// with a new MetadataWorkspace, returns false if any of the parts can't be
    /// created, some of the ItemCollections may be registered and usable even if false is
    /// returned
    /// </summary>
    public bool TryLoadAllMetadata(string inputFile, out MetadataWorkspace metadataWorkspace)
    {
        metadataWorkspace = new MetadataWorkspace();

        EdmItemCollection edmItemCollection = CreateEdmItemCollection(inputFile);
        metadataWorkspace.RegisterItemCollection(edmItemCollection);

        StoreItemCollection storeItemCollection = null;
        if (TryCreateStoreItemCollection(inputFile, out storeItemCollection))
        {
            StorageMappingItemCollection storageMappingItemCollection = null;
            if (TryCreateStorageMappingItemCollection(inputFile, edmItemCollection, storeItemCollection, out storageMappingItemCollection))
            {
                metadataWorkspace.RegisterItemCollection(storeItemCollection);
                metadataWorkspace.RegisterItemCollection(storageMappingItemCollection);
                return true;
            }
        }

        return false;
    }

    /// <summary>
    /// Create an EdmItemCollection loaded with the metadata provided
    /// </summary>
    public EdmItemCollection CreateEdmItemCollection(string sourcePath, params string[] referenceSchemas)
    {
        EdmItemCollection edmItemCollection;
        if(TryCreateEdmItemCollection(sourcePath, referenceSchemas, out edmItemCollection))
        {
            return edmItemCollection;
        }

        return new EdmItemCollection();
    }

    /// <summary>
    /// Attempts to create a EdmItemCollection from the specified metadata file
    /// </summary>
    public bool TryCreateEdmItemCollection(string sourcePath, out EdmItemCollection edmItemCollection)
    {
        return TryCreateEdmItemCollection(sourcePath, null, out edmItemCollection);
    }

    /// <summary>
    /// Attempts to create a EdmItemCollection from the specified metadata file
    /// </summary>
    public bool TryCreateEdmItemCollection(string sourcePath, string[] referenceSchemas, out EdmItemCollection edmItemCollection)
    {
        edmItemCollection = null;

        if (!ValidateInputPath(sourcePath, _textTransformation))
        {
            return false;
        }

        if (referenceSchemas == null)
        {
            referenceSchemas = new string[0];
        }

        ItemCollection itemCollection = null;
        sourcePath = _textTransformation.Host.ResolvePath(sourcePath);
        EdmItemCollectionBuilder collectionBuilder = new EdmItemCollectionBuilder(_textTransformation, referenceSchemas.Select(s => _textTransformation.Host.ResolvePath(s)).Where(s => s != sourcePath));
        if (collectionBuilder.TryCreateItemCollection(sourcePath, out itemCollection))
        {
            edmItemCollection = (EdmItemCollection)itemCollection;
        }

        return edmItemCollection != null;
    }

    /// <summary>
    /// Attempts to create a StoreItemCollection from the specified metadata file
    /// </summary>
    public bool TryCreateStoreItemCollection(string sourcePath, out StoreItemCollection storeItemCollection)
    {
        storeItemCollection = null;

        if (!ValidateInputPath(sourcePath, _textTransformation))
        {
            return false;
        }

        ItemCollection itemCollection = null;
        StoreItemCollectionBuilder collectionBuilder = new StoreItemCollectionBuilder(_textTransformation);
        if (collectionBuilder.TryCreateItemCollection(_textTransformation.Host.ResolvePath(sourcePath), out itemCollection))
        {
            storeItemCollection = (StoreItemCollection)itemCollection;
        }
        return storeItemCollection != null;
    }

    /// <summary>
    /// Attempts to create a StorageMappingItemCollection from the specified metadata file, EdmItemCollection, and StoreItemCollection
    /// </summary>
    public bool TryCreateStorageMappingItemCollection(string sourcePath, EdmItemCollection edmItemCollection, StoreItemCollection storeItemCollection, out StorageMappingItemCollection storageMappingItemCollection)
    {
        storageMappingItemCollection = null;

        if (!ValidateInputPath(sourcePath, _textTransformation))
        {
            return false;
        }

        if (edmItemCollection == null)
        {
            throw new ArgumentNullException("edmItemCollection");
        }

        if (storeItemCollection == null)
        {
            throw new ArgumentNullException("storeItemCollection");
        }

        ItemCollection itemCollection = null;
        StorageMappingItemCollectionBuilder collectionBuilder = new StorageMappingItemCollectionBuilder(_textTransformation, edmItemCollection, storeItemCollection);
        if (collectionBuilder.TryCreateItemCollection(_textTransformation.Host.ResolvePath(sourcePath), out itemCollection))
        {
            storageMappingItemCollection = (StorageMappingItemCollection)itemCollection;
        }
        return storageMappingItemCollection != null;
    }

    /// <summary>
    /// Gets the Model Namespace from the provided schema file.
    /// </summary>
    public string GetModelNamespace(string sourcePath)
    {
        if (!ValidateInputPath(sourcePath, _textTransformation))
        {
            return String.Empty;
        }

        EdmItemCollectionBuilder builder = new EdmItemCollectionBuilder(_textTransformation);
        XElement model;
        if(builder.TryLoadRootElement(_textTransformation.Host.ResolvePath(sourcePath), out model))
        {
            XAttribute attribute = model.Attribute("Namespace");
            if (attribute != null)
            {
                return attribute.Value;
            }
        }

        return String.Empty;
    }

    /// <summary>
    /// Returns true if the specified file path is valid
    /// </summary>
    private static bool ValidateInputPath(string sourcePath, DynamicTextTransformation textTransformation)
    {
        if (String.IsNullOrEmpty(sourcePath))
        {
            throw new ArgumentException("sourcePath");
        }

        if(sourcePath == "$edmxInputFile$")
        {
            textTransformation.Errors.Add(new CompilerError(textTransformation.Host.TemplateFile ?? CodeGenerationTools.GetResourceString("Template_CurrentlyRunningTemplate"), -1, -1, string.Empty,
                CodeGenerationTools.GetResourceString("Template_ReplaceVsItemTemplateToken")));
            return false;
        }

        return true;
    }

    /// <summary>
    /// Base class for ItemCollectionBuilder classes that
    /// loads the specific types of metadata
    /// </summary>
    private abstract class ItemCollectionBuilder
    {
        private readonly DynamicTextTransformation _textTransformation;
        private readonly string _fileExtension;
        private readonly string _edmxSectionName;
        private readonly string  _rootElementName;

        /// <summary>
        /// FileExtension for individual (non-edmx) metadata file for this
        /// specific ItemCollection type
        /// </summary>
        public string FileExtension
        {
            get { return _fileExtension; }
        }

        /// <summary>
        /// The name of the XmlElement in the .edmx <Runtime> element
        /// to find this ItemCollection's metadata
        /// </summary>
        public string EdmxSectionName
        {
            get { return _edmxSectionName; }
        }

        /// <summary>
        /// The name of the root element of this ItemCollection's metadata
        /// </summary>
        public string RootElementName
        {
            get { return _rootElementName; }
        }

        /// <summary>
        /// Method to build the appropriate ItemCollection
        /// </summary>
        protected abstract ItemCollection CreateItemCollection(IEnumerable<XmlReader> readers, out IList<EdmSchemaError> errors);

        /// <summary>
        /// Ctor to setup the ItemCollectionBuilder members
        /// </summary>
        protected ItemCollectionBuilder(DynamicTextTransformation textTransformation, string fileExtension, string edmxSectionName, string rootElementName)
        {
            _textTransformation = textTransformation;
            _fileExtension = fileExtension;
            _edmxSectionName = edmxSectionName;
            _rootElementName = rootElementName;
        }

        /// <summary>
        /// Selects a namespace from the supplied constants.
        /// </summary>
        protected abstract string GetNamespace(SchemaConstants constants);

        /// <summary>
        /// Try to create an ItemCollection loaded with the metadata provided
        /// </summary>
        public bool TryCreateItemCollection(string sourcePath, out ItemCollection itemCollection)
        {
            itemCollection = null;

            if (!ValidateInputPath(sourcePath, _textTransformation))
            {
                return false;
            }

            XElement schemaElement = null;
            if (TryLoadRootElement(sourcePath, out schemaElement))
            {
                List<XmlReader> readers = new List<XmlReader>();
                try
                {
                    readers.Add(schemaElement.CreateReader());
                    IList<EdmSchemaError> errors = null;

                    ItemCollection tempItemCollection = CreateItemCollection(readers, out errors);
                    if (ProcessErrors(errors, sourcePath))
                    {
                        return false;
                    }

                    itemCollection = tempItemCollection;
                    return true;
                }
                finally
                {
                    foreach (XmlReader reader in readers)
                    {
                        ((IDisposable)reader).Dispose();
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// Tries to load the root element from the metadata file provided
        /// </summary>
        public bool TryLoadRootElement(string sourcePath, out XElement schemaElement)
        {
            schemaElement = null;
            string extension = Path.GetExtension(sourcePath);
            if (extension.Equals(".edmx", StringComparison.InvariantCultureIgnoreCase))
            {
                return TryLoadRootElementFromEdmx(sourcePath, out schemaElement);
            }
            else if(extension.Equals(FileExtension, StringComparison.InvariantCultureIgnoreCase))
            {
                // load from single metadata file (.csdl, .ssdl, or .msl)
                schemaElement = XElement.Load(sourcePath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo);
                return true;
            }

            return false;
        }

        /// <summary>
        /// Tries to load the root element from the provided edmxDocument
        /// </summary>
        private bool TryLoadRootElementFromEdmx(XElement edmxDocument, SchemaConstants schemaConstants, string sectionName, string rootElementName, out XElement rootElement)
        {
            rootElement = null;

            XNamespace edmxNs = schemaConstants.EdmxNamespace;
            XNamespace sectionNs = GetNamespace(schemaConstants);

            XElement runtime = edmxDocument.Element(edmxNs  + "Runtime");
            if (runtime == null)
            {
                return false;
            }

            XElement section = runtime.Element(edmxNs + sectionName);
            if (section == null)
            {
                return false;
            }

            string templateVersion;

            if (!TemplateMetadata.TryGetValue(MetadataConstants.TT_TEMPLATE_VERSION, out templateVersion))
            {
                templateVersion = MetadataConstants.DEFAULT_TEMPLATE_VERSION;
            }

            if (schemaConstants.MinimumTemplateVersion > new Version(templateVersion))
            {
                _textTransformation.Errors.Add(new CompilerError(
                    _textTransformation.Host.TemplateFile ?? CodeGenerationTools.GetResourceString("Template_CurrentlyRunningTemplate"), -1, -1, string.Empty,
                        CodeGenerationTools.GetResourceString("Template_UnsupportedSchema"))
                {IsWarning = true});
            }

            rootElement = section.Element(sectionNs + rootElementName);
            return rootElement != null;
        }

        /// <summary>
        /// Tries to load the root element from the provided .edmx metadata file
        /// </summary>
        private bool TryLoadRootElementFromEdmx(string edmxPath, out XElement rootElement)
        {
            rootElement = null;

            XElement element = XElement.Load(edmxPath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo);

            return TryLoadRootElementFromEdmx(element, MetadataConstants.V3_SCHEMA_CONSTANTS, EdmxSectionName, RootElementName, out rootElement)
                || TryLoadRootElementFromEdmx(element, MetadataConstants.V2_SCHEMA_CONSTANTS, EdmxSectionName, RootElementName, out rootElement)
                || TryLoadRootElementFromEdmx(element, MetadataConstants.V1_SCHEMA_CONSTANTS, EdmxSectionName, RootElementName, out rootElement);
        }

        /// <summary>
        /// Takes an Enumerable of EdmSchemaErrors, and adds them
        /// to the errors collection of the template class
        /// </summary>
        private bool ProcessErrors(IEnumerable<EdmSchemaError> errors, string sourceFilePath)
        {
            bool foundErrors = false;
            foreach (EdmSchemaError error in errors)
            {
                CompilerError newError = new CompilerError(error.SchemaLocation, error.Line, error.Column,
                                                 error.ErrorCode.ToString(CultureInfo.InvariantCulture),
                                                 error.Message);
                newError.IsWarning = error.Severity == EdmSchemaErrorSeverity.Warning;
                foundErrors |= error.Severity == EdmSchemaErrorSeverity.Error;
                if (error.SchemaLocation == null)
                {
                    newError.FileName = sourceFilePath;
                }
                _textTransformation.Errors.Add(newError);
            }

            return foundErrors;
        }
    }

    /// <summary>
    /// Builder class for creating a StorageMappingItemCollection
    /// </summary>
    private class StorageMappingItemCollectionBuilder : ItemCollectionBuilder
    {
        private readonly EdmItemCollection _edmItemCollection;
        private readonly StoreItemCollection _storeItemCollection;

        public StorageMappingItemCollectionBuilder(DynamicTextTransformation textTransformation, EdmItemCollection edmItemCollection, StoreItemCollection storeItemCollection)
            : base(textTransformation, MetadataConstants.MSL_EXTENSION, MetadataConstants.MSL_EDMX_SECTION_NAME, MetadataConstants.MSL_ROOT_ELEMENT_NAME)
        {
            _edmItemCollection = edmItemCollection;
            _storeItemCollection = storeItemCollection;
        }

        protected override ItemCollection CreateItemCollection(IEnumerable<XmlReader> readers, out IList<EdmSchemaError> errors)
        {
            return MetadataItemCollectionFactory.CreateStorageMappingItemCollection(_edmItemCollection, _storeItemCollection, readers, out errors);
        }

        /// <summary>
        /// Selects a namespace from the supplied constants.
        /// </summary>
        protected override string GetNamespace(SchemaConstants constants)
        {
            return constants.MslNamespace;
        }
    }

    /// <summary>
    /// Builder class for creating a StoreItemCollection
    /// </summary>
    private class StoreItemCollectionBuilder : ItemCollectionBuilder
    {
        public StoreItemCollectionBuilder(DynamicTextTransformation textTransformation)
            : base(textTransformation, MetadataConstants.SSDL_EXTENSION, MetadataConstants.SSDL_EDMX_SECTION_NAME, MetadataConstants.SSDL_ROOT_ELEMENT_NAME)
        {
        }

        protected override ItemCollection CreateItemCollection(IEnumerable<XmlReader> readers, out IList<EdmSchemaError> errors)
        {
            return MetadataItemCollectionFactory.CreateStoreItemCollection(readers, out errors);
        }

        /// <summary>
        /// Selects a namespace from the supplied constants.
        /// </summary>
        protected override string GetNamespace(SchemaConstants constants)
        {
            return constants.SsdlNamespace;
        }
    }

    /// <summary>
    /// Builder class for creating a EdmItemCollection
    /// </summary>
    private class EdmItemCollectionBuilder : ItemCollectionBuilder
    {
        private List<string> _referenceSchemas = new List<string>();

        public EdmItemCollectionBuilder(DynamicTextTransformation textTransformation)
            : base(textTransformation, MetadataConstants.CSDL_EXTENSION, MetadataConstants.CSDL_EDMX_SECTION_NAME, MetadataConstants.CSDL_ROOT_ELEMENT_NAME)
        {
        }

        public EdmItemCollectionBuilder(DynamicTextTransformation textTransformation, IEnumerable<string> referenceSchemas)
            : this(textTransformation)
        {
            _referenceSchemas.AddRange(referenceSchemas);
        }

        protected override ItemCollection CreateItemCollection(IEnumerable<XmlReader> readers, out IList<EdmSchemaError> errors)
        {
            List<XmlReader> ownedReaders = new List<XmlReader>();
            List<XmlReader> allReaders = new List<XmlReader>();
            try
            {
                allReaders.AddRange(readers);
                foreach (string path in _referenceSchemas.Distinct())
                {
                    XElement reference;
                    if(TryLoadRootElement(path, out reference))
                    {
                        XmlReader reader = reference.CreateReader();
                        allReaders.Add(reader);
                        ownedReaders.Add(reader);
                    }
                }

                return MetadataItemCollectionFactory.CreateEdmItemCollection(allReaders, out errors);
            }
            finally
            {
                foreach (XmlReader reader in ownedReaders)
                {
                    ((IDisposable)reader).Dispose();
                }
            }
        }

        /// <summary>
        /// Selects a namespace from the supplied constants.
        /// </summary>
        protected override string GetNamespace(SchemaConstants constants)
        {
            return constants.CsdlNamespace;
        }
    }
}

/// <summary>
/// Responsible for encapsulating the retrieval and translation of the CodeGeneration
/// annotations in the EntityFramework Metadata to a form that is useful in code generation.
/// </summary>
public static class Accessibility
{
    private const string GETTER_ACCESS = "http://schemas.microsoft.com/ado/2006/04/codegeneration:GetterAccess";
    private const string SETTER_ACCESS = "http://schemas.microsoft.com/ado/2006/04/codegeneration:SetterAccess";
    private const string TYPE_ACCESS = "http://schemas.microsoft.com/ado/2006/04/codegeneration:TypeAccess";
    private const string METHOD_ACCESS = "http://schemas.microsoft.com/ado/2006/04/codegeneration:MethodAccess";
    private const string ACCESS_PROTECTED = "Protected";
    private const string ACCESS_INTERNAL = "Internal";
    private const string ACCESS_PRIVATE = "Private";
    private static readonly Dictionary<string, int> AccessibilityRankIdLookup = new Dictionary<string, int>
        {
            { "private", 1},
            { "internal", 2},
            { "protected", 3},
            { "public", 4},
        };

    /// <summary>
    /// Gets the accessibility that should be applied to a type being generated from the provided GlobalItem.
    ///
    /// defaults to public if no annotation is found.
    /// </summary>
    public static string ForType(GlobalItem item)
    {
        if (item == null)
        {
            return null;
        }

        return GetAccessibility(item, TYPE_ACCESS);
    }

    /// <summary>
    /// Gets the accessibility that should be applied at the property level for a property being
    /// generated from the provided EdmMember.
    ///
    /// defaults to public if no annotation is found.
    /// </summary>
    public static string ForProperty(EdmMember member)
    {
        if (member == null)
        {
            return null;
        }

        string getterAccess, setterAccess, propertyAccess;
        CalculatePropertyAccessibility(member, out propertyAccess, out getterAccess, out setterAccess);
        return propertyAccess;
    }

    /// <summary>
    /// Gets the accessibility that should be applied at the property level for a Read-Only property being
    /// generated from the provided EdmMember.
    ///
    /// defaults to public if no annotation is found.
    /// </summary>
    public static string ForReadOnlyProperty(EdmMember member)
    {
        if (member == null)
        {
            return null;
        }

        return GetAccessibility(member, GETTER_ACCESS);
    }

    /// <summary>
    /// Gets the accessibility that should be applied at the property level for a property being
    /// generated from the provided EntitySet.
    ///
    /// defaults to public if no annotation is found.
    /// </summary>
    public static string ForReadOnlyProperty(EntitySet set)
    {
        if (set == null)
        {
            return null;
        }

        return GetAccessibility(set, GETTER_ACCESS);
    }

    /// <summary>
    /// Gets the accessibility that should be applied at the property level for a Write-Only property being
    /// generated from the provided EdmMember.
    ///
    /// defaults to public if no annotation is found.
    /// </summary>
    public static string ForWriteOnlyProperty(EdmMember member)
    {
        if (member == null)
        {
            return null;
        }

        return GetAccessibility(member, SETTER_ACCESS);
    }


    /// <summary>
    /// Gets the accessibility that should be applied at the get level for a property being
    /// generated from the provided EdmMember.
    ///
    /// defaults to empty if no annotation is found or the accessibility is the same as the property level.
    /// </summary>
    public static string ForGetter(EdmMember member)
    {
        if (member == null)
        {
            return null;
        }

        string getterAccess, setterAccess, propertyAccess;
        CalculatePropertyAccessibility(member, out propertyAccess, out getterAccess, out setterAccess);
        return getterAccess;
    }

    /// <summary>
    /// Gets the accessibility that should be applied at the set level for a property being
    /// generated from the provided EdmMember.
    ///
    /// defaults to empty if no annotation is found or the accessibility is the same as the property level.
    /// </summary>
    public static string ForSetter(EdmMember member)
    {
        if (member == null)
        {
            return null;
        }

        string getterAccess, setterAccess, propertyAccess;
        CalculatePropertyAccessibility(member, out propertyAccess, out getterAccess, out setterAccess);
        return setterAccess;
    }

    /// <summary>
    /// Gets the accessibility that should be applied to a method being generated from the provided EdmFunction.
    ///
    /// defaults to public if no annotation is found.
    /// </summary>
    public static string ForMethod(EdmFunction function)
    {
        if (function == null)
        {
            return null;
        }

        return GetAccessibility(function, METHOD_ACCESS);
    }

    private static void CalculatePropertyAccessibility(MetadataItem item,
        out string propertyAccessibility,
        out string getterAccessibility,
        out string setterAccessibility)
    {
        getterAccessibility = GetAccessibility(item, GETTER_ACCESS);
        int getterRank = AccessibilityRankIdLookup[getterAccessibility];

        setterAccessibility = GetAccessibility(item, SETTER_ACCESS);
        int setterRank = AccessibilityRankIdLookup[setterAccessibility];

        int propertyRank = Math.Max(getterRank, setterRank);
        if (setterRank == propertyRank)
        {
            setterAccessibility = String.Empty;
        }

        if (getterRank == propertyRank)
        {
            getterAccessibility = String.Empty;
        }

        propertyAccessibility = AccessibilityRankIdLookup.Where(v => v.Value == propertyRank).Select(v => v.Key).Single();
    }

    private static string GetAccessibility(MetadataItem item, string name)
    {
        string accessibility;
        if (MetadataTools.TryGetStringMetadataPropertySetting(item, name, out accessibility))
        {
            return TranslateUserAccessibilityToCSharpAccessibility(accessibility);
        }

        return "public";
    }

    private static string TranslateUserAccessibilityToCSharpAccessibility(string userAccessibility)
    {
        if (userAccessibility == ACCESS_PROTECTED)
        {
            return "protected";
        }
        else if (userAccessibility == ACCESS_INTERNAL)
        {
            return "internal";
        }
        else if (userAccessibility == ACCESS_PRIVATE)
        {
            return "private";
        }
        else
        {
            // default to public
            return "public";
        }
    }
}

/// <summary>
/// Responsible for creating source code regions in code when the loop inside
/// actually produces something.
/// </summary>
public class CodeRegion
{
    private const int STANDARD_INDENT_LENGTH = 4;

    private readonly DynamicTextTransformation _textTransformation;
    private int _beforeRegionLength;
    private int _emptyRegionLength;
    private int _regionIndentLevel = -1;

    /// <summary>
    /// Initializes an CodeRegion instance with the
    /// TextTransformation (T4 generated class) that is currently running
    /// </summary>
    public CodeRegion(object textTransformation)
    {
        if (textTransformation == null)
        {
            throw new ArgumentNullException("textTransformation");
        }

        _textTransformation = DynamicTextTransformation.Create(textTransformation);
    }

    /// <summary>
    /// Initializes an CodeRegion instance with the
    /// TextTransformation (T4 generated class) that is currently running,
    /// and the indent level to start the first region at.
    /// </summary>
    public CodeRegion(object textTransformation, int firstIndentLevel)
        : this(textTransformation)
    {
        if (firstIndentLevel < 0)
        {
            throw new ArgumentException("firstIndentLevel");
        }

        _regionIndentLevel = firstIndentLevel - 1;
    }

    /// <summary>
    /// Starts the begining of a region
    /// </summary>
    public void Begin(string regionName)
    {
        if (regionName == null)
        {
            throw new ArgumentNullException("regionName");
        }

        Begin(regionName, 1);
    }

    /// <summary>
    /// Start the begining of a region, indented
    /// the numbers of levels specified
    /// </summary>
    public void Begin(string regionName, int levelsToIncreaseIndent)
    {
        if (regionName == null)
        {
            throw new ArgumentNullException("regionName");
        }

        _beforeRegionLength = _textTransformation.GenerationEnvironment.Length;
        _regionIndentLevel += levelsToIncreaseIndent;
        _textTransformation.Write(GetIndent(_regionIndentLevel));
        _textTransformation.WriteLine("#region " + regionName);
        _emptyRegionLength = _textTransformation.GenerationEnvironment.Length;
    }

    /// <summary>
    /// Ends a region, or totaly removes it if nothing
    /// was generted since the begining of the region.
    /// </summary>
    public void End()
    {
        End(1);
    }

    /// <summary>
    /// Ends a region, or totaly removes it if nothing
    /// was generted since the begining of the region, also outdents
    /// the number of levels specified.
    /// </summary>
    public void End(int levelsToDecrease)
    {
        int indentLevel = _regionIndentLevel;
        _regionIndentLevel -= levelsToDecrease;

        if (_emptyRegionLength == _textTransformation.GenerationEnvironment.Length)
            _textTransformation.GenerationEnvironment.Length = _beforeRegionLength;
        else
        {
            _textTransformation.WriteLine(String.Empty);
            _textTransformation.Write(GetIndent(indentLevel));
            _textTransformation.WriteLine("#endregion");
            _textTransformation.WriteLine(String.Empty);
        }
    }

    /// <summary>
    /// Gets the current indent level that the next end region statement will be written
    /// at
    /// </summary>
    public int CurrentIndentLevel { get { return _regionIndentLevel; } }

    /// <summary>
    /// Get a string of spaces equivelent to the number of indents
    /// desired.
    /// </summary>
    public static string GetIndent(int indentLevel)
    {
        if (indentLevel < 0)
        {
            throw new ArgumentException("indentLevel");
        }

        return String.Empty.PadLeft(indentLevel * STANDARD_INDENT_LENGTH);
    }
}


/// <summary>
/// Responsible for collecting together the actual method parameters
/// and the parameters that need to be sent to the Execute method.
/// </summary>
public class FunctionImportParameter
{
    public FunctionParameter Source { get; set; }
    public string RawFunctionParameterName { get; set; }
    public string FunctionParameterName { get; set; }
    public string FunctionParameterType { get; set; }
    public string LocalVariableName { get; set; }
    public string RawClrTypeName { get; set; }
    public string ExecuteParameterName { get; set; }
    public string EsqlParameterName { get; set; }
    public bool NeedsLocalVariable { get; set; }
    public bool IsNullableOfT { get; set; }


    /// <summary>
    /// Creates a set of FunctionImportParameter objects from the parameters passed in.
    /// </summary>
    public static IEnumerable<FunctionImportParameter> Create(IEnumerable<FunctionParameter> parameters, CodeGenerationTools code, MetadataTools ef)
    {
        if (parameters == null)
        {
            throw new ArgumentNullException("parameters");
        }

        if (code == null)
        {
            throw new ArgumentNullException("code");
        }

        if (ef == null)
        {
            throw new ArgumentNullException("ef");
        }

        UniqueIdentifierService unique = new UniqueIdentifierService();
        List<FunctionImportParameter> importParameters = new List<FunctionImportParameter>();
        foreach (FunctionParameter parameter in parameters)
        {
            FunctionImportParameter importParameter = new FunctionImportParameter();
            importParameter.Source = parameter;
            importParameter.RawFunctionParameterName = unique.AdjustIdentifier(code.CamelCase(parameter.Name));
            importParameter.FunctionParameterName = code.Escape(importParameter.RawFunctionParameterName);
            if (parameter.Mode == ParameterMode.In)
            {
                TypeUsage typeUsage = parameter.TypeUsage;
                importParameter.NeedsLocalVariable = true;
                importParameter.FunctionParameterType = code.GetTypeName(typeUsage);
                importParameter.EsqlParameterName = parameter.Name;
                Type clrType = ef.UnderlyingClrType(parameter.TypeUsage.EdmType);
                importParameter.RawClrTypeName = typeUsage.EdmType is EnumType ? code.GetTypeName(typeUsage.EdmType) : code.Escape(clrType);
                importParameter.IsNullableOfT = clrType.IsValueType;
            }
            else
            {
                importParameter.NeedsLocalVariable = false;
                importParameter.FunctionParameterType = "ObjectParameter";
                importParameter.ExecuteParameterName = importParameter.FunctionParameterName;
            }
            importParameters.Add(importParameter);
        }

        // we save the local parameter uniquification for a second pass to make the visible parameters
        // as pretty and sensible as possible
        for (int i = 0; i < importParameters.Count; i++)
        {
            FunctionImportParameter importParameter = importParameters[i];
            if (importParameter.NeedsLocalVariable)
            {
                importParameter.LocalVariableName = unique.AdjustIdentifier(importParameter.RawFunctionParameterName + "Parameter");
                importParameter.ExecuteParameterName = importParameter.LocalVariableName;
            }
        }

        return importParameters;
    }

    //
    // Class to create unique variables within the same scope
    //
    private sealed class UniqueIdentifierService
    {
        private readonly HashSet<string> _knownIdentifiers;

        public UniqueIdentifierService()
        {
            _knownIdentifiers = new HashSet<string>(StringComparer.Ordinal);
        }

        /// <summary>
        /// Given an identifier, makes it unique within the scope by adding
        /// a suffix (1, 2, 3, ...), and returns the adjusted identifier.
        /// </summary>
        public string AdjustIdentifier(string identifier)
        {
            // find a unique name by adding suffix as necessary
            int numberOfConflicts = 0;
            string adjustedIdentifier = identifier;

            while (!_knownIdentifiers.Add(adjustedIdentifier))
            {
                ++numberOfConflicts;
                adjustedIdentifier = identifier + numberOfConflicts.ToString(CultureInfo.InvariantCulture);
            }

            return adjustedIdentifier;
        }
    }
}

/// <summary>
/// Responsible for marking the various sections of the generation,
/// so they can be split up into separate files
/// </summary>
public class EntityFrameworkTemplateFileManager
{
    /// <summary>
    /// Creates the VsEntityFrameworkTemplateFileManager if VS is detected, otherwise
    /// creates the file system version.
    /// </summary>
    public static EntityFrameworkTemplateFileManager Create(object textTransformation)
    {
        DynamicTextTransformation transformation = DynamicTextTransformation.Create(textTransformation);
        IDynamicHost host = transformation.Host;

#if !PREPROCESSED_TEMPLATE
        var hostServiceProvider = host.AsIServiceProvider();

        if (hostServiceProvider != null)
        {
            EnvDTE.DTE dte = (EnvDTE.DTE) hostServiceProvider.GetService(typeof(EnvDTE.DTE));

            if (dte != null)
            {
                return new VsEntityFrameworkTemplateFileManager(transformation);
            }
        }
#endif
        return new EntityFrameworkTemplateFileManager(transformation);
    }

    private sealed class Block
    {
        public String Name;
        public int Start, Length;
    }

    private readonly List<Block> files = new List<Block>();
    private readonly Block footer = new Block();
    private readonly Block header = new Block();
    private readonly DynamicTextTransformation _textTransformation;

    // reference to the GenerationEnvironment StringBuilder on the
    // TextTransformation object
    private readonly StringBuilder _generationEnvironment;

    private Block currentBlock;

    /// <summary>
    /// Initializes an EntityFrameworkTemplateFileManager Instance  with the
    /// TextTransformation (T4 generated class) that is currently running
    /// </summary>
    private EntityFrameworkTemplateFileManager(object textTransformation)
    {
        if (textTransformation == null)
        {
            throw new ArgumentNullException("textTransformation");
        }

        _textTransformation = DynamicTextTransformation.Create(textTransformation);
        _generationEnvironment = _textTransformation.GenerationEnvironment;
    }

    /// <summary>
    /// Marks the end of the last file if there was one, and starts a new
    /// and marks this point in generation as a new file.
    /// </summary>
    public void StartNewFile(string name)
    {
        if (name == null)
        {
            throw new ArgumentNullException("name");
        }

        CurrentBlock = new Block { Name = name };
    }

    public void StartFooter()
    {
        CurrentBlock = footer;
    }

    public void StartHeader()
    {
        CurrentBlock = header;
    }

    public void EndBlock()
    {
        if (CurrentBlock == null)
        {
            return;
        }

        CurrentBlock.Length = _generationEnvironment.Length - CurrentBlock.Start;

        if (CurrentBlock != header && CurrentBlock != footer)
        {
            files.Add(CurrentBlock);
        }

        currentBlock = null;
    }

    /// <summary>
    /// Produce the template output files.
    /// </summary>
    public virtual IEnumerable<string> Process(bool split = true)
    {
        var generatedFileNames = new List<string>();

        if (split)
        {
            EndBlock();

            var headerText = _generationEnvironment.ToString(header.Start, header.Length);
            var footerText = _generationEnvironment.ToString(footer.Start, footer.Length);
            var outputPath = Path.GetDirectoryName(_textTransformation.Host.TemplateFile);

            files.Reverse();

            foreach (var block in files)
            {
                var fileName = Path.Combine(outputPath, block.Name);
                var content = headerText + _generationEnvironment.ToString(block.Start, block.Length) + footerText;

                generatedFileNames.Add(fileName);
                CreateFile(fileName, content);
                _generationEnvironment.Remove(block.Start, block.Length);
            }
        }

        return generatedFileNames;
    }

    protected virtual void CreateFile(string fileName, string content)
    {
        if (IsFileContentDifferent(fileName, content))
        {
            File.WriteAllText(fileName, content);
        }
    }

    protected bool IsFileContentDifferent(String fileName, string newContent)
    {
        return !(File.Exists(fileName) && File.ReadAllText(fileName) == newContent);
    }

    private Block CurrentBlock
    {
        get { return currentBlock; }
        set
        {
            if (CurrentBlock != null)
            {
                EndBlock();
            }

            if (value != null)
            {
                value.Start = _generationEnvironment.Length;
            }

            currentBlock = value;
        }
    }

#if !PREPROCESSED_TEMPLATE
    private sealed class VsEntityFrameworkTemplateFileManager : EntityFrameworkTemplateFileManager
    {
        private EnvDTE.ProjectItem templateProjectItem;
        private EnvDTE.DTE dte;
        private Action<string> checkOutAction;
        private Action<IEnumerable<string>> projectSyncAction;

        /// <summary>
        /// Creates an instance of the VsEntityFrameworkTemplateFileManager class with the IDynamicHost instance
        /// </summary>
        public VsEntityFrameworkTemplateFileManager(object textTemplating)
            : base(textTemplating)
        {
            var hostServiceProvider = _textTransformation.Host.AsIServiceProvider();
            if (hostServiceProvider == null)
            {
                throw new ArgumentNullException("Could not obtain hostServiceProvider");
            }

            dte = (EnvDTE.DTE) hostServiceProvider.GetService(typeof(EnvDTE.DTE));
            if (dte == null)
            {
                throw new ArgumentNullException("Could not obtain DTE from host");
            }

            templateProjectItem = dte.Solution.FindProjectItem(_textTransformation.Host.TemplateFile);

            checkOutAction = fileName => dte.SourceControl.CheckOutItem(fileName);
            projectSyncAction = keepFileNames => ProjectSync(templateProjectItem, keepFileNames);
        }

        public override IEnumerable<string> Process(bool split)
        {
            if (templateProjectItem.ProjectItems == null)
            {
                return new List<string>();
            }

            var generatedFileNames = base.Process(split);

            projectSyncAction.EndInvoke(projectSyncAction.BeginInvoke(generatedFileNames, null, null));

            return generatedFileNames;
        }

        protected override void CreateFile(string fileName, string content)
        {
            if (IsFileContentDifferent(fileName, content))
            {
                CheckoutFileIfRequired(fileName);
                File.WriteAllText(fileName, content);
            }
        }

        private static void ProjectSync(EnvDTE.ProjectItem templateProjectItem, IEnumerable<string> keepFileNames)
        {
            var keepFileNameSet = new HashSet<string>(keepFileNames);
            var projectFiles = new Dictionary<string, EnvDTE.ProjectItem>();
            var originalOutput = Path.GetFileNameWithoutExtension(templateProjectItem.FileNames[0]);

            foreach (EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems)
            {
                projectFiles.Add(projectItem.FileNames[0], projectItem);
            }

            // Remove unused items from the project
            foreach (var pair in projectFiles)
            {
                if (!keepFileNames.Contains(pair.Key)
                    && !(Path.GetFileNameWithoutExtension(pair.Key) + ".").StartsWith(originalOutput + "."))
                {
                    pair.Value.Delete();
                }
            }

            // Add missing files to the project
            foreach (string fileName in keepFileNameSet)
            {
                if (!projectFiles.ContainsKey(fileName))
                {
                    templateProjectItem.ProjectItems.AddFromFile(fileName);
                }
            }
        }

        private void CheckoutFileIfRequired(string fileName)
        {
            if (dte.SourceControl == null
                || !dte.SourceControl.IsItemUnderSCC(fileName)
                    || dte.SourceControl.IsItemCheckedOut(fileName))
            {
                return;
            }

            // run on worker thread to prevent T4 calling back into VS
            checkOutAction.EndInvoke(checkOutAction.BeginInvoke(fileName, null, null));
        }
    }
#endif
}

/// <summary>
/// Responsible creating an instance that can be passed
/// to helper classes that need to access the TextTransformation
/// members.  It accesses member by name and signature rather than
/// by type.  This is necessary when the
/// template is being used in Preprocessed mode
/// and there is no common known type that can be
/// passed instead
/// </summary>
public class DynamicTextTransformation
{
    private object _instance;
    IDynamicHost _dynamicHost;

    private readonly MethodInfo _write;
    private readonly MethodInfo _writeLine;
    private readonly PropertyInfo _generationEnvironment;
    private readonly PropertyInfo _errors;
    private readonly PropertyInfo _host;

    /// <summary>
    /// Creates an instance of the DynamicTextTransformation class around the passed in
    /// TextTransformation shapped instance passed in, or if the passed in instance
    /// already is a DynamicTextTransformation, it casts it and sends it back.
    /// </summary>
    public static DynamicTextTransformation Create(object instance)
    {
        if (instance == null)
        {
            throw new ArgumentNullException("instance");
        }

        DynamicTextTransformation textTransformation = instance as DynamicTextTransformation;
        if (textTransformation != null)
        {
            return textTransformation;
        }

        return new DynamicTextTransformation(instance);
    }

    private DynamicTextTransformation(object instance)
    {
        _instance = instance;
        Type type = _instance.GetType();
        _write = type.GetMethod("Write", new Type[] { typeof(string) });
        _writeLine = type.GetMethod("WriteLine", new Type[] { typeof(string) });
        _generationEnvironment = type.GetProperty("GenerationEnvironment", BindingFlags.Instance | BindingFlags.NonPublic);
        _host = type.GetProperty("Host");
        _errors = type.GetProperty("Errors");
    }

    /// <summary>
    /// Gets the value of the wrapped TextTranformation instance's GenerationEnvironment property
    /// </summary>
    public StringBuilder GenerationEnvironment { get { return (StringBuilder)_generationEnvironment.GetValue(_instance, null); } }

    /// <summary>
    /// Gets the value of the wrapped TextTranformation instance's Errors property
    /// </summary>
    public System.CodeDom.Compiler.CompilerErrorCollection Errors { get { return (System.CodeDom.Compiler.CompilerErrorCollection)_errors.GetValue(_instance, null); } }

    /// <summary>
    /// Calls the wrapped TextTranformation instance's Write method.
    /// </summary>
    public void Write(string text)
    {
        _write.Invoke(_instance, new object[] { text });
    }

    /// <summary>
    /// Calls the wrapped TextTranformation instance's WriteLine method.
    /// </summary>
    public void WriteLine(string text)
    {
        _writeLine.Invoke(_instance, new object[] { text });
    }

    /// <summary>
    /// Gets the value of the wrapped TextTranformation instance's Host property
    /// if available (shows up when hostspecific is set to true in the template directive) and returns
    /// the appropriate implementation of IDynamicHost
    /// </summary>
    public IDynamicHost Host
    {
        get
        {
            if (_dynamicHost == null)
            {
                if(_host == null)
                {
                    _dynamicHost = new NullHost();
                }
                else
                {
                    _dynamicHost = new DynamicHost(_host.GetValue(_instance, null));
                }
            }
            return _dynamicHost;
        }
    }
}


/// <summary>
/// Reponsible for abstracting the use of Host between times
/// when it is available and not
/// </summary>
public interface IDynamicHost
{
    /// <summary>
    /// An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue
    /// </summary>
    string ResolveParameterValue(string id, string name, string otherName);

    /// <summary>
    /// An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath
    /// </summary>
    string ResolvePath(string path);

    /// <summary>
    /// An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile
    /// </summary>
    string TemplateFile { get; }

    /// <summary>
    /// Returns the Host instance cast as an IServiceProvider
    /// </summary>
    IServiceProvider AsIServiceProvider();
}

/// <summary>
/// Reponsible for implementing the IDynamicHost as a dynamic
/// shape wrapper over the Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost interface
/// rather than type dependent wrapper.  We don't use the
/// interface type so that the code can be run in preprocessed mode
/// on a .net framework only installed machine.
/// </summary>
public class DynamicHost : IDynamicHost
{
    private readonly object _instance;
    private readonly MethodInfo _resolveParameterValue;
    private readonly MethodInfo _resolvePath;
    private readonly PropertyInfo _templateFile;

    /// <summary>
    /// Creates an instance of the DynamicHost class around the passed in
    /// Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost shapped instance passed in.
    /// </summary>
    public DynamicHost(object instance)
    {
        _instance = instance;
        Type type = _instance.GetType();
        _resolveParameterValue = type.GetMethod("ResolveParameterValue", new Type[] { typeof(string), typeof(string), typeof(string) });
        _resolvePath = type.GetMethod("ResolvePath", new Type[] { typeof(string) });
        _templateFile = type.GetProperty("TemplateFile");

    }

    /// <summary>
    /// A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue
    /// </summary>
    public string ResolveParameterValue(string id, string name, string otherName)
    {
        return (string)_resolveParameterValue.Invoke(_instance, new object[] { id, name, otherName });
    }

    /// <summary>
    /// A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath
    /// </summary>
    public string ResolvePath(string path)
    {
        return (string)_resolvePath.Invoke(_instance, new object[] { path });
    }

    /// <summary>
    /// A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile
    /// </summary>
    public string TemplateFile
    {
        get
        {
            return (string)_templateFile.GetValue(_instance, null);
        }
    }

    /// <summary>
    /// Returns the Host instance cast as an IServiceProvider
    /// </summary>
    public IServiceProvider AsIServiceProvider()
    {
        return _instance as IServiceProvider;
    }
}

/// <summary>
/// Reponsible for implementing the IDynamicHost when the
/// Host property is not available on the TextTemplating type. The Host
/// property only exists when the hostspecific attribute of the template
/// directive is set to true.
/// </summary>
public class NullHost : IDynamicHost
{
    /// <summary>
    /// An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue
    /// that simply retuns null.
    /// </summary>
    public string ResolveParameterValue(string id, string name, string otherName)
    {
        return null;
    }

    /// <summary>
    /// An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath
    /// that simply retuns the path passed in.
    /// </summary>
    public string ResolvePath(string path)
    {
        return path;
    }

    /// <summary>
    /// An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile
    /// that returns null.
    /// </summary>
    public string TemplateFile
    {
        get
        {
            return null;
        }
    }

    /// <summary>
    /// Returns null.
    /// </summary>
    public IServiceProvider AsIServiceProvider()
    {
        return null;
    }
}

/// <summary>
/// Responsible for encapsulating the constants defined in Metadata
/// </summary>
public static class MetadataConstants
{
    public const string CSDL_EXTENSION = ".csdl";

    public const string CSDL_EDMX_SECTION_NAME = "ConceptualModels";
    public const string CSDL_ROOT_ELEMENT_NAME = "Schema";
    public const string EDM_ANNOTATION_09_02 = "http://schemas.microsoft.com/ado/2009/02/edm/annotation";

    public const string SSDL_EXTENSION = ".ssdl";

    public const string SSDL_EDMX_SECTION_NAME = "StorageModels";
    public const string SSDL_ROOT_ELEMENT_NAME = "Schema";

    public const string MSL_EXTENSION = ".msl";

    public const string MSL_EDMX_SECTION_NAME = "Mappings";
    public const string MSL_ROOT_ELEMENT_NAME = "Mapping";

    public const string TT_TEMPLATE_NAME = "TemplateName";
    public const string TT_TEMPLATE_VERSION = "TemplateVersion";
    public const string TT_MINIMUM_ENTITY_FRAMEWORK_VERSION = "MinimumEntityFrameworkVersion";

    public const string DEFAULT_TEMPLATE_VERSION = "4.0";

    public static readonly SchemaConstants V1_SCHEMA_CONSTANTS = new SchemaConstants(
        "http://schemas.microsoft.com/ado/2007/06/edmx",
        "http://schemas.microsoft.com/ado/2006/04/edm",
        "http://schemas.microsoft.com/ado/2006/04/edm/ssdl",
        "urn:schemas-microsoft-com:windows:storage:mapping:CS",
        new Version("3.5"));

    public static readonly SchemaConstants V2_SCHEMA_CONSTANTS = new SchemaConstants(
        "http://schemas.microsoft.com/ado/2008/10/edmx",
        "http://schemas.microsoft.com/ado/2008/09/edm",
        "http://schemas.microsoft.com/ado/2009/02/edm/ssdl",
        "http://schemas.microsoft.com/ado/2008/09/mapping/cs",
        new Version("4.0"));

    public static readonly SchemaConstants V3_SCHEMA_CONSTANTS = new SchemaConstants(
        "http://schemas.microsoft.com/ado/2009/11/edmx",
        "http://schemas.microsoft.com/ado/2009/11/edm",
        "http://schemas.microsoft.com/ado/2009/11/edm/ssdl",
        "http://schemas.microsoft.com/ado/2009/11/mapping/cs",
        new Version("5.0"));
}

public struct SchemaConstants
{
    public SchemaConstants(string edmxNamespace, string csdlNamespace, string ssdlNamespace, string mslNamespace, Version minimumTemplateVersion) : this()
    {
        EdmxNamespace = edmxNamespace;
        CsdlNamespace = csdlNamespace;
        SsdlNamespace = ssdlNamespace;
        MslNamespace = mslNamespace;
        MinimumTemplateVersion = minimumTemplateVersion;
    }

    public string EdmxNamespace { get; private set; }
    public string CsdlNamespace { get; private set; }
    public string SsdlNamespace { get; private set; }
    public string MslNamespace { get; private set; }
    public Version MinimumTemplateVersion { get; private set; }
}


    }


    #region Base class
    /// <summary>
    /// Base class for this transformation
    /// </summary>
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "11.0.0.0")]
    public class CSharpCodeGenTemplateV50Base
    {
        #region Fields
        private global::System.Text.StringBuilder generationEnvironmentField;
        private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField;
        private global::System.Collections.Generic.List<int> indentLengthsField;
        private string currentIndentField = "";
        private bool endsWithNewline;
        private global::System.Collections.Generic.IDictionary<string, object> sessionField;
        #endregion
        #region Properties
        /// <summary>
        /// The string builder that generation-time code is using to assemble generated output
        /// </summary>
        protected System.Text.StringBuilder GenerationEnvironment
        {
            get
            {
                if ((this.generationEnvironmentField == null))
                {
                    this.generationEnvironmentField = new global::System.Text.StringBuilder();
                }
                return this.generationEnvironmentField;
            }
            set
            {
                this.generationEnvironmentField = value;
            }
        }
        /// <summary>
        /// The error collection for the generation process
        /// </summary>
        public System.CodeDom.Compiler.CompilerErrorCollection Errors
        {
            get
            {
                if ((this.errorsField == null))
                {
                    this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection();
                }
                return this.errorsField;
            }
        }
        /// <summary>
        /// A list of the lengths of each indent that was added with PushIndent
        /// </summary>
        private System.Collections.Generic.List<int> indentLengths
        {
            get
            {
                if ((this.indentLengthsField == null))
                {
                    this.indentLengthsField = new global::System.Collections.Generic.List<int>();
                }
                return this.indentLengthsField;
            }
        }
        /// <summary>
        /// Gets the current indent we use when adding lines to the output
        /// </summary>
        public string CurrentIndent
        {
            get
            {
                return this.currentIndentField;
            }
        }
        /// <summary>
        /// Current transformation session
        /// </summary>
        public virtual global::System.Collections.Generic.IDictionary<string, object> Session
        {
            get
            {
                return this.sessionField;
            }
            set
            {
                this.sessionField = value;
            }
        }
        #endregion
        #region Transform-time helpers
        /// <summary>
        /// Write text directly into the generated output
        /// </summary>
        public void Write(string textToAppend)
        {
            if (string.IsNullOrEmpty(textToAppend))
            {
                return;
            }
            // If we're starting off, or if the previous text ended with a newline,
            // we have to append the current indent first.
            if (((this.GenerationEnvironment.Length == 0) 
                        || this.endsWithNewline))
            {
                this.GenerationEnvironment.Append(this.currentIndentField);
                this.endsWithNewline = false;
            }
            // Check if the current text ends with a newline
            if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
            {
                this.endsWithNewline = true;
            }
            // This is an optimization. If the current indent is "", then we don't have to do any
            // of the more complex stuff further down.
            if ((this.currentIndentField.Length == 0))
            {
                this.GenerationEnvironment.Append(textToAppend);
                return;
            }
            // Everywhere there is a newline in the text, add an indent after it
            textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
            // If the text ends with a newline, then we should strip off the indent added at the very end
            // because the appropriate indent will be added when the next time Write() is called
            if (this.endsWithNewline)
            {
                this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
            }
            else
            {
                this.GenerationEnvironment.Append(textToAppend);
            }
        }
        /// <summary>
        /// Write text directly into the generated output
        /// </summary>
        public void WriteLine(string textToAppend)
        {
            this.Write(textToAppend);
            this.GenerationEnvironment.AppendLine();
            this.endsWithNewline = true;
        }
        /// <summary>
        /// Write formatted text directly into the generated output
        /// </summary>
        public void Write(string format, params object[] args)
        {
            this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
        }
        /// <summary>
        /// Write formatted text directly into the generated output
        /// </summary>
        public void WriteLine(string format, params object[] args)
        {
            this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
        }
        /// <summary>
        /// Raise an error
        /// </summary>
        public void Error(string message)
        {
            System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
            error.ErrorText = message;
            this.Errors.Add(error);
        }
        /// <summary>
        /// Raise a warning
        /// </summary>
        public void Warning(string message)
        {
            System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
            error.ErrorText = message;
            error.IsWarning = true;
            this.Errors.Add(error);
        }
        /// <summary>
        /// Increase the indent
        /// </summary>
        public void PushIndent(string indent)
        {
            if ((indent == null))
            {
                throw new global::System.ArgumentNullException("indent");
            }
            this.currentIndentField = (this.currentIndentField + indent);
            this.indentLengths.Add(indent.Length);
        }
        /// <summary>
        /// Remove the last indent that was added with PushIndent
        /// </summary>
        public string PopIndent()
        {
            string returnValue = "";
            if ((this.indentLengths.Count > 0))
            {
                int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
                this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
                if ((indentLength > 0))
                {
                    returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
                    this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
                }
            }
            return returnValue;
        }
        /// <summary>
        /// Remove any indentation
        /// </summary>
        public void ClearIndent()
        {
            this.indentLengths.Clear();
            this.currentIndentField = "";
        }
        #endregion
        #region ToString Helpers
        /// <summary>
        /// Utility class to produce culture-oriented representation of an object as a string.
        /// </summary>
        public class ToStringInstanceHelper
        {
            private System.IFormatProvider formatProviderField  = global::System.Globalization.CultureInfo.InvariantCulture;
            /// <summary>
            /// Gets or sets format provider to be used by ToStringWithCulture method.
            /// </summary>
            public System.IFormatProvider FormatProvider
            {
                get
                {
                    return this.formatProviderField ;
                }
                set
                {
                    if ((value != null))
                    {
                        this.formatProviderField  = value;
                    }
                }
            }
            /// <summary>
            /// This is called from the compile/run appdomain to convert objects within an expression block to a string
            /// </summary>
            public string ToStringWithCulture(object objectToConvert)
            {
                if ((objectToConvert == null))
                {
                    throw new global::System.ArgumentNullException("objectToConvert");
                }
                System.Type t = objectToConvert.GetType();
                System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
                            typeof(System.IFormatProvider)});
                if ((method == null))
                {
                    return objectToConvert.ToString();
                }
                else
                {
                    return ((string)(method.Invoke(objectToConvert, new object[] {
                                this.formatProviderField })));
                }
            }
        }
        private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper();
        /// <summary>
        /// Helper to produce culture-oriented representation of an object as a string
        /// </summary>
        public ToStringInstanceHelper ToStringHelper
        {
            get
            {
                return this.toStringHelperField;
            }
        }
        #endregion
    }
    #endregion
}
�
Imports System
Imports System.Linq
Imports System.IO
Imports System.Collections.Generic
Imports System.Data.Objects
Imports System.Data.Objects.DataClasses
Imports System.Xml
Imports System.Xml.Linq
Imports System.Globalization
Imports System.Reflection
Imports System.Data.Metadata.Edm
Imports System.Data.Mapping
Imports System.Data.Entity.Design
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports Microsoft.VisualBasic
Imports System.Text

'------------------------------------------------------------------------------
'<auto-generated>
'    This code was generated by a tool.
'    Runtime Version: 11.0.0.0
' 
'    Changes to this file may cause incorrect behavior and will be lost if
'    the code is regenerated.
'</auto-generated>
'------------------------------------------------------------------------------
Namespace TemplateCodeGenerators
    '''<summary>
    '''Class to produce the template output
    '''</summary>
    <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "11.0.0.0")>  _
    Partial Public Class VBCodeGenTemplate
        Inherits VBCodeGenTemplateBase
        '''<summary>
        '''Create the template output
        '''</summary>
        Public Overridable Function TransformText() As String


' 
' 
' 
'
' 
' 
' 
' 
' 
' 
' 
' 
'
' 
' 
' 
' 




DefineMetadata()

    Dim userSettings As UserSettings =
        New UserSettings With _
        { _
            .SourceCsdlPath = "$edmxInputFile$", _
            .ReferenceCsdlPaths = New string () {}, _
            .FullyQualifySystemTypes = True, _
            .CreateContextAddToMethods = True, _
            .CamelCaseFields = False _
        }

ApplyUserSettings(userSettings)
If Errors.HasErrors
    Return String.Empty
End If
Dim loader As New MetadataLoader(Me)
Dim ef As New MetadataTools(Me)
Dim region As New CodeRegion(Me)
Dim code As New CodeGenerationTools(Me) With {.FullyQualifySystemTypes = userSettings.FullyQualifySystemTypes, .CamelCaseFields = userSettings.CamelCaseFields}

ItemCollection = loader.CreateEdmItemCollection(SourceCsdlPath, ReferenceCsdlPaths.ToArray())
ModelNamespace = loader.GetModelNamespace(SourceCsdlPath)
Dim namespaceName As String = GetNamespaceName(code)
UpdateObjectNamespaceMap(namespaceName)

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"'------------------------------------------------------------------------------"& _ 
                    ""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"' <auto-generated>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(GetResourceString("Template_GeneratedCodeCommentLine1")))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"'"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(GetResourceString("Template_GeneratedCodeCommentLine2")))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(GetResourceString("Template_GeneratedCodeCommentLine3")))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"' </auto-generated>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"'---------------------------------------------------------"& _ 
                    "---------------------"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"Imports System"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"Imports System.ComponentModel"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"Imports "& _ 
                    "System.Data.EntityClient"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"Imports System.Data.Objects"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"Imports System.Data.Objec"& _ 
                    "ts.DataClasses"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"Imports System.Linq"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"Imports System.Runtime.Serialization"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"Impor"& _ 
                    "ts System.Xml.Serialization"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"<Assembly: EdmSchemaAttribute(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture)))

            Me.Write(""")>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


    ''''''''
    '''''''' Write Relationship Attributes.
    ''''''''
    region.Begin(GetResourceString("Template_RegionRelationships"))
    For Each association As AssociationType in GetSourceSchemaTypes(Of AssociationType)()

            Me.Write("<Assembly: EdmRelationshipAttribute(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(association.NamespaceName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(association.Name))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(EndName(association, 0)))

            Me.Write(""", ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(EndMultiplicity(association, 0, code)))

            Me.Write(", GetType(")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(EscapeEndTypeName(association, 0, code)))

            Me.Write("), """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(EndName(association, 1)))

            Me.Write(""", ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(EndMultiplicity(association, 1, code)))

            Me.Write(", GetType(")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(EscapeEndTypeName(association, 1, code)))

            Me.Write(")")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.StringBefore(", ", If(association.IsForeignKey, "True", Nothing))))

            Me.Write(")>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


    Next
    region.End()

    If(Not String.IsNullOrEmpty(namespaceName)) Then

            Me.Write("Namespace ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(namespaceName))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        PushIndent(CodeRegion.GetIndent(1))
    End If

    ''''''''
    '''''''' 
    ''''''''
    region.Begin(GetResourceString("Template_RegionContexts"))
    For Each container as EntityContainer in GetSourceSchemaTypes(Of EntityContainer)()

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(container)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(container, region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))

            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForType(container)))

            Me.Write(" Partial Class ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(container)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Inherits ObjectContext"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    #Region """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(GetResourceString("Template_RegionConstructors")))

            Me.Write(""""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_ContextDefaultCtorComment"), container.Name, container.Name)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Public Sub New()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        MyBase.New(""name=")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(container.Name))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(container.Name))

            Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        WriteLazyLoadingEnabled(container)

            Me.Write("        OnContextCreated()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_ContextCommonCtorComment"), container.Name)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Public Sub New(ByVal connectionString As String)"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"     "& _ 
                    "   MyBase.New(connectionString, """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(container.Name))

            Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        WriteLazyLoadingEnabled(container)

            Me.Write("        OnContextCreated()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_ContextCommonCtorComment"), container.Name)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Public Sub New(ByVal connection As EntityConnection)"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&" "& _ 
                    "       MyBase.New(connection, """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(container.Name))

            Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        WriteLazyLoadingEnabled(container)

            Me.Write("        OnContextCreated()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    #End Region"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    #Region """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(GetResourceString("Template_RegionPartialMethods")))

            Me.Write(""""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Partial Private Sub OnContextCreated()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    #End Region"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)& _ 
                    ""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        ''''''''
        '''''''' 
        ''''''''
        region.Begin(GetResourceString("Template_RegionObjectSetProperties"))
        For Each entitySet As EntitySet In container.BaseEntitySets.OfType(Of EntitySet)()
            VerifyEntityTypeAndSetAccessibilityCompatability(entitySet)

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(entitySet)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(entitySet, region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(entitySet))))


            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForReadOnlyProperty(entitySet)))

            Me.Write(" ReadOnly Property ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(entitySet)))

            Me.Write("() As ObjectSet(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(entitySet.ElementType, code)))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            If (")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(entitySet)))

            Me.Write(" Is Nothing) Then"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"                ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(entitySet)))

            Me.Write(" = MyBase.CreateObjectSet(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(entitySet.ElementType, code)))

            Me.Write(")(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(entitySet.Name))

            Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            End If"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            Return ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(entitySet)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Property"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Private ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(entitySet)))

            Me.Write(" As ObjectSet(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(entitySet.ElementType, code)))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        Next
        region.End()

        ''''''''
        '''''''' 
        ''''''''
        '''''''' 
        '''''''' 
        ''''''''
        '''''''' 
        '''''''' 
        '''''''' 
        ''''''''
        region.Begin(GetResourceString("Template_RegionAddToMethods"))
        Dim addToMethods As IEnumerable(Of EntitySet) = If(CreateContextAddToMethods.Value, container.BaseEntitySets.OfType(Of EntitySet)(), Enumerable.Empty(Of EntitySet)())
        For Each addTo As EntitySet in addToMethods
        Dim parameterName As String = code.Escape(FixParameterName(addTo.ElementType.Name, code))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_GenCommentAddToMethodVb"), addTo.Name)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForType(addTo.ElementType)))

            Me.Write(" Sub AddTo")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(addTo.Name))

            Me.Write("(ByVal ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameterName))

            Me.Write(" As ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(addTo.ElementType, code)))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        MyBase.AddObject(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(addTo.Name))

            Me.Write(""", ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameterName))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        Next
        region.End()

        region.Begin(GetResourceString("Template_RegionFunctionImports"))
        For Each edmFunction As EdmFunction in container.FunctionImports
            Dim parameters As IEnumerable(Of FunctionImportParameter) = FunctionImportParameter.Create(edmFunction.Parameters, code, ef)
            Dim paramList As String = String.Join(", ", parameters.Select(Function(p) p.FunctionParameterName & " As " & p.FunctionParameterType).ToArray())
            Dim returnType As TypeUsage = If(edmFunction.ReturnParameters.Count = 0, Nothing, ef.GetElementType(edmFunction.ReturnParameters(0).TypeUsage))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(edmFunction)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel)))


            Me.Write(Me.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(Function(p) New Tuple(Of string, string)(p.RawFunctionParameterName, SummaryComment(p.Source))), region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(edmFunction))))


            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForMethod(edmFunction)))

            Me.Write(" Function ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(edmFunction)))

            Me.Write("(")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(paramList))

            Me.Write(") As ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(If(returnType IsNot Nothing, "ObjectResult(Of " & MultiSchemaEscape(returnType, code) & ")", "Integer")))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


            For Each parameter As FunctionImportParameter In parameters
                If (Not parameter.NeedsLocalVariable) Then
                    Continue For
                End If

            Me.Write("        Dim ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName))

            Me.Write(" As ObjectParameter"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        If (")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(If(parameter.IsNullableOfT, parameter.FunctionParameterName + ".HasValue", parameter.FunctionParameterName & " IsNot Nothing")))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName))

            Me.Write(" = New ObjectParameter(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.EsqlParameterName))

            Me.Write(""", ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.FunctionParameterName))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        Else"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName))

            Me.Write(" = New ObjectParameter(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.EsqlParameterName))

            Me.Write(""", GetType(")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.RawClrTypeName))

            Me.Write("))"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End If"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


            Next

            Me.Write("        Return MyBase.ExecuteFunction")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(If(returnType Is Nothing, "", "(Of " & MultiSchemaEscape(returnType, code) & ")")))

            Me.Write("(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(edmFunction.Name))

            Me.Write("""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.StringBefore(", ", String.Join(", ", parameters.Select(Function(p) p.ExecuteParameterName).ToArray()))))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Function"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


            If (returnType IsNot Nothing AndAlso returnType.EdmType.BuiltInTypeKind = BuiltInTypeKind.EntityType)

            Me.Write("    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(edmFunction)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <param name=""mergeOption""></param>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(Function(p) New Tuple(Of string, string)(p.RawFunctionParameterName, SummaryComment(p.Source))), region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(edmFunction))))


            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForMethod(edmFunction)))

            Me.Write(" Function ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(edmFunction)))

            Me.Write("(")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.StringAfter(paramList, ", ")))

            Me.Write("mergeOption As MergeOption) As ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(If(returnType IsNot Nothing, "ObjectResult(Of " & MultiSchemaEscape(returnType, code) & ")", "Integer")))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


            For Each parameter As FunctionImportParameter In parameters
                If (Not parameter.NeedsLocalVariable) Then
                    Continue For
                End If

            Me.Write("        Dim ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName))

            Me.Write(" As ObjectParameter"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        If (")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(If(parameter.IsNullableOfT, parameter.FunctionParameterName + ".HasValue", parameter.FunctionParameterName & " IsNot Nothing")))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName))

            Me.Write(" = New ObjectParameter(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.EsqlParameterName))

            Me.Write(""", ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.FunctionParameterName))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        Else"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName))

            Me.Write(" = New ObjectParameter(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.EsqlParameterName))

            Me.Write(""", GetType(")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.RawClrTypeName))

            Me.Write("))"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End If"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


                Next

            Me.Write("        Return MyBase.ExecuteFunction(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(returnType, code)))

            Me.Write(")(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(edmFunction.Name))

            Me.Write(""", mergeOption")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.StringBefore(", ", String.Join(", ", parameters.Select(Function(p) p.ExecuteParameterName).ToArray()))))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Function"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


            End If
        Next
        region.End()

            Me.Write("End Class"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        VerifyCaseInsensitiveEntitySetUniqueness(container.BaseEntitySets.OfType(Of EntitySet)())
    Next
    region.End()

    ''''''''
    '''''''' 
    ''''''''
    region.Begin(GetResourceString("Template_RegionEntities"))
    For Each loopEntity As EntityType in GetSourceSchemaTypes(Of EntityType)().OrderBy(Function(e) e.Name)
        Dim entity As EntityType = loopEntity

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(entity)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(entity, region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"<EdmEntityTypeAttribute(NamespaceName:=""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(entity.NamespaceName))

            Me.Write(""", Name:=""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(entity.Name))

            Me.Write(""")>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"<Serializable()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"<DataContractAttribute(IsReference:=True)>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        For Each subType As EntityType in ItemCollection.GetItems(Of EntityType)().Where(Function(b) b.BaseType is entity)

            Me.Write("<KnownTypeAttribute(GetType(")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(subType, code)))

            Me.Write("))>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        Next


            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForType(entity)))

            Me.Write(" ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(code.MustInheritOption(entity))))

            Me.Write("Partial Class ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(entity)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Inherits ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(BaseTypeName(entity, code)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        If(Not entity.Abstract) Then
            WriteFactoryMethod(entity, code)
        End If

        region.Begin(GetResourceString("Template_RegionPrimitiveProperties"))
        For Each edmProperty As EdmProperty in entity.Properties.Where(Function(p) p.DeclaringType Is entity AndAlso TypeOf p.TypeUsage.EdmType Is PrimitiveType)
            VerifyGetterAndSetterAccessibilityCompatability(edmProperty)
            WritePrimitiveTypeProperty(edmProperty, code)
        Next
        region.End()

        region.Begin(GetResourceString("Template_RegionComplexProperties"))
        For Each edmProperty As EdmProperty in entity.Properties.Where(Function(p) p.DeclaringType Is entity AndAlso TypeOf p.TypeUsage.EdmType Is ComplexType)
            VerifyGetterAndSetterAccessibilityCompatability(edmProperty)
            WriteComplexTypeProperty(edmProperty, code)
        Next
        region.End()

        ''''''''
        '''''''' 
        ''''''''
        region.Begin(GetResourceString("Template_RegionNavigationProperties"))
        For Each navProperty As NavigationProperty in entity.NavigationProperties.Where(Function(n) n.DeclaringType Is entity)

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(navProperty)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(navProperty, region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <XmlIgnoreAttribute()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <SoapIgnoreAttribute()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <DataMemberAttribu"& _ 
                    "te()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <EdmRelationshipNavigationPropertyAttribute(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.NamespaceName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.Name))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name))

            Me.Write(""")>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


            If(navProperty.ToEndMember.RelationshipMultiplicity = RelationshipMultiplicity.Many) Then

            Me.Write("     ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(navProperty))))


            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(navProperty)))

            Me.Write(" Property ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(navProperty)))

            Me.Write("() As EntityCollection(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(navProperty))))

            Me.Write("Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            Return CType(Me,IEntityWithRelationships).RelationshipManager.Ge"& _ 
                    "tRelatedCollection(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(")(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name))

            Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter(navProperty))))

            Me.Write("Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            If (Not value Is Nothing)"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"                CType(Me, IEntityWith"& _ 
                    "Relationships).RelationshipManager.InitializeRelatedCollection(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(")(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name))

            Me.Write(""", value)"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            End If"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Property"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


           Else

            Me.Write("    ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(navProperty))))


            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(navProperty)))

            Me.Write(" Property ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(navProperty)))

            Me.Write("() As ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(navProperty))))

            Me.Write("Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            Return CType(Me, IEntityWithRelationships).RelationshipManager.G"& _ 
                    "etRelatedReference(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(")(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name))

            Me.Write(""").Value"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter(navProperty))))

            Me.Write("Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            CType(Me, IEntityWithRelationships).RelationshipManager.GetRelat"& _ 
                    "edReference(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(")(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name))

            Me.Write(""").Value = value"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Property"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        Dim refPropertyName As String = navProperty.Name & "Reference"
        If(entity.Members.Any(Function(m) m.Name = refPropertyName)) Then
            '
            Errors.Add(New System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6017",
                String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_ConflictingGeneratedNavPropName"), navProperty.Name, entity.FullName, refPropertyName)))
        End If

            Me.Write("    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(navProperty)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(navProperty, region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <BrowsableAttribute(False)>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <DataMemberAttribute()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(navProperty)))

            Me.Write(" Property ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(refPropertyName))

            Me.Write("() As EntityReference(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(navProperty))))

            Me.Write("Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            Return CType(Me, IEntityWithRelationships).RelationshipManager.G"& _ 
                    "etRelatedReference(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(")(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name))

            Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter(navProperty))))

            Me.Write("Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            If (Not value Is Nothing)"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"                CType(Me, IEntityWith"& _ 
                    "Relationships).RelationshipManager.InitializeRelatedReference(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(")(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name))

            Me.Write(""", value)"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            End If"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Property"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


            End If
        Next
        region.End()

            Me.Write("End Class"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        VerifyCaseInsensitiveMemberUniqueness(GetAllDeclaredMembers(entity))
    Next
    region.End()

    ''''''''
    '''''''' 
    ''''''''
    region.Begin(GetResourceString("Template_RegionComplexTypes"))
    For Each  loopComplex As ComplexType in GetSourceSchemaTypes(Of ComplexType)().OrderBy(Function(e) e.Name)
        Dim complex As ComplexType = loopComplex

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(complex)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(complex, region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"<EdmComplexTypeAttribute(NamespaceName:=""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(complex.NamespaceName))

            Me.Write(""", Name:=""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(complex.Name))

            Me.Write(""")>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"<DataContractAttribute(IsReference:=True)>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"<Serializable()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))

            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForType(complex)))

            Me.Write(" Partial Class ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(complex)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Inherits ComplexObject"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        WriteFactoryMethod(complex, code)

        region.Begin(GetResourceString("Template_RegionPrimitiveProperties"))
        For Each edmProperty As EdmProperty in complex.Properties.Where(Function(p) p.DeclaringType Is complex AndAlso TypeOf p.TypeUsage.EdmType Is PrimitiveType)
            VerifyGetterAndSetterAccessibilityCompatability(edmProperty)
            WritePrimitiveTypeProperty(edmProperty, code)
        Next
        region.End()

        region.Begin(GetResourceString("Template_RegionComplexProperties"))
        For Each edmProperty As EdmProperty in complex.Properties.Where(Function(p) p.DeclaringType Is complex AndAlso TypeOf p.TypeUsage.EdmType Is ComplexType)
            VerifyGetterAndSetterAccessibilityCompatability(edmProperty)
            WriteComplexTypeProperty(edmProperty, code)
        Next
        region.End()

            Me.Write("End Class"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        VerifyCaseInsensitiveMemberUniqueness(GetAllDeclaredMembers(complex))
    Next
    region.End()

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


    If (Not String.IsNullOrEmpty(namespaceName)) Then
    PopIndent()

            Me.Write("End Namespace"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


    End If
    VerifyCaseInsensitiveTypeUniqueness()

            Return Me.GenerationEnvironment.ToString
        End Function



    ''''''''
    '''''''' 
    ''''''''

    ''''''''
    '''''''' 
    ''''''''

    Private Sub WriteFactoryMethod(structuralType As StructuralType, code As CodeGenerationTools)
        Dim region As CodeRegion = New CodeRegion(Me, 1)

        Dim methodName As String = "Create" + structuralType.Name
        Dim uniqueIdentifier As UniqueIdentifierService = New UniqueIdentifierService()
        Dim instanceName As String = code.Escape(uniqueIdentifier.AdjustIdentifier((code.CamelCase(structuralType.Name))))
        Dim parameters As IEnumerable(Of FactoryMethodParameter) = FactoryMethodParameter.CreateParameters(structuralType.Members.OfType(Of EdmProperty)().Where(Function(p) IncludePropertyInFactoryMethod(structuralType, p)), uniqueIdentifier, Function(t, c) MultiSchemaEscape(t, c), code)

        If (parameters.Count() = 0) Then
            Return
        End If

        If(structuralType.Members.Any(Function(m) m.Name = methodName)) Then
            ' 
            Errors.Add(New System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6029",
                String.Format(CultureInfo.CurrentCulture, _
                   GetResourceString("Template_FactoryMethodNameConflict"), methodName, structuralType.FullName)))
        End If

        region.Begin(GetResourceString("Template_RegionFactoryMethod"))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_FactoryMethodComment"), structuralType.Name)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(Function(p) New Tuple(Of String, String)(p.RawParameterName, p.ParameterComment)), region.CurrentIndentLevel)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Public Shared Function ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(methodName))


Me.Write("(")


Me.Write(Me.ToStringHelper.ToStringWithCulture(String.Join(", ", parameters.Select(Function(p) p.ParameterName & " As " & p.ParameterType).ToArray())))


Me.Write(") As ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(structuralType)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        Dim ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(instanceName))


Me.Write(" as ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(structuralType)))


Me.Write(" = New ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(structuralType)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))




        For Each parameter As FactoryMethodParameter in parameters
            If(parameter.IsComplexType) Then
                ' 


Me.Write("        ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(instanceName))


Me.Write(".")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(parameter.Source)))


Me.Write(" = StructuralObject.VerifyComplexObjectIsNotNull(")


Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.ParameterName))


Me.Write(", """)


Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.Source.Name))


Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))




            Else
                ' 


Me.Write("        ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(instanceName))


Me.Write(".")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(parameter.Source)))


Me.Write(" = ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.ParameterName))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



            End If
        Next


Me.Write("        Return ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(instanceName))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Function"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



        region.End()
    End Sub


    ''''''''
    '''''''' 
    ''''''''
    Private Sub WritePrimitiveTypeProperty(primitiveProperty As EdmProperty, code As CodeGenerationTools)
        Dim ef As MetadataTools = New MetadataTools(Me)


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(primitiveProperty)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")


Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(primitiveProperty, 1)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <EdmScalarPropertyAttribute(EntityKeyProperty:=")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.CreateLiteral(ef.IsKey(primitiveProperty))))


Me.Write(", IsNullable:=")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.CreateLiteral(ef.IsNullable(primitiveProperty))))


Me.Write(")>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <DataMemberAttribute()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(primitiveProperty))))


Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(primitiveProperty)))


Me.Write(" Property ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(primitiveProperty)))


Me.Write("() As ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(primitiveProperty.TypeUsage)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(primitiveProperty))))


Me.Write("Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


             If(ef.ClrType(primitiveProperty.TypeUsage) = GetType(byte())) Then


Me.Write("                Return StructuralObject.GetValidValue(")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(primitiveProperty)))


Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


             Else


Me.Write("            Return ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(primitiveProperty)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



                End If


Me.Write("        End Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter((primitiveProperty)))))


Me.Write("Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


         If(ef.IsKey(primitiveProperty)) Then
                If(ef.ClrType(primitiveProperty.TypeUsage) = GetType(byte())) Then


Me.Write("            If (Not StructuralObject.BinaryEquals(")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(primitiveProperty)))


Me.Write(", Value)) Then"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



                Else


Me.Write("            If (")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(primitiveProperty)))


Me.Write(" <> Value) Then"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



                End If
                PushIndent(CodeRegion.GetIndent(1))
            End If


Me.Write("            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ChangingMethodName(primitiveProperty)))


Me.Write("(value)"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ReportPropertyChanging(""")


Me.Write(Me.ToStringHelper.ToStringWithCulture(primitiveProperty.Name))


Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(primitiveProperty)))


Me.Write(" = StructuralObject.SetValidValue(value")


Me.Write(Me.ToStringHelper.ToStringWithCulture(OptionalNullableParameterForSetValidValue(primitiveProperty, code)))


Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ReportPropertyChanged(""")


Me.Write(Me.ToStringHelper.ToStringWithCulture(primitiveProperty.Name))


Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ChangedMethodName(primitiveProperty)))


Me.Write("()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


         If(ef.IsKey(primitiveProperty)) Then
                PopIndent()


Me.Write("            End If"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



            End If


Me.Write("        End Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Property"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Private ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(primitiveProperty)))


Me.Write(" As ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(primitiveProperty.TypeUsage)))


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.StringBefore(" = ", code.CreateLiteral(primitiveProperty.DefaultValue))))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Private Partial Sub ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ChangingMethodName(primitiveProperty)))


Me.Write("(value As ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(primitiveProperty.TypeUsage)))


Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Private Partial Sub ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ChangedMethodName(primitiveProperty)))


Me.Write("()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



    End Sub


    ''''''''
    '''''''' 
    ''''''''
    Private Sub WriteComplexTypeProperty(complexProperty As EdmProperty, code As CodeGenerationTools)


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(complexProperty)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")


Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(complexProperty, 1)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <EdmComplexPropertyAttribute()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <DesignerSerializationVisibility(Desig"& _ 
        "nerSerializationVisibility.Content)>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <XmlElement(IsNullable:=True)>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <S"& _ 
        "oapElement(IsNullable:=True)>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <DataMemberAttribute()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(complexProperty))))


Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(complexProperty)))


Me.Write(" Property ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(complexProperty)))


Me.Write("() As ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(complexProperty.TypeUsage, code)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(complexProperty))))


Me.Write("Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)))


Me.Write(" = GetValidValue(")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)))


Me.Write(", """)


Me.Write(Me.ToStringHelper.ToStringWithCulture(complexProperty.Name))


Me.Write(""", False, ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(InitializedTrackingField(complexProperty, code)))


Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(InitializedTrackingField(complexProperty, code)))


Me.Write(" = True"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            Return ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter(complexProperty))))


Me.Write("Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ChangingMethodName(complexProperty)))


Me.Write("(value)"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ReportPropertyChanging(""")


Me.Write(Me.ToStringHelper.ToStringWithCulture(complexProperty.Name))


Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)))


Me.Write(" = SetValidValue(")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)))


Me.Write(", value, """)


Me.Write(Me.ToStringHelper.ToStringWithCulture(complexProperty.Name))


Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(InitializedTrackingField(complexProperty, code)))


Me.Write(" = True"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ReportPropertyChanged(""")


Me.Write(Me.ToStringHelper.ToStringWithCulture(complexProperty.Name))


Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ChangedMethodName(complexProperty)))


Me.Write("()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Property"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Private ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)))


Me.Write(" As ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(complexProperty.TypeUsage, code)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Private ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(InitializedTrackingField(complexProperty, code)))


Me.Write(" As Boolean"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Private Partial Sub ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ChangingMethodName(complexProperty)))


Me.Write("(value As ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(complexProperty.TypeUsage, code)))


Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Private Partial Sub ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ChangedMethodName(complexProperty)))


Me.Write("()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



    End Sub

    Private Sub WriteLazyLoadingEnabled(ByVal container As EntityContainer)
        Dim lazyLoadingAttributeValue As String = Nothing
        Dim lazyLoadingAttributeName As String = MetadataConstants.EDM_ANNOTATION_09_02 & ":LazyLoadingEnabled"
        If MetadataTools.TryGetStringMetadataPropertySetting(container, lazyLoadingAttributeName, lazyLoadingAttributeValue) Then
            Dim isLazyLoading As Boolean = False
            If Boolean.TryParse(lazyLoadingAttributeValue, isLazyLoading) Then


Me.Write("        MyBase.ContextOptions.LazyLoadingEnabled = ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(isLazyLoading.ToString().ToLowerInvariant()))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



            End If
        End If
    End Sub

    ''''''''
    '''''''' 
    ''''''''
    Public Property SourceCsdlPath() As String
    Public Property ModelNamespace() As String
    Public Property ItemCollection() As EdmItemCollection
    Public Property ReferenceCsdlPaths() As IEnumerable(Of String)
    Public Property FullyQualifySystemTypes() As Nullable(Of Boolean)
    Public Property CreateContextAddToMethods As Nullable(Of Boolean)
    Public Property EdmToObjectNamespaceMap() As Dictionary(Of string, string)
        Get
            Return _edmToObjectNamespaceMap
        End Get
        Set
            _edmToObjectNamespaceMap = Value
        End Set

    End Property
    Dim _edmToObjectNamespaceMap As Dictionary(Of string, string) = New Dictionary(Of string, string)

    Public ReadOnly Property SourceEdmVersion As Double
        Get
            If (Not ItemCollection Is Nothing) Then
                Return ItemCollection.EdmVersion
            End If
            Return 0.0
        End Get
    End Property

    ''''''''
    '''''''' 
    ''''''''
    Private Shared ReadOnly Property ResourceManager As System.Resources.ResourceManager
        Get
            If(_resourceManager Is Nothing)
                    Dim manager As System.Resources.ResourceManager = New System.Resources.ResourceManager("System.Data.Entity.Design", GetType(System.Data.Entity.Design.MetadataItemCollectionFactory).Assembly)
                    System.Threading.Interlocked.CompareExchange(_resourceManager, manager, Nothing)
            End If
            Return _resourceManager
        End Get
    End Property
    Dim Shared _resourceManager As System.Resources.ResourceManager




    Private Shared Function GetResourceString(resourceName As String) As String
        Return ResourceManager.GetString(resourceName, _
             Nothing) ' 
    End Function

    Private Sub ApplyUserSettings(userSettings as UserSettings)
        If(SourceCsdlPath Is Nothing) Then
#If NOT PREPROCESSED_TEMPLATE
            If userSettings.SourceCsdlPath = ("$" & "edmxInputFile" & "$")
                Errors.Add(New System.CodeDom.Compiler.CompilerError(Host.TemplateFile, -1, -1, String.Empty,
                    GetResourceString("Template_ReplaceVsItemTemplateToken")))
                Return
            End If

            SourceCsdlPath = Host.ResolvePath(userSettings.SourceCsdlPath)
#Else
            SourceCsdlPath = userSettings.SourceCsdlPath
#End If
        End If

        ' normalize the path, remove ..\ from it
        SourceCsdlPath = Path.GetFullPath(SourceCsdlPath)

        If(ReferenceCsdlPaths Is Nothing) Then
            ReferenceCsdlPaths = userSettings.ReferenceCsdlPaths
        End If

        If(Not FullyQualifySystemTypes.HasValue) Then
            FullyQualifySystemTypes = userSettings.FullyQualifySystemTypes
        End If

        If(Not CreateContextAddToMethods.HasValue) Then
            CreateContextAddToMethods = userSettings.CreateContextAddToMethods
        End If

        DefaultSummaryComment = GetResourceString("Template_CommentNoDocumentation")
    End Sub

    ''''''''
    '''''''' 
    ''''''''
    Private Class UserSettings
        Public Property SourceCsdlPath() As String
        Public Property ReferenceCsdlPaths() As String ()
        Public Property FullyQualifySystemTypes() As Boolean
        Public Property CreateContextAddToMethods() As Boolean
        Public Property CamelCaseFields() As Boolean
    End Class

    Private Function GetNamespaceName(code As CodeGenerationTools) As String
        Dim namespaceName As String = code.VsNamespaceSuggestion()

#If PREPROCESSED_TEMPLATE Then
        If String.IsNullOrEmpty(namespaceName) Then
            namespaceName = GetObjectNamespace(ModelNamespace)
        End If
#End If
        Return namespaceName
    End Function

Private Function MultiSchemaEscape(ByVal usage As TypeUsage, ByVal code As CodeGenerationTools) As String
    Dim structural As StructuralType = TryCast(usage.EdmType, StructuralType)
    If structural IsNot Nothing Then
        Return MultiSchemaEscape(structural, code)
    End If
    Return code.Escape(usage)
End Function

Private Function MultiSchemaEscape(ByVal type As StructuralType, ByVal code As CodeGenerationTools) As String
    If type.NamespaceName <> ModelNamespace Then
        Return code.CreateFullName(code.EscapeNamespace(GetObjectNamespace(type.NamespaceName)), code.Escape(type))
    End If

    Return code.Escape(type)
End Function

Private Function NewModifier(ByVal navigationProperty As NavigationProperty) As String
    Dim baseType As Type = GetType(EntityObject)
    Return NewModifier(baseType, navigationProperty.Name)
End Function

Private Function NewModifier(ByVal edmFunction As EdmFunction) As String
    Dim baseType As Type = GetType(ObjectContext)
    Return NewModifier(baseType, edmFunction.Name)
End Function

Private Function NewModifier(ByVal entitySet As EntitySet) As String
    Dim baseType As Type = GetType(ObjectContext)
    Return NewModifier(baseType, entitySet.Name)
End Function

Private Function NewModifier(ByVal edmProperty As EdmProperty) As String
    Dim baseType As Type
    If edmProperty.DeclaringType.BuiltInTypeKind = BuiltInTypeKind.EntityType Then
        baseType = GetType(EntityObject)
    Else
        baseType = GetType(ComplexObject)
    End If
    Return NewModifier(baseType, edmProperty.Name)
End Function

Private Function NewModifier(ByVal type As Type, ByVal memberName As String) As String
    If HasBaseMemberWithMatchingName(type, memberName) Then
        Return "Shadows"
    End If
    Return String.Empty
End Function

Private Function ChangingMethodName(ByVal member As EdmMember) As String
    Return String.Format(CultureInfo.InvariantCulture, "On{0}Changing", member.Name)
End Function

Private Function ChangedMethodName(ByVal member As EdmMember) As String
    Return String.Format(CultureInfo.InvariantCulture, "On{0}Changed", member.Name)
End Function

Private Function InitializedTrackingField(ByVal edmProperty As EdmProperty, ByVal code As CodeGenerationTools) As String
    Dim namePart As String = edmProperty.Name & "Initialized"
    If code.CamelCaseFields Then
        namePart = code.CamelCase(namePart)
    End If
    Return "_" & namePart
End Function

Private Function OptionalNullableParameterForSetValidValue(ByVal member As EdmMember, ByVal code As CodeGenerationTools) As String
    Dim ef As New MetadataTools(Me)
    Dim list As String = String.Empty
    If DirectCast(member.TypeUsage.EdmType, PrimitiveType).ClrEquivalentType.IsClass Then
        Dim storeGeneratedPatternProperty As MetadataProperty = Nothing
        Dim isNullable As Boolean = ef.IsNullable(member.TypeUsage) OrElse
            (member.MetadataProperties.TryGetValue(MetadataConstants.EDM_ANNOTATION_09_02 & ":StoreGeneratedPattern", False, storeGeneratedPatternProperty) AndAlso
             Object.Equals(storeGeneratedPatternProperty.Value, "Computed"))
        list += ", " & code.CreateLiteral(isNullable)
    End If
    Return list
End Function

Private Shared Function IsVisibleMember(ByVal memberInfo As MemberInfo) As Boolean
    If TypeOf memberInfo Is EventInfo Then
        Dim ei As EventInfo = DirectCast(memberInfo, EventInfo)
        Dim add As MethodInfo = ei.GetAddMethod()
        Dim remove As MethodInfo = ei.GetRemoveMethod()
        Return IsVisibleMethod(add) OrElse IsVisibleMethod(remove)
    ElseIf TypeOf memberInfo Is FieldInfo Then
        Dim fi As FieldInfo = DirectCast(memberInfo, FieldInfo)
        Return Not fi.IsPrivate AndAlso Not fi.IsAssembly
    ElseIf TypeOf memberInfo Is MethodBase Then
        Dim mb As MethodBase = DirectCast(memberInfo, MethodBase)
        If mb.IsSpecialName Then
            Return False
        End If
        Return IsVisibleMethod(mb)
    ElseIf TypeOf memberInfo Is PropertyInfo Then
        Dim pi As PropertyInfo = DirectCast(memberInfo, PropertyInfo)
        Dim getMethod As MethodInfo = pi.GetGetMethod()
        Dim entitySet As MethodInfo = pi.GetSetMethod()
        Return IsVisibleMethod(getMethod) OrElse IsVisibleMethod(entitySet)
    End If

    Return False
End Function

Private Shared Function IsVisibleMethod(ByVal methodBase As MethodBase) As Boolean
    If methodBase Is Nothing Then
        Return False
    End If

    Return Not methodBase.IsPrivate AndAlso Not methodBase.IsAssembly
End Function

Private Shared Function HasBaseMemberWithMatchingName(ByVal type As Type, ByVal memberName As String) As Boolean
    Dim bindings As BindingFlags = BindingFlags.FlattenHierarchy Or BindingFlags.NonPublic Or BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.Static
    Return type.GetMembers(bindings).Where(Function(m) IsVisibleMember(m)).Any(Function(m) m.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase))
End Function

Private Function GetSourceSchemaTypes(Of T As GlobalItem)() As IEnumerable(Of T)
    If Path.GetExtension(SourceCsdlPath) <> ".edmx" Then
        Return ItemCollection.GetItems(Of T)().Where(Function(e) e.MetadataProperties.Any(Function(mp) mp.Name = "SchemaSource" AndAlso DirectCast(mp.Value, String) = SourceCsdlPath))
    Else
        Return ItemCollection.GetItems(Of T)()
    End If
End Function

Private Function EndName(ByVal association As AssociationType, ByVal index As Integer) As String
    Return association.AssociationEndMembers(index).Name
End Function

Private Function EndMultiplicity(ByVal association As AssociationType, ByVal index As Integer, ByVal code As CodeGenerationTools) As String
    Return code.CreateLiteral(association.AssociationEndMembers(index).RelationshipMultiplicity)
End Function

Private Function EscapeEndTypeName(ByVal association As AssociationType, ByVal index As Integer, ByVal code As CodeGenerationTools) As String
    Dim entity As EntityType = association.AssociationEndMembers(index).GetEntityType()
    Return code.CreateFullName(code.EscapeNamespace(GetObjectNamespace(entity.NamespaceName)), code.Escape(entity))
End Function

Private Function GetObjectNamespace(ByVal csdlNamespaceName As String) As String
    Dim objectNamespace As String = Nothing
    If EdmToObjectNamespaceMap.TryGetValue(csdlNamespaceName, objectNamespace) Then
        Return objectNamespace
    End If

    Return csdlNamespaceName
End Function

Private Sub UpdateObjectNamespaceMap(objectNamespace As String)
    If Not objectNamespace = ModelNamespace AndAlso Not EdmToObjectNamespaceMap.ContainsKey(ModelNamespace)
        EdmToObjectNamespaceMap.Add(ModelNamespace, objectNamespace)
    End If
End Sub


Private Shared Function FixParameterName(ByVal name As String, ByVal code As CodeGenerationTools) As String
    ' 
    ' 
    If StringComparer.OrdinalIgnoreCase.Equals(name, "id") Then
        ' 
        Return "id"
    End If
    Return code.CamelCase(name)
End Function

Private Function BaseTypeName(ByVal entity As EntityType, ByVal code As CodeGenerationTools) As String
    Return If(entity.BaseType Is Nothing, "EntityObject", MultiSchemaEscape(DirectCast(entity.BaseType, StructuralType), code))
End Function

Private Function IncludePropertyInFactoryMethod(ByVal factoryType As StructuralType, ByVal edmProperty As EdmProperty) As Boolean
    If edmProperty.Nullable Then
        Return False
    End If

    If edmProperty.DefaultValue IsNot Nothing Then
        Return False
    End If

    If (Accessibility.ForReadOnlyProperty(edmProperty) <> "Public" AndAlso Accessibility.ForWriteOnlyProperty(edmProperty) <> "Public") OrElse (factoryType IsNot edmProperty.DeclaringType AndAlso Accessibility.ForWriteOnlyProperty(edmProperty) = "Private") Then
        ' 
        Return False
    End If

    Return True
End Function

Private Class FactoryMethodParameter
    Public Source As EdmProperty
    Public RawParameterName As String
    Public ParameterName As String
    Public ParameterType As String
    Public ParameterComment As String
    Public IsComplexType As Boolean

    Public Shared Function CreateParameters(ByVal properties As IEnumerable(Of EdmProperty), ByVal unique As UniqueIdentifierService, ByVal multiSchemaEscape As Func(Of TypeUsage, CodeGenerationTools, String), ByVal code As CodeGenerationTools) As IEnumerable(Of FactoryMethodParameter)
        Dim parameters As New List(Of FactoryMethodParameter)()
        For Each edmProperty As EdmProperty In properties
            Dim parameter As New FactoryMethodParameter()
            parameter.Source = edmProperty
            parameter.IsComplexType = TypeOf edmProperty.TypeUsage.EdmType Is ComplexType
            parameter.RawParameterName = unique.AdjustIdentifier(FixParameterName(edmProperty.Name, code))
            parameter.ParameterName = code.Escape(parameter.RawParameterName)
            parameter.ParameterType = multiSchemaEscape(edmProperty.TypeUsage, code)
            parameter.ParameterComment = String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_CommentFactoryMethodParam"), edmProperty.Name)
            parameters.Add(parameter)
        Next

        Return parameters
    End Function
End Class

Private Property DefaultSummaryComment() As String

Private Function SummaryComment(ByVal item As MetadataItem) As String
    If item.Documentation IsNot Nothing AndAlso item.Documentation.Summary IsNot Nothing Then
        Return PrefixLinesOfMultilineComment(XMLCOMMENT_START & " ", XmlEntityize(item.Documentation.Summary))
    End If

    If DefaultSummaryComment IsNot Nothing Then
        Return DefaultSummaryComment
    End If

    Return String.Empty
End Function

Private Function LongDescriptionCommentElement(ByVal item As MetadataItem, ByVal indentLevel As Integer) As String
    If item.Documentation IsNot Nothing AndAlso Not String.IsNullOrEmpty(item.Documentation.LongDescription) Then
        Dim comment As String = Environment.NewLine
        Dim lineStart As String = CodeRegion.GetIndent(indentLevel) + XMLCOMMENT_START & " "
        comment += (lineStart & "<LongDescription>") + Environment.NewLine
        comment += lineStart + PrefixLinesOfMultilineComment(lineStart, XmlEntityize(item.Documentation.LongDescription)) + Environment.NewLine
        comment += lineStart & "</LongDescription>"
        Return comment
    End If
    Return String.Empty
End Function

Private Function PrefixLinesOfMultilineComment(ByVal prefix As String, ByVal comment As String) As String
    Return comment.Replace(Environment.NewLine, Environment.NewLine + prefix)
End Function

Private Function ParameterComments(ByVal parameters As IEnumerable(Of Tuple(Of String, String)), ByVal indentLevel As Integer) As String
    Dim builder As New System.Text.StringBuilder()
    For Each parameter As Tuple(Of String, String) In parameters
        builder.AppendLine()
        builder.Append(CodeRegion.GetIndent(indentLevel))
        builder.Append(XMLCOMMENT_START)
        builder.Append(String.Format(CultureInfo.InvariantCulture, " <param name=""{0}"">{1}</param>", parameter.Item1, parameter.Item2))
    Next
    Return builder.ToString()
End Function

Private Function XmlEntityize(ByVal text As String) As String
    If String.IsNullOrEmpty(text) Then
        Return String.Empty
    End If

    text = text.Replace("&", "&amp;")
    text = text.Replace("<", "&lt;").Replace(">", "&gt;")
    Dim id As String = Guid.NewGuid().ToString()
    text = text.Replace(Environment.NewLine, id)
    text = text.Replace(vbCr, "&#xD;").Replace(vbLf, "&#xA;")
    text = text.Replace(id, Environment.NewLine)
    Return text.Replace("'", "&apos;").Replace("""", "&quot;")
End Function

Const XMLCOMMENT_START As String = "'''"
Private Function GetProperties(ByVal type As StructuralType) As IEnumerable(Of EdmProperty)
    If type.BuiltInTypeKind = BuiltInTypeKind.EntityType Then
        Return DirectCast(type, EntityType).Properties
    Else
        Return DirectCast(type, ComplexType).Properties
    End If
End Function

    ''''''''
    '''''''' 
    ''''''''
Private Function GetGlobalItemName(item As GlobalItem) As String
    If TypeOf item Is EdmType Then
        ' 
        Return CType(item, EdmType).Name
    Else
        ' 
        Return CType(item, EntityContainer).Name
    End If
End Function

Protected Sub VerifyGetterAndSetterAccessibilityCompatability(ByVal member As EdmMember)
    Dim rawGetterAccessibility As String = Accessibility.ForReadOnlyProperty(member)
    Dim rawSetterAccessibility As String = Accessibility.ForWriteOnlyProperty(member)

    If (rawGetterAccessibility = "Friend" AndAlso rawSetterAccessibility = "Protected") OrElse (rawGetterAccessibility = "Protected" AndAlso rawSetterAccessibility = "Friend") Then

        Errors.Add(New System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6033", String.Format(CultureInfo.CurrentCulture, GetResourceString("GeneratedPropertyAccessibilityConflict"), member.Name, rawGetterAccessibility, rawSetterAccessibility)))
    End If
End Sub

Private Sub VerifyEntityTypeAndSetAccessibilityCompatability(ByVal entitySet As EntitySet)
    Dim typeAccess As String = Accessibility.ForType(entitySet.ElementType)
    Dim setAccess As String = Accessibility.ForReadOnlyProperty(entitySet)

    If typeAccess = "Friend" AndAlso (setAccess = "Public" OrElse setAccess = "Protected") Then
        Errors.Add(New System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6036", String.Format(CultureInfo.CurrentCulture, GetResourceString("EntityTypeAndSetAccessibilityConflict"), entitySet.ElementType.Name, typeAccess, entitySet.Name, setAccess)))
    End If
End Sub


Private Sub VerifyCaseInsensitiveTypeUniqueness()
    VerifyCaseInsensitiveUniqueness(GetSourceSchemaTypes(Of GlobalItem)().Where(Function(i) TypeOf i is StructuralType OrElse TypeOf i is EntityContainer), _
        Function(g) GetGlobalItemName(g), _
        Function(g) String.Format(CultureInfo.CurrentCulture, _
            GetResourceString("Template_CaseInsensitiveTypeConflict"), GetGlobalItemName(g)))
End Sub

Private Sub VerifyCaseInsensitiveEntitySetUniqueness(entitySets As IEnumerable(Of EntitySet))
    VerifyCaseInsensitiveUniqueness(entitySets, Function(e) e.Name, _
        Function(e) String.Format(CultureInfo.CurrentCulture, _
            GetResourceString("Template_CaseInsensitiveEntitySetConflict"), e.EntityContainer.Name, e.Name))
End Sub

Private Sub VerifyCaseInsensitiveMemberUniqueness(members As IEnumerable(Of EdmMember))
    VerifyCaseInsensitiveUniqueness(members, Function(m) m.Name, _
        Function(m) String.Format(CultureInfo.CurrentCulture, _
            GetResourceString("Template_CaseInsensitiveMemberConflict"), m.DeclaringType.FullName, m.Name))
End Sub

Private Sub VerifyCaseInsensitiveUniqueness(Of T As MetadataItem)(items As IEnumerable(Of T), getIdentity As Func(Of T, String), formatMessage As Func(Of T, String) )
    Dim hash As HashSet(Of String) = New HashSet(Of String)(StringComparer.InvariantCultureIgnoreCase)
    For Each item As MetadataItem in items
        If Not hash.Add(getIdentity(item)) Then
            ' 
            Errors.Add(New System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, 6023, formatMessage(item)))
        End If
    Next
End Sub

Public Function GetAllDeclaredMembers(structural As StructuralType) As IEnumerable(Of EdmMember)
    If(TypeOf structural Is EntityType) Then
        Dim entity As EntityType = CType(structural, EntityType)
        Dim declaredMembers As IEnumerable(Of EdmMember) = entity.Members.Where(Function(m) m.DeclaringType Is entity)
        Dim decalredNavigationProperties As IEnumerable(Of NavigationProperty) = entity.NavigationProperties.Where(Function(n) n.DeclaringType Is entity)

        Return declaredMembers.Union(decalredNavigationProperties.Cast(Of EdmMember)())
    End If

    Return structural.Members.Where(Function(m) m.DeclaringType Is structural)
End Function

Private Sub DefineMetadata()
    TemplateMetadata(MetadataConstants.TT_TEMPLATE_NAME) = "VBCodeGen"
    TemplateMetadata(MetadataConstants.TT_TEMPLATE_VERSION) = "4.0"
    TemplateMetadata(MetadataConstants.TT_MINIMUM_ENTITY_FRAMEWORK_VERSION) = "4.0"
End Sub

Private NotInheritable Class UniqueIdentifierService
    Private ReadOnly _knownIdentifiers As HashSet(Of String) = New HashSet(Of string)(StringComparer.OrdinalIgnoreCase)

    ''' <summary>
    ''' 
    ''' 
    ''' </summary>
    Public Function AdjustIdentifier(identifier As String) As String
        ' 
        Dim numberOfConflicts As Int32 = 0
        Dim adjustedIdentifier As String = identifier
        While Not _knownIdentifiers.Add(adjustedIdentifier)
            numberOfConflicts += 1
            adjustedIdentifier = identifier + numberOfConflicts.ToString(CultureInfo.InvariantCulture)
        End While

        Return adjustedIdentifier
    End Function
End Class



' Copyright (c) Microsoft Corporation.  All rights reserved.

Public Shared TemplateMetadata As New Dictionary(Of String, String)()

''' <summary>
''' Responsible for helping to create source code that is
''' correctly formated and functional
''' </summary>
Public Class CodeGenerationTools
    Private ReadOnly _textTransformation As DynamicTextTransformation
    Private ReadOnly _code As VBCodeProvider
    Private ReadOnly _ef As MetadataTools

    ''' <summary>
    ''' Initializes a new CodeGenerationTools object with the TextTransformation (T4 generated class)
    ''' that is currently running.
    ''' </summary>
    Public Sub New(ByVal textTransformation As Object)
        If textTransformation Is Nothing Then
            Throw New ArgumentNullException("textTransformation")
        End If

        _textTransformation = DynamicTextTransformation.Create(textTransformation)
        _code = New VBCodeProvider()
        _ef = New MetadataTools(_textTransformation)
        FullyQualifySystemTypes = False
        CamelCaseFields = True
    End Sub

    ''' <summary>
    ''' When true, all types that are not being generated
    ''' are fully qualified to keep them from conflicting with
    ''' types that are being generated. Useful when you have
    ''' something like a type being generated named System.
    '''
    ''' Default is false.
    ''' </summary>
    Private _FullyQualifySystemTypes As Boolean
    Public Property FullyQualifySystemTypes() As Boolean
        Get
            Return _FullyQualifySystemTypes
        End Get
        Set(ByVal value As Boolean)
            _FullyQualifySystemTypes = value
        End Set
    End Property

    ''' <summary>
    ''' When true, the field names are Camel Cased,
    ''' otherwise they will preserve the case they
    ''' start with.
    '''
    ''' Default is true.
    ''' </summary>
    Private _CamelCaseFields As Boolean
    Public Property CamelCaseFields() As Boolean
        Get
            Return _CamelCaseFields
        End Get
        Set(ByVal value As Boolean)
            _CamelCaseFields = value
        End Set
    End Property

    ''' <summary>
    ''' Returns the NamespaceName suggested by VS if running inside VS. Otherwise, returns
    ''' null.
    ''' </summary>
    Public Function VsNamespaceSuggestion() As String
        Dim suggestion As String = _textTransformation.Host.ResolveParameterValue("directiveId", "namespaceDirectiveProcessor", "namespaceHint")
        If String.IsNullOrEmpty(suggestion) Then
            Return Nothing
        End If

        Return suggestion
    End Function

    ''' <summary>
    ''' Returns a string that is safe for use as an identifier in C#.
    ''' Keywords are escaped.
    ''' </summary>
    Public Function Escape(ByVal name As String) As String
        If name Is Nothing Then
            Return Nothing
        End If

        Return _code.CreateEscapedIdentifier(name)
    End Function

    ''' <summary>
    ''' Returns the name of the TypeUsage's EdmType that is safe for
    ''' use as an identifier.
    ''' </summary>
    Public Function Escape(ByVal typeUsage As TypeUsage) As String
        If typeUsage Is Nothing Then
            Return Nothing
        End If

        If TypeOf typeUsage.EdmType Is ComplexType OrElse TypeOf typeUsage.EdmType Is EntityType Then
            Return Escape(typeUsage.EdmType.Name)
        ElseIf TypeOf typeUsage.EdmType Is SimpleType Then
            Dim clrType As Type = _ef.UnderlyingClrType(typeUsage.EdmType)
            Dim typeName As String = If(TypeOf typeUsage.EdmType Is EnumType, Escape(typeUsage.EdmType.Name), Escape(clrType))
            If clrType.IsValueType AndAlso _ef.IsNullable(typeUsage) Then
                Return String.Format(CultureInfo.InvariantCulture, "Nullable(Of {0})", typeName)
            End If

            Return typeName
        ElseIf TypeOf typeUsage.EdmType Is CollectionType Then
            Return String.Format(CultureInfo.InvariantCulture, "ICollection(Of {0})", Escape(DirectCast(typeUsage.EdmType, CollectionType).TypeUsage))
        End If

        Throw New ArgumentException("typeUsage")
    End Function

    ''' <summary>
    ''' Returns the name of the EdmMember that is safe for
    ''' use as an identifier.
    ''' </summary>
    Public Function Escape(ByVal member As EdmMember) As String
        If member Is Nothing Then
            Return Nothing
        End If

        Return Escape(member.Name)
    End Function

    ''' <summary>
    ''' Returns the name of the EdmType that is safe for
    ''' use as an identifier.
    ''' </summary>
    Public Function Escape(ByVal type As EdmType) As String
        If type Is Nothing Then
            Return Nothing
        End If

        Return Escape(type.Name)
    End Function

    ''' <summary>
    ''' Returns the name of the EdmFunction that is safe for
    ''' use as an identifier.
    ''' </summary>
    Public Function Escape(ByVal edmFunction As EdmFunction) As String
        If edmFunction Is Nothing Then
            Return Nothing
        End If

        Return Escape(edmFunction.Name)
    End Function

    ''' <summary>
    ''' Returns the name of the EnumMember that is safe for
    ''' use as an identifier.
    ''' </summary>
    Public Function Escape(ByVal member As EnumMember) As String
        If member Is Nothing Then
            Return Nothing
        End If

        Return Escape(member.Name)
    End Function


    ''' <summary>
    ''' Returns the name of the EntityContainer that is safe for
    ''' use as an identifier.
    ''' </summary>
    Public Function Escape(ByVal container As EntityContainer) As String
        If container Is Nothing Then
            Return Nothing
        End If

        Return Escape(container.Name)
    End Function

    ''' <summary>
    ''' Returns the name of the EntitySet that is safe for
    ''' use as an identifier.
    ''' </summary>
    Public Function Escape(ByVal edmSet As EntitySet) As String
        If edmSet Is Nothing Then
            Return Nothing
        End If

        Return Escape(edmSet.Name)
    End Function

    ''' <summary>
    ''' Returns the name of the StructuralType that is safe for
    ''' use as an identifier.
    ''' </summary>
    Public Function Escape(ByVal type As StructuralType) As String
        If type Is Nothing Then
            Return Nothing
        End If

        Return Escape(type.Name)
    End Function

    ''' <summary>
    ''' Returns the NamespaceName with each segment safe to
    ''' use as an identifier.
    ''' </summary>
    Public Function EscapeNamespace(ByVal namespaceName As String) As String
        If String.IsNullOrEmpty(namespaceName) Then
            Return namespaceName
        End If

        Dim parts As String() = namespaceName.Split("."c)
        namespaceName = String.Empty
        For Each part As String In parts
            If namespaceName <> String.Empty Then
                namespaceName += "."
            End If

            namespaceName += Escape(part)
        Next

        Return namespaceName
    End Function

    ''' <summary>
    ''' Returns the name of the EdmMember formatted for
    ''' use as a field identifier.
    '''
    ''' This method changes behavior based on the CamelCaseFields
    ''' setting.
    ''' </summary>
    Public Function FieldName(ByVal member As EdmMember) As String
        If member Is Nothing Then
            Return Nothing
        End If

        Return FieldName(member.Name)
    End Function

    ''' <summary>
    ''' Returns the name of the EntitySet formatted for
    ''' use as a field identifier.
    '''
    ''' This method changes behavior based on the CamelCaseFields
    ''' setting.
    ''' </summary>
    Public Function FieldName(ByVal edmSet As EntitySet) As String
        If edmSet Is Nothing Then
            Return Nothing
        End If


        Return FieldName(edmSet.Name)
    End Function

    Private Function FieldName(ByVal name As String) As String
        If CamelCaseFields Then
            Return "_" & CamelCase(name)
        Else
            Return "_" & name
        End If
    End Function

    ''' <summary>
    ''' Returns the name of the Type object formatted for
    ''' use in source code.
    '''
    ''' This method changes behavior based on the FullyQualifySystemTypes
    ''' setting.
    ''' </summary>
    Public Function Escape(ByVal clrType As Type) As String
        Return Escape(clrType, FullyQualifySystemTypes)
    End Function

    ''' <summary>
    ''' Returns the name of the Type object formatted for
    ''' use in source code.
    ''' </summary>
    Public Function Escape(ByVal clrType As Type, ByVal fullyQualifySystemTypes As Boolean) As String
        If clrType Is Nothing Then
            Return Nothing
        End If

        Dim typeName As String
        If fullyQualifySystemTypes Then
            If(Not clrType.IsArray) Then
                typeName = clrType.FullName
            Else
                typeName = clrType.GetElementType().FullName & "()"
            End If

            typeName = "Global." & typeName
        Else
            typeName = _code.GetTypeOutput(New CodeTypeReference(clrType))
        End If
        Return typeName
    End Function

    ''' <summary>
    ''' Returns the abstract option if the entity is Abstract, otherwise returns String.Empty
    ''' </summary>
    Public Function MustInheritOption(entity As EntityType) As String
        If entity.Abstract Then
            Return "MustInherit"
        End If

        Return String.Empty
    End Function

    ''' <summary>
    ''' Returns the passed in identifier with the first letter changed to lowercase
    ''' </summary>
    Public Function CamelCase(ByVal identifier As String) As String
        If String.IsNullOrEmpty(identifier) Then
            Return identifier
        End If

        If identifier.Length = 1 Then
            Return identifier(0).ToString(CultureInfo.InvariantCulture).ToLowerInvariant()
        End If

        Return identifier(0).ToString(CultureInfo.InvariantCulture).ToLowerInvariant() + identifier.Substring(1)
    End Function

    ''' <summary>
    ''' If the value parameter is null or empty an empty string is returned,
    ''' otherwise it retuns value with a single space concatenated on the end.
    ''' </summary>
    Public Function SpaceAfter(ByVal value As String) As String
        Return StringAfter(value, " ")
    End Function

    ''' <summary>
    ''' If the value parameter is null or empty an empty string is returned,
    ''' otherwise it retuns value with a single space concatenated on the end.
    ''' </summary>
    Public Function SpaceBefore(ByVal value As String) As String
        Return StringBefore(" ", value)
    End Function

    ''' <summary>
    ''' If the value parameter is null or empty an empty string is returned,
    ''' otherwise it retuns value with append concatenated on the end.
    ''' </summary>
    Public Function StringAfter(ByVal value As String, ByVal append As String) As String
        If String.IsNullOrEmpty(value) Then
            Return String.Empty
        End If

        Return value + append
    End Function

    ''' <summary>
    ''' If the value parameter is null or empty an empty string is returned,
    ''' otherwise it retuns value with prepend concatenated on the front.
    ''' </summary>
    Public Function StringBefore(ByVal prepend As String, ByVal value As String) As String
        If String.IsNullOrEmpty(value) Then
            Return String.Empty
        End If

        Return prepend + value
    End Function

    ''' <summary>
    ''' Returns false and shows an error if the supplied type names aren't case-insensitively unique,
    ''' otherwise returns true.
    ''' </summary>
    Public Function VerifyCaseInsensitiveTypeUniqueness(types As IEnumerable(Of String), ByVal sourceFile As String) As Boolean
        Return VerifyCaseInsensitiveUniqueness(types, _
            Function(t) String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_CaseInsensitiveTypeConflict"), t), sourceFile)
    End Function

    ''' <summary>
    ''' Returns false and shows an error if the supplied entity set names aren't case-insensitively unique,
    ''' otherwise returns true.
    ''' </summary>
    Public Function VerifyCaseInsensitiveEntitySetUniqueness(entitySets As IEnumerable(Of String), ByVal entityContainerName As String, ByVal sourceFile As String) As Boolean
        Return VerifyCaseInsensitiveUniqueness(entitySets, Function(e) String.Format(CultureInfo.CurrentCulture, _
                GetResourceString("Template_CaseInsensitiveEntitySetConflict"), entityContainerName, e), sourceFile)
    End Function

    ''' <summary>
    ''' Returns false and shows an error if the supplied type members names aren't case-insensitively unique,
    ''' otherwise returns true.
    ''' </summary>
    Public Function VerifyCaseInsensitiveMemberUniqueness(members As IEnumerable(Of String), ByVal declaringType As String, ByVal sourceFile As String) As Boolean
        Return VerifyCaseInsensitiveUniqueness(members, _
            Function(m) String.Format(CultureInfo.CurrentCulture, _
                GetResourceString("Template_CaseInsensitiveMemberConflict"), declaringType, m), sourceFile)
    End Function

    ''' <summary>
    ''' Returns false and shows an error if the supplied strings aren't case-insensitively unique,
    ''' otherwise returns true.
    ''' </summary>
    Private Function VerifyCaseInsensitiveUniqueness(items As IEnumerable(Of String), formatMessage As Func(Of String, String), ByVal sourceFile As String) As Boolean
        Dim hash As HashSet(Of String) = New HashSet(Of String)(StringComparer.InvariantCultureIgnoreCase)
        For Each item As String in items
            If Not hash.Add(item) Then
                _textTransformation.Errors.Add(New System.CodeDom.Compiler.CompilerError(sourceFile, -1, -1, 6023, formatMessage(item)))
                Return False
            End If
        Next
        Return True
    End Function

    ''' <summary>
    ''' Returns the names of the items in the supplied collection that correspond to O-Space types.
    ''' </summary>
    Public Function GetAllGlobalItems(ByVal itemCollection As EdmItemCollection) As IEnumerable(Of String)
        Return itemCollection.GetItems(Of GlobalItem)() _
                .Where(Function(i) TypeOf i Is EntityType OrElse TypeOf i Is ComplexType OrElse TypeOf i Is EnumType OrElse TypeOf i is EntityContainer) _
                .Select(Function(g) GetGlobalItemName(g))
    End Function

    ''' <summary>
    ''' Returns the name of the supplied GlobalItem.
    ''' </summary>
    Private Function GetGlobalItemName(item As GlobalItem) As String
        If TypeOf item Is EdmType Then
            Return CType(item, EdmType).Name
        Else
            Return CType(item, EntityContainer).Name
        End If
    End Function

    ''' <summary>
    ''' Returns the names of the members of the supplied EdmType.
    ''' </summary>
    Public Function GetAllDeclaredMembers(edmType As EdmType) As IEnumerable(Of String)
        Dim entity As EntityType = TryCast(edmType, EntityType)
        If Not entity Is Nothing Then
            Dim declaredMembers As IEnumerable(Of EdmMember) = entity.Members.Where(Function(m) m.DeclaringType Is entity)
            Dim decalredNavigationProperties As IEnumerable(Of NavigationProperty) = entity.NavigationProperties.Where(Function(n) n.DeclaringType Is entity)

            Return declaredMembers.Union(decalredNavigationProperties.Cast(Of EdmMember)()).Select(Function(m) m.Name)
        End If

        Dim structural As StructuralType = TryCast(edmType, StructuralType)
        If Not structural Is Nothing Then
            Return structural.Members.Where(Function(m) m.DeclaringType Is structural).Select(Function(m) m.Name)
        End If

        Dim enumType As EnumType = TryCast(edmType, EnumType)
        If Not enumType Is Nothing Then
            Return enumType.Members.Select(Function(m) m.Name)
        End If

        Return Enumerable.Empty(Of String)()
    End Function

    ''' <summary>
    ''' Retuns as full of a name as possible, if a namespace is provided
    ''' the namespace and name are combined with a period, otherwise just
    ''' the name is returned.
    ''' </summary>
    Public Function CreateFullName(ByVal namespaceName As String, ByVal name As String) As String
        If String.IsNullOrEmpty(namespaceName) Then
            Return name
        End If

        Return (namespaceName & ".") + name
    End Function

    ''' <summary>
    ''' Retuns a literal representing the supplied value.
    ''' </summary>
    Public Function CreateLiteral(ByVal value As Object) As String
        If value Is Nothing Then
            Return String.Empty
        End If

        Dim type As Type = value.GetType()
        If type.IsEnum Then
            Return (type.FullName & ".") + value.ToString()
        End If
        If type Is GetType(Guid) Then
            Return String.Format(CultureInfo.InvariantCulture, "New Guid(""{0}"")", DirectCast(value, Guid).ToString("D", CultureInfo.InvariantCulture))
        ElseIf type Is GetType(DateTime) Then
            Return String.Format(CultureInfo.InvariantCulture, "New DateTime({0}, DateTimeKind.Unspecified)", DirectCast(value, DateTime).Ticks)
        ElseIf type Is GetType(Byte()) Then
            Dim arrayInit As String = String.Join(", ", DirectCast(value, Byte()).Select(Function(b) b.ToString(CultureInfo.InvariantCulture)).ToArray())
            Return String.Format(CultureInfo.InvariantCulture, "New Byte() {{{0}}}", arrayInit)
        ElseIf type Is GetType(DateTimeOffset) Then
            Dim dto As DateTimeOffset = DirectCast(value, DateTimeOffset)
            Return String.Format(CultureInfo.InvariantCulture, "New DateTimeOffset({0}, New TimeSpan({1}))", dto.Ticks, dto.Offset.Ticks)
        ElseIf type Is GetType(Decimal) Then
            Return String.Format(CultureInfo.InvariantCulture, "{0}D", DirectCast(value, Decimal).ToString(CultureInfo.InvariantCulture))
        ElseIf type Is GetType(TimeSpan) Then
            Return String.Format(CultureInfo.InvariantCulture, "New TimeSpan({0})", DirectCast(value, TimeSpan).Ticks)
        End If

        Dim expression As CodePrimitiveExpression = New CodePrimitiveExpression(value)
        Dim writer As StringWriter = New StringWriter()
        Dim code As VBCodeProvider = New VBCodeProvider()
        code.GenerateCodeFromExpression(expression, writer, New CodeGeneratorOptions())
        Return writer.ToString()
    End Function

    ''' <summary>
    ''' Returns a resource string from the System.Data.Entity.Design assembly.
    ''' </summary>
    Public Shared Function GetResourceString(resourceName As String, Optional culture As CultureInfo = Nothing) As String
        If _resourceManager Is Nothing Then
            _resourceManager = New System.Resources.ResourceManager("System.Data.Entity.Design", GetType(System.Data.Entity.Design.MetadataItemCollectionFactory).Assembly)
        End If

        Return _resourceManager.GetString(resourceName, culture)
    End Function
    Shared Private _resourceManager As System.Resources.ResourceManager

    Private Const ExternalTypeNameAttributeName As String = "http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName"

    ''' <summary>
    ''' Gets the entity, complex, or enum types for which code should be generated from the given item collection.
    ''' Any types for which an ExternalTypeName annotation has been applied in the conceptual model
    ''' metadata (CSDL) are filtered out of the returned list.
    ''' </summary>
    ''' <typeparam name="T">The type of item to return.</typeparam>
    ''' <param name="itemCollection">The item collection to look in.</param>
    ''' <returns>The items to generate.</returns>
    Public Function GetItemsToGenerate(Of T As GlobalItem)(itemCollection As ItemCollection) As IEnumerable(Of T)
        Return itemCollection.GetItems(Of T)().Where(Function(i) Not i.MetadataProperties.Any(Function(p) p.Name = ExternalTypeNameAttributeName))
    End Function

    ''' <summary>
    ''' Returns the escaped type name to use for the given usage of an o-space type. This might be
    ''' an external type name if the ExternalTypeName annotation has been specified in the
    ''' conceptual model metadata (CSDL).
    ''' </summary>
    ''' <param name="typeUsage">The o-space type usage to get a name for.</param>
    ''' <returns>The type name to use.</returns>
    Public Function GetTypeName(typeUsage As TypeUsage) As String
        Return If(typeUsage Is Nothing, Nothing, GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace := Nothing))
    End Function

    ''' <summary>
    ''' Returns the escaped type name to use for the given o-space type. This might be
    ''' an external type name if the ExternalTypeName annotation has been specified in the
    ''' conceptual model metadata (CSDL).
    ''' </summary>
    ''' <param name="edmType">The o-space type to get a name for.</param>
    ''' <returns>The type name to use.</returns>
    Public Function GetTypeName(edmType As EdmType) As String
        Return GetTypeName(edmType, isNullable := Nothing, modelNamespace := Nothing)
    End Function

    ''' <summary>
    ''' Returns the escaped type name to use for the given usage of an o-space type. This might be
    ''' an external type name if the ExternalTypeName annotation has been specified in the
    ''' conceptual model metadata (CSDL).
    ''' </summary>
    ''' <param name="typeUsage">The o-space type usage to get a name for.</param>
    ''' <param name="modelNamespace">If not null and the type's namespace does not match this namespace, then a
    ''' fully qualified name will be returned.</param>
    ''' <returns>The type name to use.</returns>
    Public Function GetTypeName(typeUsage As TypeUsage, modelNamespace As String) As String
        Return If(typeUsage Is Nothing, Nothing, GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace))
    End Function

    ''' <summary>
    ''' Returns the escaped type name to use for the given o-space type. This might be
    ''' an external type name if the ExternalTypeName annotation has been specified in the
    ''' conceptual model metadata (CSDL).
    ''' </summary>
    ''' <param name="edmType">The o-space type to get a name for.</param>
    ''' <param name="modelNamespace">If not null and the type's namespace does not match this namespace, then a
    ''' fully qualified name will be returned.</param>
    ''' <returns>The type name to use.</returns>
    Public Function GetTypeName(edmType As EdmType, modelNamespace As String) As String
        Return GetTypeName(edmType, isNullable := Nothing, modelNamespace := modelNamespace)
    End Function

    ''' <summary>
    ''' Returns the escaped type name to use for the given o-space type. This might be
    ''' an external type name if the ExternalTypeName annotation has been specified in the
    ''' conceptual model metadata (CSDL).
    ''' </summary>
    ''' <param name="edmType">The o-space type to get a name for.</param>
    ''' <param name="isNullable">Set this to true for nullable usage of this type.</param>
    ''' <param name="modelNamespace">If not null and the type's namespace does not match this namespace, then a
    ''' fully qualified name will be returned.</param>
    ''' <returns>The type name to use.</returns>
    Private Function GetTypeName(edmType As EdmType, isNullable As System.Nullable(Of Boolean), modelNamespace As String) As String
        If edmType Is Nothing Then
            Return Nothing
        End If

        Dim collectionType = TryCast(edmType, CollectionType)
        If collectionType IsNot Nothing Then
            Return String.Format(CultureInfo.InvariantCulture, "ICollection( Of {0})", GetTypeName(collectionType.TypeUsage, modelNamespace))
        End If

        Dim typeName = If(Escape(edmType.MetadataProperties.Where(Function(p) p.Name = ExternalTypeNameAttributeName).[Select](Function(p) DirectCast(p.Value, String)).FirstOrDefault()), (If(modelNamespace IsNot Nothing AndAlso edmType.NamespaceName <> modelNamespace, CreateFullName(EscapeNamespace(edmType.NamespaceName), Escape(edmType)), Escape(edmType))))

        If TypeOf edmType Is StructuralType Then
            Return typeName
        End If

        If TypeOf edmType Is SimpleType Then
            Dim clrType = _ef.UnderlyingClrType(edmType)
            If Not (TypeOf edmType Is EnumType) Then
                typeName = Escape(clrType)
            End If

            Return If(clrType.IsValueType AndAlso isNullable = True, String.Format(CultureInfo.InvariantCulture, "Nullable(Of {0})", typeName), typeName)
        End If

        Throw New ArgumentException("typeUsage")
    End Function

End Class

''' <summary>
''' Responsible for making the Entity Framework Metadata more
''' accessible for code generation.
''' </summary>
Public Class MetadataTools
    Private ReadOnly _textTransformation As DynamicTextTransformation

    ''' <summary>
    ''' Initializes an MetadataTools Instance with the
    ''' TextTransformation (T4 generated class) that is currently running
    ''' </summary>
    Public Sub New(ByVal textTransformation As Object)
        If textTransformation Is Nothing Then
            Throw New ArgumentNullException("textTransformation")
        End If

        _textTransformation = DynamicTextTransformation.Create(textTransformation)
    End Sub

    ''' <summary>
    ''' This method returns the underlying CLR type of the O-space type corresponding to the supplied <paramref name="typeUsage"/>
    ''' Note that for an enum type this means that the type backing the enum will be returned, not the enum type itself.
    ''' </summary>
    Public Function ClrType(typeUsage As TypeUsage) As Type
        Return UnderlyingClrType(typeUsage.EdmType)
    End Function

    ''' <summary>
    ''' This method returns the underlying CLR type of given the O-space type.
    ''' Note that for an enum type this means that the type backing the enum will be returned, not the enum type itself.
    ''' </summary>
    Public Function UnderlyingClrType(edmType As EdmType) As Type
        Dim primitiveType = TryCast(edmType, PrimitiveType)
        If primitiveType IsNot Nothing Then
            Return primitiveType.ClrEquivalentType
        End If

        Dim enumType = TryCast(edmType, EnumType)
        If enumType IsNot Nothing Then
            Return enumType.UnderlyingType.ClrEquivalentType
        End If

        Return GetType(Object)
    End Function

    ''' <summary>
    ''' True if the EdmProperty is a key of its DeclaringType, False otherwise.
    ''' </summary>
    Public Function IsKey(ByVal edmProp As EdmProperty) As Boolean
        If edmProp IsNot Nothing AndAlso edmProp.DeclaringType.BuiltInTypeKind = BuiltInTypeKind.EntityType Then
            Return DirectCast(edmProp.DeclaringType, EntityType).KeyMembers.Contains(edmProp)
        End If

        Return False
    End Function

    ''' <summary>
    ''' True if the EdmProperty TypeUsage is Nullable, False otherwise.
    ''' </summary>
    Public Function IsNullable(ByVal edmProp As EdmProperty) As Boolean
        Return edmProp IsNot Nothing AndAlso IsNullable(edmProp.TypeUsage)
    End Function

    ''' <summary>
    ''' True if the TypeUsage is Nullable, False otherwise.
    ''' </summary>
    Public Function IsNullable(ByVal typeUsage As TypeUsage) As Boolean
        Dim nullableFacet As Facet = Nothing
        If typeUsage IsNot Nothing AndAlso typeUsage.Facets.TryGetValue("Nullable", True, nullableFacet) Then
            Return CBool(nullableFacet.Value)
        End If

        Return False
    End Function

    ''' <summary>
    ''' If the passed in TypeUsage represents a collection this method returns final element
    ''' type of the collection, otherwise it returns the value passed in.
    ''' </summary>
    Public Function GetElementType(ByVal typeUsage As TypeUsage) As TypeUsage
        If typeUsage Is Nothing Then
            Return Nothing
        End If

        If TypeOf typeUsage.EdmType Is CollectionType Then
            Return GetElementType(DirectCast(typeUsage.EdmType, CollectionType).TypeUsage)
        Else
            Return typeUsage
        End If
    End Function

    ''' <summary>
    ''' Returns the NavigationProperty that is the other end of the same association set if it is
    ''' available, otherwise it returns null.
    ''' </summary>
    Public Function Inverse(ByVal navProperty As NavigationProperty) As NavigationProperty
        If navProperty Is Nothing Then
            Return Nothing
        End If

        Dim toEntity As EntityType = navProperty.ToEndMember.GetEntityType()
        Return toEntity.NavigationProperties.SingleOrDefault(Function(n) n.RelationshipType Is navProperty.RelationshipType AndAlso n IsNot navProperty)
    End Function

    ''' <summary>
    ''' Given a property on the dependent end of a referential constraint, returns the corresponding property on the principal end.
    ''' Requires: The association has a referential constraint, and the specified dependentProperty is one of the properties on the dependent end.
    ''' </summary>
    Public Function GetCorrespondingPrincipalProperty(ByVal navProperty As NavigationProperty, ByVal dependentProperty As EdmProperty) As EdmProperty
        If navProperty Is Nothing Then
            Throw New ArgumentNullException("navProperty")
        End If

        If dependentProperty Is Nothing Then
            Throw New ArgumentNullException("dependentProperty")
        End If

        Dim fromProperties As ReadOnlyMetadataCollection(Of EdmProperty) = GetPrincipalProperties(navProperty)
        Dim toProperties As ReadOnlyMetadataCollection(Of EdmProperty) = GetDependentProperties(navProperty)
        Return fromProperties(toProperties.IndexOf(dependentProperty))
    End Function

    ''' <summary>
    ''' Given a property on the principal end of a referential constraint, returns the corresponding property on the dependent end.
    ''' Requires: The association has a referential constraint, and the specified principalProperty is one of the properties on the principal end.
    ''' </summary>
    Public Function GetCorrespondingDependentProperty(ByVal navProperty As NavigationProperty, ByVal principalProperty As EdmProperty) As EdmProperty
        If navProperty Is Nothing Then
            Throw New ArgumentNullException("navProperty")
        End If

        If principalProperty Is Nothing Then
            Throw New ArgumentNullException("principalProperty")
        End If

        Dim fromProperties As ReadOnlyMetadataCollection(Of EdmProperty) = GetPrincipalProperties(navProperty)
        Dim toProperties As ReadOnlyMetadataCollection(Of EdmProperty) = GetDependentProperties(navProperty)
        Return toProperties(fromProperties.IndexOf(principalProperty))
    End Function

    ''' <summary>
    ''' Gets the collection of properties that are on the principal end of a referential constraint for the specified navigation property.
    ''' Requires: The association has a referential constraint.
    ''' </summary>
    Public Function GetPrincipalProperties(ByVal navProperty As NavigationProperty) As ReadOnlyMetadataCollection(Of EdmProperty)
        If navProperty Is Nothing Then
            Throw New ArgumentNullException("navProperty")
        End If

        Return DirectCast(navProperty.RelationshipType, AssociationType).ReferentialConstraints(0).FromProperties
    End Function

    ''' <summary>
    ''' Gets the collection of properties that are on the dependent end of a referential constraint for the specified navigation property.
    ''' Requires: The association has a referential constraint.
    ''' </summary>
    Public Function GetDependentProperties(ByVal navProperty As NavigationProperty) As ReadOnlyMetadataCollection(Of EdmProperty)
        If navProperty Is Nothing Then
            Throw New ArgumentNullException("navProperty")
        End If

        Return DirectCast(navProperty.RelationshipType, AssociationType).ReferentialConstraints(0).ToProperties
    End Function

    ''' <summary>
    ''' True if this entity type requires the HandleCascadeDelete method defined and the method has
    ''' not been defined on any base type
    ''' </summary>
    Public Function NeedsHandleCascadeDeleteMethod(itemCollection As ItemCollection, entity As EntityType) As Boolean
        Dim needsMethod As Boolean = ContainsCascadeDeleteAssociation(itemCollection, entity)
        ' Check to make sure no base types have already declared this method
        Dim baseType As EntityType = TryCast(entity.BaseType, EntityType)
        While needsMethod AndAlso baseType IsNot Nothing
            needsMethod = Not ContainsCascadeDeleteAssociation(itemCollection, baseType)
            baseType = TryCast(baseType.BaseType, EntityType)
        End While
        Return needsMethod
    End Function

    ''' <summary>
    ''' True if this entity type participates in any relationships where the other end has an OnDelete
    ''' cascade delete defined, or if it is the dependent in any identifying relationships
    ''' </summary>
    Private Function ContainsCascadeDeleteAssociation(itemCollection As ItemCollection, entity As EntityType) As Boolean
        Return itemCollection.GetItems(Of AssociationType)().Where(Function(a) DirectCast(a.AssociationEndMembers(0).TypeUsage.EdmType, RefType).ElementType Is entity AndAlso IsCascadeDeletePrincipal(a.AssociationEndMembers(1)) OrElse DirectCast(a.AssociationEndMembers(1).TypeUsage.EdmType, RefType).ElementType Is entity AndAlso IsCascadeDeletePrincipal(a.AssociationEndMembers(0))).Any()
    End Function

    ''' <summary>
    ''' True if the source end of the specified navigation property is the principal in an identifying relationship.
    ''' or if the source end has cascade delete defined.
    ''' </summary>
    Public Function IsCascadeDeletePrincipal(ByVal navProperty As NavigationProperty) As Boolean
        If navProperty Is Nothing Then
            Throw New ArgumentNullException("navProperty")
        End If

        Return IsCascadeDeletePrincipal(DirectCast(navProperty.FromEndMember, AssociationEndMember))
    End Function

    ''' <summary>
    ''' True if the specified association end is the principal in an identifying relationship.
    ''' or if the association end has cascade delete defined.
    ''' </summary>
    Public Function IsCascadeDeletePrincipal(ByVal associationEnd As AssociationEndMember) As Boolean
        If associationEnd Is Nothing Then
            Throw New ArgumentNullException("associationEnd")
        End If

        Return associationEnd.DeleteBehavior = OperationAction.Cascade OrElse IsPrincipalEndOfIdentifyingRelationship(associationEnd)
    End Function

    ''' <summary>
    ''' True if the specified association end is the principal end in an identifying relationship.
    ''' In order to be an identifying relationship, the association must have a referential constraint where all of the dependent properties are part of the dependent type's primary key.
    ''' </summary>
    Public Function IsPrincipalEndOfIdentifyingRelationship(ByVal associationEnd As AssociationEndMember) As Boolean
        If associationEnd Is Nothing Then
            Throw New ArgumentNullException("associationEnd")
        End If

        Dim refConstraint As ReferentialConstraint = DirectCast(associationEnd.DeclaringType, AssociationType).ReferentialConstraints.Where(Function(rc) rc.FromRole Is associationEnd).SingleOrDefault()
        If refConstraint IsNot Nothing Then
            Dim entity As EntityType = refConstraint.ToRole.GetEntityType()
            Return Not refConstraint.ToProperties.Where(Function(tp) Not entity.KeyMembers.Contains(tp)).Any()
        End If
        Return False
    End Function

    ''' <summary>
    ''' True if the specified association type is an identifying relationship.
    ''' In order to be an identifying relationship, the association must have a referential constraint where all of the dependent properties are part of the dependent type's primary key.
    ''' </summary>
    Public Function IsIdentifyingRelationship(ByVal association As AssociationType) As Boolean
        If association Is Nothing Then
            Throw New ArgumentNullException("association")
        End If

        Return IsPrincipalEndOfIdentifyingRelationship(association.AssociationEndMembers(0)) OrElse IsPrincipalEndOfIdentifyingRelationship(association.AssociationEndMembers(1))
    End Function

    ''' <summary>
    ''' requires: firstType is not null
    ''' effects: if secondType is among the base types of the firstType, return true,
    ''' otherwise returns false.
    ''' when firstType is same as the secondType, return false.
    ''' </summary>
    Public Function IsSubtypeOf(ByVal firstType As EdmType, ByVal secondType As EdmType) As Boolean
        If secondType Is Nothing Then
            Return False
        End If

        ' walk up firstType hierarchy list
        Dim t As EdmType = firstType.BaseType
        While t IsNot Nothing
            If t.Equals(secondType) Then
                Return True
            End If
            t = t.BaseType
        End While
        Return False
    End Function

    ''' <summary>
    ''' Returns the subtype of the EntityType in the current itemCollection
    ''' </summary>
    Public Function GetSubtypesOf(ByVal type As EntityType, ByVal itemCollection As ItemCollection, ByVal includeAbstractTypes As Boolean) As IEnumerable(Of EntityType)
        Dim subTypes As List(Of EntityType) = New List(Of EntityType)
        If type IsNot Nothing Then
            Dim typesInCollection As IEnumerable(Of EntityType) = itemCollection.GetItems(Of EntityType)()
            For Each typeInCollection As EntityType In typesInCollection
                If type.Equals(typeInCollection) = False AndAlso Me.IsSubtypeOf(typeInCollection, type) Then
                    If includeAbstractTypes OrElse Not typeInCollection.Abstract Then
                        subTypes.Add(typeInCollection)
                    End If
                End If
            Next
        End If
        Return subTypes
    End Function

    Public Shared Function TryGetStringMetadataPropertySetting(ByVal item As MetadataItem, ByVal propertyName As String, ByRef value As String) As Boolean
        Dim [property] As MetadataProperty = item.MetadataProperties.FirstOrDefault(Function(p) p.Name = propertyName)
        If [property] IsNot Nothing Then
            value = DirectCast([property].Value, String)
        End If
        Return value IsNot Nothing
    End Function

End Class

''' <summary>
''' Responsible for loading an EdmItemCollection from a .edmx file or .csdl files
''' </summary>
Public Class MetadataLoader
    Private ReadOnly _textTransformation As DynamicTextTransformation

    ''' <summary>
    ''' Initializes an MetadataLoader Instance with the
    ''' TextTransformation (T4 generated class) that is currently running
    ''' </summary>
    Public Sub New(ByVal textTransformation As Object)
        If textTransformation Is Nothing Then
            Throw New ArgumentNullException("textTransformation")
        End If

        _textTransformation = DynamicTextTransformation.Create(textTransformation)
    End Sub

    ''' <summary>
    ''' Load the metadata for Edm, Store, and Mapping collections and register them
    ''' with a new MetadataWorkspace, returns false if any of the parts can't be
    ''' created, some of the ItemCollections may be registered and usable even if false is
    ''' returned
    ''' </summary>
    Public Function TryLoadAllMetadata(ByVal inputFile As String, ByRef metadataWorkspace As MetadataWorkspace) As Boolean
        metadataWorkspace = New MetadataWorkspace()

        Dim edmItemCollection As EdmItemCollection = CreateEdmItemCollection(inputFile)
        metadataWorkspace.RegisterItemCollection(edmItemCollection)

        Dim storeItemCollection As StoreItemCollection = Nothing
        If TryCreateStoreItemCollection(inputFile, storeItemCollection) Then
            Dim storageMappingItemCollection As StorageMappingItemCollection = Nothing
            If TryCreateStorageMappingItemCollection(inputFile, edmItemCollection, storeItemCollection, storageMappingItemCollection) Then
                metadataWorkspace.RegisterItemCollection(storeItemCollection)
                metadataWorkspace.RegisterItemCollection(storageMappingItemCollection)
                Return True
            End If
        End If

        Return False
    End Function

    ''' <summary>
    ''' Create an EdmItemCollection loaded with the metadata provided
    ''' </summary>
    Public Function CreateEdmItemCollection(ByVal sourcePath As String, ByVal ParamArray referenceSchemas As String()) As EdmItemCollection
        Dim edmItemCollection As EdmItemCollection = Nothing
        If TryCreateEdmItemCollection(sourcePath, referenceSchemas, edmItemCollection) Then
            Return edmItemCollection
        End If

        Return New EdmItemCollection()
    End Function

    ''' <summary>
    ''' Attempts to create a EdmItemCollection from the specified metadata file
    ''' </summary>
    Public Function TryCreateEdmItemCollection(ByVal sourcePath As String, ByRef edmItemCollection As EdmItemCollection) As Boolean
        Return TryCreateEdmItemCollection(sourcePath, Nothing, edmItemCollection)
    End Function

    ''' <summary>
    ''' Attempts to create a EdmItemCollection from the specified metadata file
    ''' </summary>
    Public Function TryCreateEdmItemCollection(ByVal sourcePath As String, ByVal referenceSchemas As String(), ByRef edmItemCollection As EdmItemCollection) As Boolean
        edmItemCollection = Nothing

        If Not ValidateInputPath(sourcePath, _textTransformation) Then
            Return False
        End If

        If referenceSchemas Is Nothing Then
            referenceSchemas = New String(-1) {}
        End If

        Dim itemCollection As ItemCollection = Nothing
        sourcePath = _textTransformation.Host.ResolvePath(sourcePath)
        Dim collectionBuilder As New EdmItemCollectionBuilder(_textTransformation, referenceSchemas.Select(Function(s) _textTransformation.Host.ResolvePath(s)).Where(Function(s) s <> sourcePath))
        If collectionBuilder.TryCreateItemCollection(sourcePath, itemCollection) Then
            edmItemCollection = DirectCast(itemCollection, EdmItemCollection)
        End If

        Return edmItemCollection IsNot Nothing
    End Function

    ''' <summary>
    ''' Attempts to create a StoreItemCollection from the specified metadata file
    ''' </summary>
    Public Function TryCreateStoreItemCollection(ByVal sourcePath As String, ByRef storeItemCollection As StoreItemCollection) As Boolean
        storeItemCollection = Nothing

        If Not ValidateInputPath(sourcePath, _textTransformation) Then
            Return False
        End If

        Dim itemCollection As ItemCollection = Nothing
        Dim collectionBuilder As New StoreItemCollectionBuilder(_textTransformation)
        If collectionBuilder.TryCreateItemCollection(_textTransformation.Host.ResolvePath(sourcePath), itemCollection) Then
            storeItemCollection = DirectCast(itemCollection, StoreItemCollection)
        End If
        Return storeItemCollection IsNot Nothing
    End Function

    ''' <summary>
    ''' Attempts to create a StorageMappingItemCollection from the specified metadata file, EdmItemCollection, and StoreItemCollection
    ''' </summary>
    Public Function TryCreateStorageMappingItemCollection(ByVal sourcePath As String, ByVal edmItemCollection As EdmItemCollection, ByVal storeItemCollection As StoreItemCollection, ByRef storageMappingItemCollection As StorageMappingItemCollection) As Boolean
        storageMappingItemCollection = Nothing

        If Not ValidateInputPath(sourcePath, _textTransformation) Then
            Return False
        End If

        If edmItemCollection Is Nothing Then
            Throw New ArgumentNullException("edmItemCollection")
        End If

        If storeItemCollection Is Nothing Then
            Throw New ArgumentNullException("storeItemCollection")
        End If

        Dim itemCollection As ItemCollection = Nothing
        Dim collectionBuilder As New StorageMappingItemCollectionBuilder(_textTransformation, edmItemCollection, storeItemCollection)
        If collectionBuilder.TryCreateItemCollection(_textTransformation.Host.ResolvePath(sourcePath), itemCollection) Then
            storageMappingItemCollection = DirectCast(itemCollection, StorageMappingItemCollection)
        End If
        Return storageMappingItemCollection IsNot Nothing
    End Function

    ''' <summary>
    ''' Gets the Model Namespace from the provided schema file.
    ''' </summary>
    Public Function GetModelNamespace(ByVal sourcePath As String) As String
        If Not ValidateInputPath(sourcePath, _textTransformation) Then
            Return String.Empty
        End If

        Dim builder As New EdmItemCollectionBuilder(_textTransformation)
        Dim model As XElement = Nothing
        If builder.TryLoadRootElement(_textTransformation.Host.ResolvePath(sourcePath), model) Then
            Dim attribute As XAttribute = model.Attribute("Namespace")
            If attribute IsNot Nothing Then
                Return attribute.Value
            End If
        End If

        Return String.Empty
    End Function

    ''' <summary>
    ''' Returns true if the specified file path is valid
    ''' </summary>
    Private Shared Function ValidateInputPath(sourcePath As String, textTransformation As DynamicTextTransformation) As Boolean
        If String.IsNullOrEmpty(sourcePath) Then
            Throw New ArgumentException("sourcePath")
        End If

        If sourcePath = "$edmxInputFile$" Then
            textTransformation.Errors.Add(New CompilerError(If(textTransformation.Host.TemplateFile, CodeGenerationTools.GetResourceString("Template_CurrentlyRunningTemplate")), -1, -1, String.Empty, _
                CodeGenerationTools.GetResourceString("Template_ReplaceVsItemTemplateToken")))
            Return False
        End If

        Return True
    End Function

    ''' <summary>
    ''' base class for ItemCollectionBuilder classes that
    ''' load the specific types of metadata
    ''' </summary>
    Private MustInherit Class ItemCollectionBuilder
        Private ReadOnly _textTransformation As DynamicTextTransformation
        Private ReadOnly _fileExtension As String
        Private ReadOnly _edmxSectionName As String
        Private ReadOnly _rootElementName As String

        ''' <summary>
        ''' FileExtension for individual (non-edmx) metadata file for this
        ''' specific ItemCollection type
        ''' </summary>
        Public ReadOnly Property FileExtension() As String
            Get
                Return _fileExtension
            End Get
        End Property

        ''' <summary>
        ''' The name of the XmlElement in the .edmx <Runtime> element
        ''' to find this ItemCollection's metadata
        ''' </summary>
        Public ReadOnly Property EdmxSectionName() As String
            Get
                Return _edmxSectionName
            End Get
        End Property

        ''' <summary>
        ''' The name of the root element of this ItemCollection's metadata
        ''' </summary>
        Public ReadOnly Property RootElementName() As String
            Get
                Return _rootElementName
            End Get
        End Property

        ''' <summary>
        ''' Method to build the appropriate ItemCollection
        ''' </summary>
        Protected MustOverride Function CreateItemCollection(ByVal readers As IEnumerable(Of XmlReader), ByRef errors As IList(Of EdmSchemaError)) As ItemCollection

        ''' <summary>
        ''' Ctor to setup the ItemCollectionBuilder members
        ''' </summary>
        Protected Sub New(ByVal textTransformation As DynamicTextTransformation, ByVal fileExtension As String, ByVal edmxSectionName As String, ByVal rootElementName As String)
            _textTransformation = textTransformation
            _fileExtension = fileExtension
            _edmxSectionName = edmxSectionName
            _rootElementName = rootElementName
        End Sub

        ''' <summary>
        ''' Selects a namespace from the supplied constants.
        ''' </summary>
        Protected MustOverride Function GetNamespace(ByVal constants As SchemaConstants) As String

        ''' <summary>
        ''' Try to create an ItemCollection loaded with the metadata provided
        ''' </summary>
        Public Function TryCreateItemCollection(ByVal sourcePath As String, ByRef itemCollection As ItemCollection) As Boolean
            itemCollection = Nothing

            If Not ValidateInputPath(sourcePath, _textTransformation) Then
                Return False
            End If

            Dim schemaElement As XElement = Nothing
            If TryLoadRootElement(sourcePath, schemaElement) Then
                Dim readers As New List(Of XmlReader)()
                Try
                    readers.Add(schemaElement.CreateReader())
                    Dim errors As IList(Of EdmSchemaError) = Nothing

                    Dim tempItemCollection As ItemCollection = CreateItemCollection(readers, errors)
                    If ProcessErrors(errors, sourcePath) Then
                        Return False
                    End If

                    itemCollection = tempItemCollection
                    Return True
                Finally
                    For Each reader As XmlReader In readers
                        DirectCast(reader, IDisposable).Dispose()
                    Next
                End Try
            End If

            Return False
        End Function

        ''' <summary>
        ''' Tries to load the root element from the metadata file provided
        ''' </summary>
        Public Function TryLoadRootElement(ByVal sourcePath As String, ByRef schemaElement As XElement) As Boolean
            schemaElement = Nothing
            Dim extension As String = Path.GetExtension(sourcePath)
            If extension.Equals(".edmx", StringComparison.InvariantCultureIgnoreCase) Then
                Return TryLoadRootElementFromEdmx(sourcePath, schemaElement)
            ElseIf extension.Equals(FileExtension, StringComparison.InvariantCultureIgnoreCase) Then
                ' load from single metadata file (.csdl, .ssdl, or .msl)
                schemaElement = XElement.Load(sourcePath, LoadOptions.SetBaseUri Or LoadOptions.SetLineInfo)
                Return True
            End If

            Return False
        End Function

        ''' <summary>
        ''' Tries to load the root element from the provided edmxDocument
        ''' </summary>
        Private Function TryLoadRootElementFromEdmx(ByVal edmxDocument As XElement, ByVal schemaConstants As SchemaConstants, ByVal sectionName As String, ByVal rootElementName As String, ByRef rootElement As XElement) As Boolean
            rootElement = Nothing

            Dim edmxNs As XNamespace = schemaConstants.EdmxNamespace
            Dim sectionNs As XNamespace = GetNamespace(schemaConstants)

            Dim runtime As XElement = edmxDocument.Element(edmxNs + "Runtime")
            If runtime Is Nothing Then
                Return False
            End If

            Dim section As XElement = runtime.Element(edmxNs + sectionName)
            If section Is Nothing Then
                Return False
            End If

            Dim templateVersion As String = Nothing

            If Not TemplateMetadata.TryGetValue(MetadataConstants.TT_TEMPLATE_VERSION, templateVersion) Then
                templateVersion = MetadataConstants.DEFAULT_TEMPLATE_VERSION
            End If

            If schemaConstants.MinimumTemplateVersion > New Version(templateVersion) Then
                _textTransformation.Errors.Add(New CompilerError(If(_textTransformation.Host.TemplateFile, CodeGenerationTools.GetResourceString("Template_CurrentlyRunningTemplate")), -1, -1, String.Empty, _
                    CodeGenerationTools.GetResourceString("Template_UnsupportedSchema")) With { _
                        .IsWarning = True _
                    })
            End If

            rootElement = section.Element(sectionNs + rootElementName)
            Return rootElement IsNot Nothing
        End Function

        ''' <summary>
        ''' Tries to load the root element from the provided .edmx metadata file
        ''' </summary>
        Private Function TryLoadRootElementFromEdmx(ByVal edmxPath As String, ByRef rootElement As XElement) As Boolean
            rootElement = Nothing

            Dim element As XElement = XElement.Load(edmxPath, LoadOptions.SetBaseUri Or LoadOptions.SetLineInfo)

            Return TryLoadRootElementFromEdmx(element, MetadataConstants.V3_SCHEMA_CONSTANTS, EdmxSectionName, RootElementName, rootElement) OrElse TryLoadRootElementFromEdmx(element, MetadataConstants.V2_SCHEMA_CONSTANTS, EdmxSectionName, RootElementName, rootElement) OrElse TryLoadRootElementFromEdmx(element, MetadataConstants.V1_SCHEMA_CONSTANTS, EdmxSectionName, RootElementName, rootElement)
        End Function

        ''' <summary>
        ''' Takes an Enumerable of EdmSchemaErrors, and adds them
        ''' to the errors collection of the template class
        ''' </summary>
        Private Function ProcessErrors(ByVal errors As IEnumerable(Of EdmSchemaError), ByVal sourceFilePath As String) As Boolean
            Dim foundErrors As Boolean = False
            For Each schemaError As EdmSchemaError In errors
                Dim newError As New CompilerError(schemaError.SchemaLocation, schemaError.Line, schemaError.Column, schemaError.ErrorCode.ToString(CultureInfo.InvariantCulture), schemaError.Message)
                newError.IsWarning = schemaError.Severity = EdmSchemaErrorSeverity.Warning
                foundErrors = foundErrors Or schemaError.Severity = EdmSchemaErrorSeverity.Error
                If schemaError.SchemaLocation Is Nothing Then
                    newError.FileName = sourceFilePath
                End If
                _textTransformation.Errors.Add(newError)
            Next

            Return foundErrors
        End Function
    End Class

    ''' <summary>
    ''' Builder class for creating a StorageMappingItemCollection
    ''' </summary>
    Private Class StorageMappingItemCollectionBuilder
        Inherits ItemCollectionBuilder
        Private ReadOnly _edmItemCollection As EdmItemCollection
        Private ReadOnly _storeItemCollection As StoreItemCollection

        Public Sub New(ByVal textTransformation As DynamicTextTransformation, ByVal edmItemCollection As EdmItemCollection, ByVal storeItemCollection As StoreItemCollection)
            MyBase.New(textTransformation, MetadataConstants.MSL_EXTENSION, MetadataConstants.MSL_EDMX_SECTION_NAME, MetadataConstants.MSL_ROOT_ELEMENT_NAME)
            _edmItemCollection = edmItemCollection
            _storeItemCollection = storeItemCollection
        End Sub

        Protected Overloads Overrides Function CreateItemCollection(ByVal readers As IEnumerable(Of XmlReader), ByRef errors As IList(Of EdmSchemaError)) As ItemCollection
            Return MetadataItemCollectionFactory.CreateStorageMappingItemCollection(_edmItemCollection, _storeItemCollection, readers, errors)
        End Function

        ''' <summary>
        ''' Selects a namespace from the supplied constants.
        ''' </summary>
        Protected Overrides Function GetNamespace(ByVal constants As SchemaConstants) As String
            Return constants.MslNamespace
        End Function
    End Class

    ''' <summary>
    ''' Builder class for creating a StoreItemCollection
    ''' </summary>
    Private Class StoreItemCollectionBuilder
        Inherits ItemCollectionBuilder
        Public Sub New(ByVal textTransformation As DynamicTextTransformation)
            MyBase.New(textTransformation, MetadataConstants.SSDL_EXTENSION, MetadataConstants.SSDL_EDMX_SECTION_NAME, MetadataConstants.SSDL_ROOT_ELEMENT_NAME)
        End Sub

        Protected Overloads Overrides Function CreateItemCollection(ByVal readers As IEnumerable(Of XmlReader), ByRef errors As IList(Of EdmSchemaError)) As ItemCollection
            Return MetadataItemCollectionFactory.CreateStoreItemCollection(readers, errors)
        End Function

        ''' <summary>
        ''' Selects a namespace from the supplied constants.
        ''' </summary>
        Protected Overrides Function GetNamespace(ByVal constants As SchemaConstants) As String
            Return constants.SsdlNamespace
        End Function

    End Class

    ''' <summary>
    ''' Builder class for creating a EdmItemCollection
    ''' </summary>
    Private Class EdmItemCollectionBuilder
        Inherits ItemCollectionBuilder
        Private _referenceSchemas As New List(Of String)()

        Public Sub New(ByVal textTransformation As DynamicTextTransformation)
            MyBase.New(textTransformation, MetadataConstants.CSDL_EXTENSION, MetadataConstants.CSDL_EDMX_SECTION_NAME, MetadataConstants.CSDL_ROOT_ELEMENT_NAME)
        End Sub

        Public Sub New(ByVal textTransformation As DynamicTextTransformation, ByVal referenceSchemas As IEnumerable(Of String))
            Me.New(textTransformation)
            _referenceSchemas.AddRange(referenceSchemas)
        End Sub

        Protected Overloads Overrides Function CreateItemCollection(ByVal readers As IEnumerable(Of XmlReader), ByRef errors As IList(Of EdmSchemaError)) As ItemCollection
            Dim ownedReaders As New List(Of XmlReader)()
            Dim allReaders As New List(Of XmlReader)()
            Try
                allReaders.AddRange(readers)
                For Each path As String In _referenceSchemas.Distinct()
                    Dim reference As XElement = Nothing
                    If TryLoadRootElement(path, reference) Then
                        Dim reader As XmlReader = reference.CreateReader()
                        allReaders.Add(reader)
                        ownedReaders.Add(reader)
                    End If
                Next

                Return MetadataItemCollectionFactory.CreateEdmItemCollection(allReaders, errors)
            Finally
                For Each reader As XmlReader In ownedReaders
                    DirectCast(reader, IDisposable).Dispose()
                Next
            End Try
        End Function

        ''' <summary>
        ''' Selects a namespace from the supplied constants.
        ''' </summary>
        Protected Overrides Function GetNamespace(ByVal constants As SchemaConstants) As String
            Return constants.CsdlNamespace
        End Function
    End Class
End Class

''' <summary>
''' Responsible for encapsulating the retrieval and translation of the CodeGeneration
''' annotations in the EntityFramework Metadata to a form that is useful in code generation.
''' </summary>
Public Class Accessibility
    Private Sub New()
    End Sub
    Private Const GETTER_ACCESS As String = "http://schemas.microsoft.com/ado/2006/04/codegeneration:GetterAccess"
    Private Const SETTER_ACCESS As String = "http://schemas.microsoft.com/ado/2006/04/codegeneration:SetterAccess"
    Private Const TYPE_ACCESS As String = "http://schemas.microsoft.com/ado/2006/04/codegeneration:TypeAccess"
    Private Const METHOD_ACCESS As String = "http://schemas.microsoft.com/ado/2006/04/codegeneration:MethodAccess"
    Private Const ACCESS_PROTECTED As String = "Protected"
    Private Const ACCESS_INTERNAL As String = "Internal"
    Private Const ACCESS_PRIVATE As String = "Private"
    Private Shared ReadOnly AccessibilityRankIdLookup As New Dictionary(Of String, Integer)() From _
        { _
            { "Private", 1}, _
            { "Friend", 2}, _
            { "Protected", 3}, _
            { "Public", 4} _
        }

    ''' <summary>
    ''' Gets the accessibility that should be applied to a type being generated from the provided GlobalItem.
    '''
    ''' defaults to public if no annotation is found.
    ''' </summary>
    Public Shared Function ForType(ByVal item As GlobalItem) As String
        If item Is Nothing Then
            Return Nothing
        End If

        Return GetAccessibility(item, TYPE_ACCESS)
    End Function

    ''' <summary>
    ''' Gets the accessibility that should be applied at the property level for a property being
    ''' generated from the provided EdmMember.
    '''
    ''' defaults to public if no annotation is found.
    ''' </summary>
    Public Shared Function ForProperty(ByVal member As EdmMember) As String
        If member Is Nothing Then
            Return Nothing
        End If

        Dim getterAccess As String = Nothing
        Dim setterAccess As String = Nothing
        Dim propertyAccess As String = Nothing
        CalculatePropertyAccessibility(member, propertyAccess, getterAccess, setterAccess)
        Return propertyAccess
    End Function

    ''' <summary>
    ''' Gets the accessibility that should be applied at the property level for a Read-Only property being
    ''' generated from the provided EdmMember.
    '''
    ''' defaults to public if no annotation is found.
    ''' </summary>
    Public Shared Function ForReadOnlyProperty(ByVal member As EdmMember) As String
        If member Is Nothing Then
            Return Nothing
        End If

        Return GetAccessibility(member, GETTER_ACCESS)
    End Function

    ''' <summary>
    ''' Gets the accessibility that should be applied at the property level for a property being
    ''' generated from the provided EntitySet.
    '''
    ''' defaults to public if no annotation is found.
    ''' </summary>
    Public Shared Function ForReadOnlyProperty(ByVal edmSet As EntitySet) As String
        If edmSet Is Nothing Then
            Return Nothing
        End If

        Return GetAccessibility(edmSet, GETTER_ACCESS)
    End Function

    ''' <summary>
    ''' Gets the accessibility that should be applied at the property level for a Write-Only property being
    ''' generated from the provided EdmMember.
    '''
    ''' defaults to public if no annotation is found.
    ''' </summary>
    Public Shared Function ForWriteOnlyProperty(ByVal member As EdmMember) As String
        If member Is Nothing Then
            Return Nothing
        End If

        Return GetAccessibility(member, SETTER_ACCESS)
    End Function

    ''' <summary>
    ''' Gets the accessibility that should be applied at the get level for a property being
    ''' generated from the provided EdmMember.
    '''
    ''' defaults to empty if no annotation is found or the accessibility is the same as the property level.
    ''' </summary>
    Public Shared Function ForGetter(ByVal member As EdmMember) As String
        If member Is Nothing Then
            Return Nothing
        End If

        Dim getterAccess As String = Nothing
        Dim setterAccess As String = Nothing
        Dim propertyAccess As String = Nothing
        CalculatePropertyAccessibility(member, propertyAccess, getterAccess, setterAccess)
        Return getterAccess
    End Function

    ''' <summary>
    ''' Gets the accessibility that should be applied at the set level for a property being
    ''' generated from the provided EdmMember.
    '''
    ''' defaults to empty if no annotation is found or the accessibility is the same as the property level.
    ''' </summary>
    Public Shared Function ForSetter(ByVal member As EdmMember) As String
        If member Is Nothing Then
            Return Nothing
        End If

        Dim getterAccess As String = Nothing
        Dim setterAccess As String = Nothing
        Dim propertyAccess As String = Nothing
        CalculatePropertyAccessibility(member, propertyAccess, getterAccess, setterAccess)
        Return setterAccess
    End Function

    ''' <summary>
    ''' Gets the accessibility that should be applied to a method being generated from the provided EdmFunction.
    '''
    ''' defaults to public if no annotation is found.
    ''' </summary>
    Public Shared Function ForMethod(ByVal edmFunction As EdmFunction) As String
        If edmFunction Is Nothing Then
            Return Nothing
        End If

        Return GetAccessibility(edmFunction, METHOD_ACCESS)
    End Function

    Private Shared Sub CalculatePropertyAccessibility(ByVal item As MetadataItem, ByRef propertyAccessibility As String, ByRef getterAccessibility As String, ByRef setterAccessibility As String)
        getterAccessibility = GetAccessibility(item, GETTER_ACCESS)
        Dim getterRank As Integer = AccessibilityRankIdLookup(getterAccessibility)

        setterAccessibility = GetAccessibility(item, SETTER_ACCESS)
        Dim setterRank As Integer = AccessibilityRankIdLookup(setterAccessibility)

        Dim propertyRank As Integer = Math.Max(getterRank, setterRank)
        If setterRank = propertyRank Then
            setterAccessibility = String.Empty
        End If

        If getterRank = propertyRank Then
            getterAccessibility = String.Empty
        End If

        propertyAccessibility = AccessibilityRankIdLookup.Where(Function(v) v.Value = propertyRank).Select(Function(v) v.Key).Single()
    End Sub

    Private Shared Function GetAccessibility(ByVal item As MetadataItem, ByVal name As String) As String
        Dim accessibility As String = Nothing
        If MetadataTools.TryGetStringMetadataPropertySetting(item, name, accessibility) Then
            Return TranslateUserAccessibilityToCSharpAccessibility(accessibility)
        End If

        Return "Public"
    End Function

    Private Shared Function TranslateUserAccessibilityToCSharpAccessibility(ByVal userAccessibility As String) As String
        If userAccessibility = ACCESS_PROTECTED Then
            Return "Protected"
        ElseIf userAccessibility = ACCESS_INTERNAL Then
            Return "Friend"
        ElseIf userAccessibility = ACCESS_PRIVATE Then
            Return "Private"
        Else
            ' default to public
            Return "Public"
        End If
    End Function

End Class

''' <summary>
''' Responsible for creating source code regions in code when the loop inside
''' actually produces something.
''' </summary>
Public Class CodeRegion
    Private Const STANDARD_INDENT_LENGTH As Integer = 4

    Private ReadOnly _textTransformation As DynamicTextTransformation
    Private _beforeRegionLength As Integer
    Private _emptyRegionLength As Integer
    Private _regionIndentLevel As Integer = -1

    ''' <summary>
    ''' Initializes an CodeRegion instance with the
    ''' TextTransformation (T4 generated class) that is currently running
    ''' </summary>
    Public Sub New(ByVal textTransformation As Object)
        If textTransformation Is Nothing Then
            Throw New ArgumentNullException("textTransformation")
        End If

        _textTransformation = DynamicTextTransformation.Create(textTransformation)
    End Sub

    ''' <summary>
    ''' Initializes an CodeRegion instance with the
    ''' TextTransformation (T4 generated class) that is currently running,
    ''' and the indent level to start the first region at.
    ''' </summary>
    Public Sub New(ByVal textTransformation As Object, ByVal firstIndentLevel As Integer)
        Me.New(textTransformation)
        If firstIndentLevel < 0 Then
            Throw New ArgumentException("firstIndentLevel")
        End If

        _regionIndentLevel = firstIndentLevel - 1
    End Sub

    ''' <summary>
    ''' Starts the begining of a region
    ''' </summary>
    Public Sub Begin(ByVal regionName As String)
        If regionName Is Nothing Then
            Throw New ArgumentNullException("regionName")
        End If

        Begin(regionName, 1)
    End Sub

    ''' <summary>
    ''' Start the begining of a region, indented
    ''' the numbers of levels specified
    ''' </summary>
    Public Sub Begin(ByVal regionName As String, ByVal levelsToIncreaseIndent As Integer)
        If regionName Is Nothing Then
            Throw New ArgumentNullException("regionName")
        End If

        _beforeRegionLength = _textTransformation.GenerationEnvironment.Length
        _regionIndentLevel += levelsToIncreaseIndent
        _textTransformation.Write(GetIndent(_regionIndentLevel))
        _textTransformation.WriteLine("#Region """ + regionName + """")
        _emptyRegionLength = _textTransformation.GenerationEnvironment.Length
    End Sub

    ''' <summary>
    ''' Ends a region, or totaly removes it if nothing
    ''' was generted since the begining of the region.
    ''' </summary>
    Public Sub [End]()
        [End](1)
    End Sub

    ''' <summary>
    ''' Ends a region, or totaly removes it if nothing
    ''' was generted since the begining of the region, also outdents
    ''' the number of levels specified.
    ''' </summary>
    Public Sub [End](ByVal levelsToDecrease As Integer)
        Dim indentLevel As Integer = _regionIndentLevel
        _regionIndentLevel -= levelsToDecrease

        If _emptyRegionLength = _textTransformation.GenerationEnvironment.Length Then
            _textTransformation.GenerationEnvironment.Length = _beforeRegionLength
        Else
            _textTransformation.WriteLine(String.Empty)
            _textTransformation.Write(GetIndent(indentLevel))
            _textTransformation.WriteLine("#End Region")
            _textTransformation.WriteLine(String.Empty)
        End If
    End Sub

    ''' <summary>
    ''' Gets the current indent level that the next end region statement will be written
    ''' at
    ''' </summary>
    Public ReadOnly Property CurrentIndentLevel() As Integer
        Get
            Return _regionIndentLevel
        End Get
    End Property

    ''' <summary>
    ''' Get a string of spaces equivelent to the number of indents
    ''' desired.
    ''' </summary>
    Public Shared Function GetIndent(ByVal indentLevel As Integer) As String
        If indentLevel < 0 Then
            Throw New ArgumentException("indentLevel")
        End If

        Return String.Empty.PadLeft(indentLevel * STANDARD_INDENT_LENGTH)
    End Function
End Class


''' <summary>
''' Responsible for collecting together the actual method parameters
''' and the parameters that need to be sent to the Execute method.
''' </summary>
Public Class FunctionImportParameter
Private _Source As FunctionParameter
    Public Property Source() As FunctionParameter
        Get
            Return _Source
        End Get
        Set(ByVal value As FunctionParameter)
            _Source = value
        End Set
    End Property
Private _RawFunctionParameterName As String
    Public Property RawFunctionParameterName() As String
        Get
            Return _RawFunctionParameterName
        End Get
        Set(ByVal value As String)
            _RawFunctionParameterName = value
        End Set
    End Property
Private _FunctionParameterName As String
    Public Property FunctionParameterName() As String
        Get
            Return _FunctionParameterName
        End Get
        Set(ByVal value As String)
            _FunctionParameterName = value
        End Set
    End Property
Private _FunctionParameterType As String
    Public Property FunctionParameterType() As String
        Get
            Return _FunctionParameterType
        End Get
        Set(ByVal value As String)
            _FunctionParameterType = value
        End Set
    End Property
Private _LocalVariableName As String
    Public Property LocalVariableName() As String
        Get
            Return _LocalVariableName
        End Get
        Set(ByVal value As String)
            _LocalVariableName = value
        End Set
    End Property
Private _RawClrTypeName As String
    Public Property RawClrTypeName() As String
        Get
            Return _RawClrTypeName
        End Get
        Set(ByVal value As String)
            _RawClrTypeName = value
        End Set
    End Property
Private _ExecuteParameterName As String
    Public Property ExecuteParameterName() As String
        Get
            Return _ExecuteParameterName
        End Get
        Set(ByVal value As String)
            _ExecuteParameterName = value
        End Set
    End Property
Private _EsqlParameterName As String
    Public Property EsqlParameterName() As String
        Get
            Return _EsqlParameterName
        End Get
        Set(ByVal value As String)
            _EsqlParameterName = value
        End Set
    End Property
Private _NeedsLocalVariable As Boolean
    Public Property NeedsLocalVariable() As Boolean
        Get
            Return _NeedsLocalVariable
        End Get
        Set(ByVal value As Boolean)
            _NeedsLocalVariable = value
        End Set
    End Property
Private _IsNullableOfT As Boolean
    Public Property IsNullableOfT() As Boolean
        Get
            Return _IsNullableOfT
        End Get
        Set(ByVal value As Boolean)
            _IsNullableOfT = value
        End Set
    End Property


    ''' <summary>
    ''' Creates a set of FunctionImportParameter objects from the parameters passed in.
    ''' </summary>
    Public Shared Function Create(ByVal parameters As IEnumerable(Of FunctionParameter), ByVal code As CodeGenerationTools, ByVal ef As MetadataTools) As IEnumerable(Of FunctionImportParameter)
        If parameters Is Nothing Then
            Throw New ArgumentNullException("parameters")
        End If

        If code Is Nothing Then
            Throw New ArgumentNullException("code")
        End If

        If ef Is Nothing Then
            Throw New ArgumentNullException("ef")
        End If

        Dim unique As New UniqueIdentifierService()
        Dim importParameters As New List(Of FunctionImportParameter)()
        For Each parameter As FunctionParameter In parameters
            Dim importParameter As New FunctionImportParameter()
            importParameter.Source = parameter
            importParameter.RawFunctionParameterName = unique.AdjustIdentifier(code.CamelCase(parameter.Name))
            importParameter.FunctionParameterName = code.Escape(importParameter.RawFunctionParameterName)
            If parameter.Mode = ParameterMode.In Then
                Dim typeUsage As TypeUsage = parameter.TypeUsage
                importParameter.NeedsLocalVariable = True
                importParameter.FunctionParameterType = code.GetTypeName(typeUsage)
                importParameter.EsqlParameterName = parameter.Name
                Dim clrType As Type = ef.UnderlyingClrType(parameter.TypeUsage.EdmType)
                importParameter.RawClrTypeName = If(TypeOf typeUsage.EdmType Is EnumType, code.GetTypeName(typeUsage.EdmType), code.Escape(clrType))
                importParameter.IsNullableOfT = clrType.IsValueType
            Else
                importParameter.NeedsLocalVariable = False
                importParameter.FunctionParameterType = "ObjectParameter"
                importParameter.ExecuteParameterName = importParameter.FunctionParameterName
            End If
            importParameters.Add(importParameter)
        Next

        ' we save the local parameter uniquification for a second pass to make the visible parameters
        ' as pretty and sensible as possible
        For i As Integer = 0 To importParameters.Count - 1
            Dim importParameter As FunctionImportParameter = importParameters(i)
            If importParameter.NeedsLocalVariable Then
                importParameter.LocalVariableName = unique.AdjustIdentifier(importParameter.RawFunctionParameterName & "Parameter")
                importParameter.ExecuteParameterName = importParameter.LocalVariableName
            End If
        Next

        Return importParameters
    End Function

    '
    ' Class to create unique variables within the same scope
    '
    Private NotInheritable Class UniqueIdentifierService
        Private ReadOnly _knownIdentifiers As HashSet(Of String)

        Public Sub New()
            _knownIdentifiers = New HashSet(Of String)(StringComparer.OrdinalIgnoreCase)
        End Sub

        ''' <summary>
        ''' Given an identifier, makes it unique within the scope by adding
        ''' a suffix (1, 2, 3, ...), and returns the adjusted identifier.
        ''' </summary>
        Public Function AdjustIdentifier(ByVal identifier As String) As String
            ' find a unique name by adding suffix as necessary
            Dim numberOfConflicts As Integer = 0
            Dim adjustedIdentifier As String = identifier

            While Not _knownIdentifiers.Add(adjustedIdentifier)
                numberOfConflicts += 1
                adjustedIdentifier = identifier + numberOfConflicts.ToString(CultureInfo.InvariantCulture)
            End While

            Return adjustedIdentifier
        End Function
    End Class
End Class

''' <summary>
''' Responsible for marking the various sections of the generation,
''' so they can be split up into separate files
''' </summary>
Public Class EntityFrameworkTemplateFileManager
    ''' <summary>
    ''' Creates the VsEntityFrameworkTemplateFileManager if VS is detected, otherwise
    ''' creates the file system version.
    ''' </summary>
    Public Shared Function Create(ByVal textTransformation As Object) As EntityFrameworkTemplateFileManager
        Dim transformation As DynamicTextTransformation = DynamicTextTransformation.Create(textTransformation)
        Dim host As IDynamicHost = transformation.Host

        #If Not PREPROCESSED_TEMPLATE Then
        Dim hostServiceProvider = host.AsIServiceProvider()
        If hostServiceProvider IsNot Nothing Then
            Dim dte = DirectCast(hostServiceProvider.GetService(GetType(EnvDTE.DTE)), EnvDTE.DTE)
            If dte IsNot Nothing Then
                Return New VsEntityFrameworkTemplateFileManager(transformation)
            End If
        End If
        #End If
        Return New EntityFrameworkTemplateFileManager(transformation)
    End Function

    Private NotInheritable Class Block
        Public Name As String
        Public Start As Integer, Length As Integer
    End Class

    Private ReadOnly files As New List(Of Block)()
    Private ReadOnly footer As New Block()
    Private ReadOnly header As New Block()
    Private ReadOnly _textTransformation As DynamicTextTransformation

    ' reference to the GenerationEnvironment StringBuilder on the
    ' TextTransformation object
    Private ReadOnly _generationEnvironment As StringBuilder

    Private m_currentBlock As Block

    ''' <summary>
    ''' Initializes an EntityFrameworkTemplateFileManager Instance  with the
    ''' TextTransformation (T4 generated class) that is currently running
    ''' </summary>
    Private Sub New(ByVal textTransformation As Object)
        If textTransformation Is Nothing Then
            Throw New ArgumentNullException("textTransformation")
        End If

        _textTransformation = DynamicTextTransformation.Create(textTransformation)
        _generationEnvironment = _textTransformation.GenerationEnvironment
    End Sub

    ''' <summary>
    ''' Marks the end of the last file if there was one, and starts a new
    ''' and marks this point in generation as a new file.
    ''' </summary>
    Public Sub StartNewFile(ByVal name As String)
        If name Is Nothing Then
            Throw New ArgumentNullException("name")
        End If

        CurrentBlock = New Block() With { .Name = name }
    End Sub

    Public Sub StartFooter()
        CurrentBlock = footer
    End Sub

    Public Sub StartHeader()
        CurrentBlock = header
    End Sub

    Public Sub EndBlock()
        If CurrentBlock Is Nothing Then
            Exit Sub
        End If

        CurrentBlock.Length = _generationEnvironment.Length - CurrentBlock.Start

        If CurrentBlock IsNot header AndAlso CurrentBlock IsNot footer Then
            files.Add(CurrentBlock)
        End If

        m_currentBlock = Nothing
    End Sub

    ''' <summary>
    ''' Produce the template output files.
    ''' </summary>
    Public Overridable Function Process(Optional split As Boolean = True) As IEnumerable(Of String)
        Dim generatedFileNames As List(Of String) = New List(Of String)()

        If split Then
            EndBlock()

            Dim headerText As String = _generationEnvironment.ToString(header.Start, header.Length)
            Dim footerText As String = _generationEnvironment.ToString(footer.Start, footer.Length)
            Dim outputPath As String = Path.GetDirectoryName(_textTransformation.Host.TemplateFile)

            files.Reverse()

            For Each block As Block In files
                Dim fileName As String = Path.Combine(outputPath, block.Name)
                Dim content = headerText + _generationEnvironment.ToString(block.Start, block.Length) + footerText

                generatedFileNames.Add(fileName)
                CreateFile(fileName, content)
                _generationEnvironment.Remove(block.Start, block.Length)
            Next
        End If

        Return generatedFileNames
    End Function

    Protected Overridable Sub CreateFile(ByVal fileName As String, ByVal content As String)
        If IsFileContentDifferent(fileName, content) Then
            File.WriteAllText(fileName, content)
        End If
    End Sub

    Protected Function IsFileContentDifferent(ByVal fileName As String, ByVal newContent As String) As Boolean
        Return Not (File.Exists(fileName) AndAlso File.ReadAllText(fileName) = newContent)
    End Function

    Private Property CurrentBlock() As Block
        Get
            Return m_currentBlock
        End Get
        Set(ByVal value As Block)
            If CurrentBlock IsNot Nothing Then
                EndBlock()
            End If

            If value IsNot Nothing Then
                value.Start = _generationEnvironment.Length
            End If

            m_currentBlock = value
        End Set
    End Property

    #If Not PREPROCESSED_TEMPLATE Then
    Private NotInheritable Class VsEntityFrameworkTemplateFileManager
        Inherits EntityFrameworkTemplateFileManager
        Private templateProjectItem As EnvDTE.ProjectItem
        Private dte As EnvDTE.DTE
        Private checkOutAction As Action(Of String)
        Private projectSyncAction As Action(Of IEnumerable(Of String))

        ''' <summary>
        ''' Creates an instance of the VsEntityFrameworkTemplateFileManager class with the IDynamicHost instance
        ''' </summary>
        Public Sub New(ByVal textTemplating As Object)
            MyBase.New(textTemplating)
            Dim hostServiceProvider = _textTransformation.Host.AsIServiceProvider()
            If hostServiceProvider Is Nothing Then
                Throw New ArgumentNullException("Could not obtain hostServiceProvider")
            End If

            dte = DirectCast(hostServiceProvider.GetService(GetType(EnvDTE.DTE)), EnvDTE.DTE)
            If dte Is Nothing Then
                Throw New ArgumentNullException("Could not obtain DTE from host")
            End If

            templateProjectItem = dte.Solution.FindProjectItem(_textTransformation.Host.TemplateFile)

            checkOutAction = Function(fileName) dte.SourceControl.CheckOutItem(fileName)
            projectSyncAction = Sub(keepFileNames) ProjectSync(templateProjectItem, keepFileNames)
        End Sub

        Public Overloads Overrides Function Process(Optional split As Boolean = True) As IEnumerable(Of String)
            If templateProjectItem.ProjectItems Is Nothing Then
                Return New List(Of String)
            End If

            Dim generatedFileNames As IEnumerable(Of String) = MyBase.Process(split)

            projectSyncAction.EndInvoke(projectSyncAction.BeginInvoke(generatedFileNames, Nothing, Nothing))

            Return generatedFileNames
        End Function

        Protected Overloads Overrides Sub CreateFile(ByVal fileName As String, ByVal content As String)
            If IsFileContentDifferent(fileName, content) Then
                CheckoutFileIfRequired(fileName)
                File.WriteAllText(fileName, content)
            End If
        End Sub

        Private Shared Sub ProjectSync(ByVal templateProjectItem As EnvDTE.ProjectItem, ByVal keepFileNames As IEnumerable(Of String))
            Dim keepFileNameSet = New HashSet(Of String)(keepFileNames)
            Dim projectFiles = New Dictionary(Of String, EnvDTE.ProjectItem)()
            Dim originalOutput = Path.GetFileNameWithoutExtension(templateProjectItem.FileNames(0))

            For Each projectItem As EnvDTE.ProjectItem In templateProjectItem.ProjectItems
                projectFiles.Add(projectItem.FileNames(0), projectItem)
            Next

            ' Remove unused items from the project
            For Each pair As KeyValuePair(Of String, EnvDTE.ProjectItem) In projectFiles
                If Not keepFileNames.Contains(pair.Key) _
                  AndAlso Not (Path.GetFileNameWithoutExtension(pair.Key) + ".").StartsWith(originalOutput + ".") Then
                    pair.Value.Delete()
                End If
            Next

            ' Add missing files to the project
            For Each fileName As String In keepFileNameSet
                If Not projectFiles.ContainsKey(fileName) Then
                    templateProjectItem.ProjectItems.AddFromFile(fileName)
                End If
            Next
        End Sub

        Private Sub CheckoutFileIfRequired(ByVal fileName As String)
            If dte.SourceControl Is Nothing OrElse Not dte.SourceControl.IsItemUnderSCC(fileName) OrElse dte.SourceControl.IsItemCheckedOut(fileName) Then
                Exit Sub
            End If

            ' run on worker thread to prevent T4 calling back into VS
            checkOutAction.EndInvoke(checkOutAction.BeginInvoke(fileName, Nothing, Nothing))
        End Sub
    End Class
    #End If
End Class

''' <summary>
''' Responsible creating an instance that can be passed
''' to helper classes that need to access the TextTransformation
''' members. It accesses member by name and signature rather than
''' by type. This is necessary when the
''' template is being used in Preprocessed mode
''' and there is no common known type that can be
''' passed instead
''' </summary>
Public Class DynamicTextTransformation
    Private _instance As Object
    Private _dynamicHost As IDynamicHost

    Private ReadOnly _write As MethodInfo
    Private ReadOnly _writeLine As MethodInfo
    Private ReadOnly _generationEnvironment As PropertyInfo
    Private ReadOnly _errors As PropertyInfo
    Private ReadOnly _host As PropertyInfo

    ''' <summary>
    ''' Creates an instance of the DynamicTextTransformation class around the passed in
    ''' TextTransformation shapped instance passed in, or if the passed in instance
    ''' already is a DynamicTextTransformation, it casts it and sends it back.
    ''' </summary>
    Public Shared Function Create(ByVal instance As Object) As DynamicTextTransformation
        If instance Is Nothing Then
            Throw New ArgumentNullException("instance")
        End If

        Dim textTransformation As DynamicTextTransformation = TryCast(instance, DynamicTextTransformation)
        If textTransformation IsNot Nothing Then
            Return textTransformation
        End If

        Return New DynamicTextTransformation(instance)
    End Function

    Private Sub New(ByVal instance As Object)
        _instance = instance
        Dim type As Type = _instance.GetType()
        _write = type.GetMethod("Write", New Type() {GetType(String)})
        _writeLine = type.GetMethod("WriteLine", New Type() {GetType(String)})
        _generationEnvironment = type.GetProperty("GenerationEnvironment", BindingFlags.Instance Or BindingFlags.NonPublic)
        _host = type.GetProperty("Host")
        _errors = type.GetProperty("Errors")
    End Sub

    ''' <summary>
    ''' Gets the value of the wrapped TextTranformation instance's GenerationEnvironment property
    ''' </summary>
    Public ReadOnly Property GenerationEnvironment() As StringBuilder
        Get
            Return DirectCast(_generationEnvironment.GetValue(_instance, Nothing), StringBuilder)
        End Get
    End Property

    ''' <summary>
    ''' Gets the value of the wrapped TextTranformation instance's Errors property
    ''' </summary>
    Public ReadOnly Property Errors() As System.CodeDom.Compiler.CompilerErrorCollection
        Get
            Return DirectCast(_errors.GetValue(_instance, Nothing), System.CodeDom.Compiler.CompilerErrorCollection)
        End Get
    End Property

    ''' <summary>
    ''' Calls the wrapped TextTranformation instance's Write method.
    ''' </summary>
    Public Sub Write(ByVal text As String)
        _write.Invoke(_instance, New Object() {text})
    End Sub

    ''' <summary>
    ''' Calls the wrapped TextTranformation instance's WriteLine method.
    ''' </summary>
    Public Sub WriteLine(ByVal text As String)
        _writeLine.Invoke(_instance, New Object() {text})
    End Sub

    ''' <summary>
    ''' Gets the value of the wrapped TextTranformation instance's Host property
    ''' if available (shows up when hostspecific is set to true in the template directive) and returns
    ''' the appropriate implementation of IDynamicHost
    ''' </summary>
    Public ReadOnly Property Host() As IDynamicHost
        Get
            If _dynamicHost Is Nothing Then
                If _host Is Nothing Then
                    _dynamicHost = New NullHost()
                Else
                    _dynamicHost = New DynamicHost(_host.GetValue(_instance, Nothing))
                End If
            End If
            Return _dynamicHost
        End Get
    End Property
End Class


''' <summary>
''' Reponsible for abstracting the use of Host between times
''' when it is available and not
''' </summary>
Public Interface IDynamicHost
    ''' <summary>
    ''' An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue
    ''' </summary>
    Function ResolveParameterValue(ByVal id As String, ByVal name As String, ByVal otherName As String) As String

    ''' <summary>
    ''' An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath
    ''' </summary>
    Function ResolvePath(ByVal path As String) As String

    ''' <summary>
    ''' An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile
    ''' </summary>
    ReadOnly Property TemplateFile() As String

    ''' <summary>
    ''' Returns the Host instance cast as an IServiceProvider
    ''' </summary>
    Function AsIServiceProvider() As IServiceProvider
End Interface

''' <summary>
''' Reponsible for implementing the IDynamicHost as a dynamic
''' shape wrapper over the Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost interface
''' rather than type dependent wrapper. We don't use the
''' interface type so that the code can be run in preprocessed mode
''' on a .net framework only installed machine.
''' </summary>
Public Class DynamicHost
    Implements IDynamicHost
    Private ReadOnly _instance As Object
    Private ReadOnly _resolveParameterValue As MethodInfo
    Private ReadOnly _resolvePath As MethodInfo
    Private ReadOnly _templateFile As PropertyInfo

    ''' <summary>
    ''' Creates an instance of the DynamicHost class around the passed in
    ''' Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost shapped instance passed in.
    ''' </summary>
    Public Sub New(ByVal instance As Object)
        _instance = instance
        Dim type As Type = _instance.GetType()
        _resolveParameterValue = type.GetMethod("ResolveParameterValue", New Type() {GetType(String), GetType(String), GetType(String)})
        _resolvePath = type.GetMethod("ResolvePath", New Type() {GetType(String)})

        _templateFile = type.GetProperty("TemplateFile")
    End Sub

    ''' <summary>
    ''' A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue
    ''' </summary>
    Public Function ResolveParameterValue(ByVal id As String, ByVal name As String, ByVal otherName As String) As String Implements IDynamicHost.ResolveParameterValue
        Return DirectCast(_resolveParameterValue.Invoke(_instance, New Object() {id, name, otherName}), String)
    End Function

    ''' <summary>
    ''' A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath
    ''' </summary>
    Public Function ResolvePath(ByVal path As String) As String Implements IDynamicHost.ResolvePath
        Return DirectCast(_resolvePath.Invoke(_instance, New Object() {path}), String)
    End Function

    ''' <summary>
    ''' A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile
    ''' </summary>
    Public ReadOnly Property TemplateFile() As String Implements IDynamicHost.TemplateFile
        Get
            Return DirectCast(_templateFile.GetValue(_instance, Nothing), String)
        End Get
    End Property

    ''' <summary>
    ''' Returns the Host instance cast as an IServiceProvider
    ''' </summary>
    Public Function AsIServiceProvider() As IServiceProvider Implements IDynamicHost.AsIServiceProvider
        Return TryCast(_instance, IServiceProvider)
    End Function
End Class

''' <summary>
''' Reponsible for implementing the IDynamicHost when the
''' Host property is not available on the TextTemplating type. The Host
''' property only exists when the hostspecific attribute of the template
''' directive is set to true.
''' </summary>
Public Class NullHost
    Implements IDynamicHost
    ''' <summary>
    ''' An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue
    ''' that simply retuns null.
    ''' </summary>
    Public Function ResolveParameterValue(ByVal id As String, ByVal name As String, ByVal otherName As String) As String Implements IDynamicHost.ResolveParameterValue
        Return Nothing
    End Function

    ''' <summary>
    ''' An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath
    ''' that simply retuns the path passed in.
    ''' </summary>
    Public Function ResolvePath(ByVal path As String) As String Implements IDynamicHost.ResolvePath
        Return path
    End Function

    ''' <summary>
    ''' An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile
    ''' that returns null.
    ''' </summary>
    Public ReadOnly Property TemplateFile() As String Implements IDynamicHost.TemplateFile
        Get
            Return Nothing
        End Get
    End Property

    ''' <summary>
    ''' Returns null.
    ''' </summary>
    Public Function AsIServiceProvider() As IServiceProvider Implements IDynamicHost.AsIServiceProvider
        Return Nothing
    End Function
End Class

''' <summary>
''' Responsible for encapsulating the constants defined in Metadata
''' </summary>
Public NotInheritable Class MetadataConstants
    Private Sub New()
    End Sub

    Public Const CSDL_EXTENSION As String = ".csdl"

    Public Const CSDL_EDMX_SECTION_NAME As String = "ConceptualModels"
    Public Const CSDL_ROOT_ELEMENT_NAME As String = "Schema"
    Public Const EDM_ANNOTATION_09_02 As String = "http://schemas.microsoft.com/ado/2009/02/edm/annotation"

    Public Const SSDL_EXTENSION As String = ".ssdl"

    Public Const SSDL_EDMX_SECTION_NAME As String = "StorageModels"
    Public Const SSDL_ROOT_ELEMENT_NAME As String = "Schema"

    Public Const MSL_EXTENSION As String = ".msl"

    Public Const MSL_EDMX_SECTION_NAME As String = "Mappings"
    Public Const MSL_ROOT_ELEMENT_NAME As String = "Mapping"

    Public Const TT_TEMPLATE_NAME As String = "TemplateName"
    Public Const TT_TEMPLATE_VERSION As String = "TemplateVersion"
    Public Const TT_MINIMUM_ENTITY_FRAMEWORK_VERSION As String = "MinimumEntityFrameworkVersion"

    Public Const DEFAULT_TEMPLATE_VERSION As String = "4.0"

    Public Shared ReadOnly V1_SCHEMA_CONSTANTS As New SchemaConstants(
        "http://schemas.microsoft.com/ado/2007/06/edmx",
        "http://schemas.microsoft.com/ado/2006/04/edm",
        "http://schemas.microsoft.com/ado/2006/04/edm/ssdl",
        "urn:schemas-microsoft-com:windows:storage:mapping:CS",
        New Version("3.5"))

    Public Shared ReadOnly V2_SCHEMA_CONSTANTS As New SchemaConstants(
        "http://schemas.microsoft.com/ado/2008/10/edmx",
        "http://schemas.microsoft.com/ado/2008/09/edm",
        "http://schemas.microsoft.com/ado/2009/02/edm/ssdl",
        "http://schemas.microsoft.com/ado/2008/09/mapping/cs",
        New Version("4.0"))

    Public Shared ReadOnly V3_SCHEMA_CONSTANTS As New SchemaConstants(
        "http://schemas.microsoft.com/ado/2009/11/edmx",
        "http://schemas.microsoft.com/ado/2009/11/edm",
        "http://schemas.microsoft.com/ado/2009/11/edm/ssdl",
        "http://schemas.microsoft.com/ado/2009/11/mapping/cs",
        New Version("5.0"))
End Class

Public Structure SchemaConstants
    Public Sub New(ByVal edmxNamespace As String, ByVal csdlNamespace As String, ByVal ssdlNamespace As String, ByVal mslNamespace As String, ByVal minimumTemplateVersion As Version)
        Me.EdmxNamespace = edmxNamespace
        Me.CsdlNamespace = csdlNamespace
        Me.SsdlNamespace = ssdlNamespace
        Me.MslNamespace = mslNamespace
        Me.MinimumTemplateVersion = minimumTemplateVersion
    End Sub

    Public Property EdmxNamespace() As String
        Get
            Return m_EdmxNamespace
        End Get
        Private Set
            m_EdmxNamespace = Value
        End Set
    End Property
    Private m_EdmxNamespace As String

    Public Property CsdlNamespace() As String
        Get
            Return m_CsdlNamespace
        End Get
        Private Set
            m_CsdlNamespace = Value
        End Set
    End Property
    Private m_CsdlNamespace As String

    Public Property SsdlNamespace() As String
        Get
            Return m_SsdlNamespace
        End Get
        Private Set
            m_SsdlNamespace = Value
        End Set
    End Property
    Private m_SsdlNamespace As String

    Public Property MslNamespace() As String
        Get
            Return m_MslNamespace
        End Get
        Private Set
            m_MslNamespace = Value
        End Set
    End Property
    Private m_MslNamespace As String

    Public Property MinimumTemplateVersion() As Version
        Get
            Return m_MinimumTemplateVersion
        End Get
        Private Set
            m_MinimumTemplateVersion = Value
        End Set
    End Property
    Private m_MinimumTemplateVersion As Version
End Structure

    End Class
    #Region "Base class"
    '''<summary>
    '''Base class for this transformation
    '''</summary>
    <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "11.0.0.0")>  _
    Public Class VBCodeGenTemplateBase
        #Region "Fields"
        Private generationEnvironmentField As Global.System.Text.StringBuilder
        Private errorsField As Global.System.CodeDom.Compiler.CompilerErrorCollection
        Private indentLengthsField As Global.System.Collections.Generic.List(Of Integer)
        Private currentIndentField As String = ""
        Private endsWithNewline As Boolean
        Private sessionField As Global.System.Collections.Generic.IDictionary(Of String, Object)
        #End Region
        #Region "Properties"
        '''<summary>
        '''The string builder that generation-time code is using to assemble generated output
        '''</summary>
        Protected Property GenerationEnvironment() As System.Text.StringBuilder
            Get
                If (Me.generationEnvironmentField Is Nothing) Then
                    Me.generationEnvironmentField = New Global.System.Text.StringBuilder()
                End If
                Return Me.generationEnvironmentField
            End Get
            Set
                Me.generationEnvironmentField = value
            End Set
        End Property
        '''<summary>
        '''The error collection for the generation process
        '''</summary>
        Public ReadOnly Property Errors() As System.CodeDom.Compiler.CompilerErrorCollection
            Get
                If (Me.errorsField Is Nothing) Then
                    Me.errorsField = New Global.System.CodeDom.Compiler.CompilerErrorCollection()
                End If
                Return Me.errorsField
            End Get
        End Property
        '''<summary>
        '''A list of the lengths of each indent that was added with PushIndent
        '''</summary>
        Private ReadOnly Property indentLengths() As System.Collections.Generic.List(Of Integer)
            Get
                If (Me.indentLengthsField Is Nothing) Then
                    Me.indentLengthsField = New Global.System.Collections.Generic.List(Of Integer)()
                End If
                Return Me.indentLengthsField
            End Get
        End Property
        '''<summary>
        '''Gets the current indent we use when adding lines to the output
        '''</summary>
        Public ReadOnly Property CurrentIndent() As String
            Get
                Return Me.currentIndentField
            End Get
        End Property
        '''<summary>
        '''Current transformation session
        '''</summary>
        Public Overridable Property Session() As Global.System.Collections.Generic.IDictionary(Of String, Object)
            Get
                Return Me.sessionField
            End Get
            Set
                Me.sessionField = value
            End Set
        End Property
        #End Region
        #Region "Transform-time helpers"
        '''<summary>
        '''Write text directly into the generated output
        '''</summary>
        Public Overloads Sub Write(ByVal textToAppend As String)
            If String.IsNullOrEmpty(textToAppend) Then
                Return
            End If
            'If we're starting off, or if the previous text ended with a newline,
            'we have to append the current indent first.
            If ((Me.GenerationEnvironment.Length = 0)  _
                        OrElse Me.endsWithNewline) Then
                Me.GenerationEnvironment.Append(Me.currentIndentField)
                Me.endsWithNewline = false
            End If
            'Check if the current text ends with a newline
            If textToAppend.EndsWith(Global.System.Environment.NewLine, Global.System.StringComparison.CurrentCulture) Then
                Me.endsWithNewline = true
            End If
            'This is an optimization. If the current indent is "", then we don't have to do any
            'of the more complex stuff further down.
            If (Me.currentIndentField.Length = 0) Then
                Me.GenerationEnvironment.Append(textToAppend)
                Return
            End If
            'Everywhere there is a newline in the text, add an indent after it
            textToAppend = textToAppend.Replace(Global.System.Environment.NewLine, (Global.System.Environment.NewLine + Me.currentIndentField))
            'If the text ends with a newline, then we should strip off the indent added at the very end
            'because the appropriate indent will be added when the next time Write() is called
            If Me.endsWithNewline Then
                Me.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - Me.currentIndentField.Length))
            Else
                Me.GenerationEnvironment.Append(textToAppend)
            End If
        End Sub
        '''<summary>
        '''Write text directly into the generated output
        '''</summary>
        Public Overloads Sub WriteLine(ByVal textToAppend As String)
            Me.Write(textToAppend)
            Me.GenerationEnvironment.AppendLine
            Me.endsWithNewline = true
        End Sub
        '''<summary>
        '''Write formatted text directly into the generated output
        '''</summary>
        Public Overloads Sub Write(ByVal format As String, <System.ParamArrayAttribute()> ByVal args() As Object)
            Me.Write(String.Format(Global.System.Globalization.CultureInfo.CurrentCulture, format, args))
        End Sub
        '''<summary>
        '''Write formatted text directly into the generated output
        '''</summary>
        Public Overloads Sub WriteLine(ByVal format As String, <System.ParamArrayAttribute()> ByVal args() As Object)
            Me.WriteLine(String.Format(Global.System.Globalization.CultureInfo.CurrentCulture, format, args))
        End Sub
        '''<summary>
        '''Raise an error
        '''</summary>
        Public Sub [Error](ByVal message As String)
            Dim [error] As System.CodeDom.Compiler.CompilerError = New Global.System.CodeDom.Compiler.CompilerError()
            [error].ErrorText = message
            Me.Errors.Add([error])
        End Sub
        '''<summary>
        '''Raise a warning
        '''</summary>
        Public Sub Warning(ByVal message As String)
            Dim [error] As System.CodeDom.Compiler.CompilerError = New Global.System.CodeDom.Compiler.CompilerError()
            [error].ErrorText = message
            [error].IsWarning = true
            Me.Errors.Add([error])
        End Sub
        '''<summary>
        '''Increase the indent
        '''</summary>
        Public Sub PushIndent(ByVal indent As String)
            If (indent = Nothing) Then
                Throw New Global.System.ArgumentNullException("indent")
            End If
            Me.currentIndentField = (Me.currentIndentField + indent)
            Me.indentLengths.Add(indent.Length)
        End Sub
        '''<summary>
        '''Remove the last indent that was added with PushIndent
        '''</summary>
        Public Function PopIndent() As String
            Dim returnValue As String = ""
            If (Me.indentLengths.Count > 0) Then
                Dim indentLength As Integer = Me.indentLengths((Me.indentLengths.Count - 1))
                Me.indentLengths.RemoveAt((Me.indentLengths.Count - 1))
                If (indentLength > 0) Then
                    returnValue = Me.currentIndentField.Substring((Me.currentIndentField.Length - indentLength))
                    Me.currentIndentField = Me.currentIndentField.Remove((Me.currentIndentField.Length - indentLength))
                End If
            End If
            Return returnValue
        End Function
        '''<summary>
        '''Remove any indentation
        '''</summary>
        Public Sub ClearIndent()
            Me.indentLengths.Clear
            Me.currentIndentField = ""
        End Sub
        #End Region
        #Region "ToString Helpers"
        '''<summary>
        '''Utility class to produce culture-oriented representation of an object as a string.
        '''</summary>
        Public Class ToStringInstanceHelper
            Private formatProviderField  As System.IFormatProvider = Global.System.Globalization.CultureInfo.InvariantCulture
            '''<summary>
            '''Gets or sets format provider to be used by ToStringWithCulture method.
            '''</summary>
            Public Property FormatProvider() As System.IFormatProvider
                Get
                    Return Me.formatProviderField 
                End Get
                Set
                    If (Not (value) Is Nothing) Then
                        Me.formatProviderField  = value
                    End If
                End Set
            End Property
            '''<summary>
            '''This is called from the compile/run appdomain to convert objects within an expression block to a string
            '''</summary>
            Public Function ToStringWithCulture(ByVal objectToConvert As Object) As String
                If (objectToConvert Is Nothing) Then
                    Throw New Global.System.ArgumentNullException("objectToConvert")
                End If
                Dim t As System.Type = objectToConvert.GetType
                Dim method As System.Reflection.MethodInfo = t.GetMethod("ToString", New System.Type() {GetType(System.IFormatProvider)})
                If (method Is Nothing) Then
                    Return objectToConvert.ToString
                Else
                    Return CType(method.Invoke(objectToConvert, New Object() {Me.formatProviderField }),String)
                End If
            End Function
        End Class
        Private toStringHelperField As ToStringInstanceHelper = New ToStringInstanceHelper()
        '''<summary>
        '''Helper to produce culture-oriented representation of an object as a string
        '''</summary>
        Public ReadOnly Property ToStringHelper() As ToStringInstanceHelper
            Get
                Return Me.toStringHelperField
            End Get
        End Property
        #End Region
    End Class
    #End Region
End Namespace
$Imports System
Imports System.Linq
Imports System.IO
Imports System.Collections.Generic
Imports System.Data.Objects
Imports System.Data.Objects.DataClasses
Imports System.Xml
Imports System.Xml.Linq
Imports System.Globalization
Imports System.Reflection
Imports System.Data.Metadata.Edm
Imports System.Data.Mapping
Imports System.Data.Entity.Design
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports Microsoft.VisualBasic
Imports System.Text

'------------------------------------------------------------------------------
'<auto-generated>
'    This code was generated by a tool.
'    Runtime Version: 11.0.0.0
' 
'    Changes to this file may cause incorrect behavior and will be lost if
'    the code is regenerated.
'</auto-generated>
'------------------------------------------------------------------------------
Namespace TemplateCodeGenerators
    '''<summary>
    '''Class to produce the template output
    '''</summary>
    <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "11.0.0.0")>  _
    Partial Public Class VBCodeGenTemplateV50
        Inherits VBCodeGenTemplateV50Base
        '''<summary>
        '''Create the template output
        '''</summary>
        Public Overridable Function TransformText() As String


' 
' 
' 
'
' 
' 
' 
' 
' 
' 
' 
' 
'
' 
' 
' 
' 




DefineMetadata()

Dim userSettings As UserSettings =
    New UserSettings With _
    { _
        .SourceCsdlPath = "$edmxInputFile$", _
        .ReferenceCsdlPaths = new string () {}, _
        .FullyQualifySystemTypes = True, _
        .CreateContextAddToMethods = True, _
        .CamelCaseFields = False _
    }

ApplyUserSettings(userSettings)
If Errors.HasErrors
    Return String.Empty
End If
Dim loader As New MetadataLoader(Me)
Dim ef As New MetadataTools(Me)
Dim region As New CodeRegion(Me)
Dim code As New CodeGenerationTools(Me) With {.FullyQualifySystemTypes = userSettings.FullyQualifySystemTypes, .CamelCaseFields = userSettings.CamelCaseFields}

ItemCollection = loader.CreateEdmItemCollection(SourceCsdlPath, ReferenceCsdlPaths.ToArray())
ModelNamespace = loader.GetModelNamespace(SourceCsdlPath)
Dim namespaceName As String = GetNamespaceName(code)
UpdateObjectNamespaceMap(namespaceName)

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"'------------------------------------------------------------------------------"& _ 
                    ""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"' <auto-generated>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine1")))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"'"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine2")))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine3")))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"' </auto-generated>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"'---------------------------------------------------------"& _ 
                    "---------------------"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"Imports System"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"Imports System.ComponentModel"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"Imports "& _ 
                    "System.Data.EntityClient"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"Imports System.Data.Objects"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"Imports System.Data.Objec"& _ 
                    "ts.DataClasses"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"Imports System.Linq"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"Imports System.Runtime.Serialization"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"Impor"& _ 
                    "ts System.Xml.Serialization"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"<Assembly: EdmSchemaAttribute(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture)))

            Me.Write(""")>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


    ''''''''
    '''''''' Write Relationship Attributes.
    ''''''''
    region.Begin(CodeGenerationTools.GetResourceString("Template_RegionRelationships"))
    For Each association As AssociationType in GetSourceSchemaTypes(Of AssociationType)()

            Me.Write("<Assembly: EdmRelationshipAttribute(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(association.NamespaceName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(association.Name))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(EndName(association, 0)))

            Me.Write(""", ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(EndMultiplicity(association, 0, code)))

            Me.Write(", GetType(")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(EscapeEndTypeName(association, 0, code)))

            Me.Write("), """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(EndName(association, 1)))

            Me.Write(""", ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(EndMultiplicity(association, 1, code)))

            Me.Write(", GetType(")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(EscapeEndTypeName(association, 1, code)))

            Me.Write(")")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.StringBefore(", ", If(association.IsForeignKey, "True", Nothing))))

            Me.Write(")>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


    Next
    region.End()

    If(Not String.IsNullOrEmpty(namespaceName)) Then

            Me.Write("Namespace ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(namespaceName))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        PushIndent(CodeRegion.GetIndent(1))
    End If

    ''''''''
    '''''''' 
    ''''''''
    region.Begin(CodeGenerationTools.GetResourceString("Template_RegionContexts"))
    For Each container as EntityContainer in GetSourceSchemaTypes(Of EntityContainer)()

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(container)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(container, region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))

            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForType(container)))

            Me.Write(" Partial Class ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(container)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Inherits ObjectContext"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    #Region """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(CodeGenerationTools.GetResourceString("Template_RegionConstructors")))

            Me.Write(""""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_ContextDefaultCtorComment"), container.Name, container.Name)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Public Sub New()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        MyBase.New(""name=")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(container.Name))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(container.Name))

            Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        WriteLazyLoadingEnabled(container)

            Me.Write("        OnContextCreated()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_ContextCommonCtorComment"), container.Name)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Public Sub New(ByVal connectionString As String)"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"     "& _ 
                    "   MyBase.New(connectionString, """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(container.Name))

            Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        WriteLazyLoadingEnabled(container)

            Me.Write("        OnContextCreated()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_ContextCommonCtorComment"), container.Name)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Public Sub New(ByVal connection As EntityConnection)"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&" "& _ 
                    "       MyBase.New(connection, """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(container.Name))

            Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        WriteLazyLoadingEnabled(container)

            Me.Write("        OnContextCreated()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    #End Region"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    #Region """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(CodeGenerationTools.GetResourceString("Template_RegionPartialMethods")))

            Me.Write(""""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Partial Private Sub OnContextCreated()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    #End Region"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)& _ 
                    ""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        ''''''''
        '''''''' 
        ''''''''
        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionObjectSetProperties"))
        For Each entitySet As EntitySet In container.BaseEntitySets.OfType(Of EntitySet)()
            VerifyEntityTypeAndSetAccessibilityCompatability(entitySet)

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(entitySet)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(entitySet, region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(entitySet))))


            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForReadOnlyProperty(entitySet)))

            Me.Write(" ReadOnly Property ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(entitySet)))

            Me.Write("() As ObjectSet(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(entitySet.ElementType, code)))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            If (")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(entitySet)))

            Me.Write(" Is Nothing) Then"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"                ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(entitySet)))

            Me.Write(" = MyBase.CreateObjectSet(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(entitySet.ElementType, code)))

            Me.Write(")(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(entitySet.Name))

            Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            End If"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            Return ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(entitySet)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Property"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Private ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(entitySet)))

            Me.Write(" As ObjectSet(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(entitySet.ElementType, code)))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        Next
        region.End()

        ''''''''
        '''''''' 
        ''''''''
        '''''''' 
        '''''''' 
        ''''''''
        '''''''' 
        '''''''' 
        '''''''' 
        ''''''''
        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionAddToMethods"))
        Dim addToMethods As IEnumerable(Of EntitySet) = If(CreateContextAddToMethods.Value, container.BaseEntitySets.OfType(Of EntitySet)(), Enumerable.Empty(Of EntitySet)())
        For Each addTo As EntitySet in addToMethods
        Dim parameterName As String = code.Escape(FixParameterName(addTo.ElementType.Name, code))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_GenCommentAddToMethodVb"), addTo.Name)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForType(addTo.ElementType)))

            Me.Write(" Sub AddTo")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(addTo.Name))

            Me.Write("(ByVal ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameterName))

            Me.Write(" As ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(addTo.ElementType, code)))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        MyBase.AddObject(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(addTo.Name))

            Me.Write(""", ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(parameterName))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        Next
        region.End()

        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionFunctionImports"))
        For Each edmFunction As EdmFunction in container.FunctionImports
            Dim parameters As IEnumerable(Of FunctionImportParameter) = FunctionImportParameter.Create(edmFunction.Parameters, code, ef)
            Dim paramList As String = String.Join(", ", parameters.Select(Function(p) p.FunctionParameterName & " As " & p.FunctionParameterType).ToArray())
            Dim returnType As TypeUsage = If(edmFunction.ReturnParameters.Count = 0, Nothing, ef.GetElementType(edmFunction.ReturnParameters(0).TypeUsage))
            If edmFunction.IsComposableAttribute Then

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(edmFunction)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel)))


            Me.Write(Me.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(Function(p) New Tuple(Of string, string)(p.RawFunctionParameterName, SummaryComment(p.Source))), region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <EdmFunction(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(edmFunction.NamespaceName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(edmFunction.Name))

            Me.Write(""")>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(edmFunction))))


            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForMethod(edmFunction)))

            Me.Write(" Function ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(edmFunction)))

            Me.Write("(")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(paramList))

            Me.Write(") As IQueryable(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(returnType, code)))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


                WriteFunctionParameters(parameters)

            Me.Write("        Return MyBase.CreateQuery(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(returnType, code)))

            Me.Write(")(""[")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(edmFunction.NamespaceName))

            Me.Write("].[")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(edmFunction.Name))

            Me.Write("](")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(String.Join(", ", parameters.Select(Function(p) "@" + p.EsqlParameterName).ToArray())))

            Me.Write(")""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.StringBefore(", ", String.Join(", ", parameters.Select(Function(p) p.ExecuteParameterName).ToArray()))))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Function"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


            Else

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(edmFunction)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel)))


            Me.Write(Me.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(Function(p) New Tuple(Of string, string)(p.RawFunctionParameterName, SummaryComment(p.Source))), region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(edmFunction))))


            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForMethod(edmFunction)))

            Me.Write(" Function ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(edmFunction)))

            Me.Write("(")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(paramList))

            Me.Write(") As ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(If(returnType IsNot Nothing, "ObjectResult(Of " & MultiSchemaEscape(returnType, code) & ")", "Integer")))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


                WriteFunctionParameters(parameters)

            Me.Write("        Return MyBase.ExecuteFunction")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(If(returnType Is Nothing, "", "(Of " & MultiSchemaEscape(returnType, code) & ")")))

            Me.Write("(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(edmFunction.Name))

            Me.Write("""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.StringBefore(", ", String.Join(", ", parameters.Select(Function(p) p.ExecuteParameterName).ToArray()))))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Function"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


                If (returnType IsNot Nothing AndAlso returnType.EdmType.BuiltInTypeKind = BuiltInTypeKind.EntityType)

            Me.Write("    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(edmFunction)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <param name=""mergeOption""></param>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(Function(p) New Tuple(Of string, string)(p.RawFunctionParameterName, SummaryComment(p.Source))), region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(edmFunction))))


            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForMethod(edmFunction)))

            Me.Write(" Function ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(edmFunction)))

            Me.Write("(")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.StringAfter(paramList, ", ")))

            Me.Write("mergeOption As MergeOption) As ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(If(returnType IsNot Nothing, "ObjectResult(Of " & MultiSchemaEscape(returnType, code) & ")", "Integer")))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


                    WriteFunctionParameters(parameters)

            Me.Write("        Return MyBase.ExecuteFunction(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(returnType, code)))

            Me.Write(")(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(edmFunction.Name))

            Me.Write(""", mergeOption")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.StringBefore(", ", String.Join(", ", parameters.Select(Function(p) p.ExecuteParameterName).ToArray()))))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Function"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


                End If
            End If
        Next
        region.End()

            Me.Write("End Class"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        If Not code.VerifyCaseInsensitiveEntitySetUniqueness(container.BaseEntitySets.OfType(Of EntitySet)().Select(Function(e) e.Name), _
                container.Name, SourceCsdlPath) Then
            Return String.Empty
        End If

    Next
    region.End()

    ''''''''
    '''''''' 
    ''''''''
    region.Begin(CodeGenerationTools.GetResourceString("Template_RegionEntities"))
    For Each loopEntity As EntityType in GetSourceSchemaTypes(Of EntityType)().OrderBy(Function(e) e.Name)
        Dim entity As EntityType = loopEntity

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(entity)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(entity, region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"<EdmEntityTypeAttribute(NamespaceName:=""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(entity.NamespaceName))

            Me.Write(""", Name:=""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(entity.Name))

            Me.Write(""")>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"<Serializable()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"<DataContractAttribute(IsReference:=True)>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        For Each subType As EntityType in ItemCollection.GetItems(Of EntityType)().Where(Function(b) b.BaseType is entity)

            Me.Write("<KnownTypeAttribute(GetType(")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(subType, code)))

            Me.Write("))>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        Next


            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForType(entity)))

            Me.Write(" ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(code.MustInheritOption(entity))))

            Me.Write("Partial Class ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(entity)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Inherits ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(BaseTypeName(entity, code)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        If(Not entity.Abstract) Then
            WriteFactoryMethod(entity, code)
        End If

        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionSimpleProperties"))
        For Each edmProperty As EdmProperty in entity.Properties.Where(Function(p) p.DeclaringType Is entity AndAlso TypeOf p.TypeUsage.EdmType Is SimpleType)
            VerifyGetterAndSetterAccessibilityCompatability(edmProperty)
            WriteSimpleTypeProperty(edmProperty, code)
        Next
        region.End()

        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionComplexProperties"))
        For Each edmProperty As EdmProperty in entity.Properties.Where(Function(p) p.DeclaringType Is entity AndAlso TypeOf p.TypeUsage.EdmType Is ComplexType)
            VerifyGetterAndSetterAccessibilityCompatability(edmProperty)
            WriteComplexTypeProperty(edmProperty, code)
        Next
        region.End()

        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionNavigationProperties"))
        For Each navProperty As NavigationProperty in entity.NavigationProperties.Where(Function(n) n.DeclaringType Is entity)

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(navProperty)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(navProperty, region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <XmlIgnoreAttribute()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <SoapIgnoreAttribute()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <DataMemberAttribu"& _ 
                    "te()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <EdmRelationshipNavigationPropertyAttribute(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.NamespaceName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.Name))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name))

            Me.Write(""")>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


            If(navProperty.ToEndMember.RelationshipMultiplicity = RelationshipMultiplicity.Many) Then

            Me.Write("     ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(navProperty))))


            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(navProperty)))

            Me.Write(" Property ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(navProperty)))

            Me.Write("() As EntityCollection(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(navProperty))))

            Me.Write("Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            Return CType(Me,IEntityWithRelationships).RelationshipManager.Ge"& _ 
                    "tRelatedCollection(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(")(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name))

            Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter(navProperty))))

            Me.Write("Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            If (Not value Is Nothing)"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"                CType(Me, IEntityWith"& _ 
                    "Relationships).RelationshipManager.InitializeRelatedCollection(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(")(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name))

            Me.Write(""", value)"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            End If"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Property"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


           Else

            Me.Write("    ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(navProperty))))


            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(navProperty)))

            Me.Write(" Property ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(navProperty)))

            Me.Write("() As ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(navProperty))))

            Me.Write("Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            Return CType(Me, IEntityWithRelationships).RelationshipManager.G"& _ 
                    "etRelatedReference(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(")(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name))

            Me.Write(""").Value"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter(navProperty))))

            Me.Write("Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            CType(Me, IEntityWithRelationships).RelationshipManager.GetRelat"& _ 
                    "edReference(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(")(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name))

            Me.Write(""").Value = value"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Property"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        Dim refPropertyName As String = navProperty.Name & "Reference"
        If(entity.Members.Any(Function(m) m.Name = refPropertyName)) Then
            '
            Errors.Add(New System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6017",
                String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_ConflictingGeneratedNavPropName"), navProperty.Name, entity.FullName, refPropertyName)))
        End If

            Me.Write("    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(navProperty)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(navProperty, region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <BrowsableAttribute(False)>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <DataMemberAttribute()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(navProperty)))

            Me.Write(" Property ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(refPropertyName))

            Me.Write("() As EntityReference(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(navProperty))))

            Me.Write("Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            Return CType(Me, IEntityWithRelationships).RelationshipManager.G"& _ 
                    "etRelatedReference(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(")(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name))

            Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter(navProperty))))

            Me.Write("Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            If (Not value Is Nothing)"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"                CType(Me, IEntityWith"& _ 
                    "Relationships).RelationshipManager.InitializeRelatedReference(Of ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(navProperty.ToEndMember.GetEntityType(), code)))

            Me.Write(")(""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.RelationshipType.FullName))

            Me.Write(""", """)

            Me.Write(Me.ToStringHelper.ToStringWithCulture(navProperty.ToEndMember.Name))

            Me.Write(""", value)"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            End If"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Property"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


            End If
        Next
        region.End()

            Me.Write("End Class"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        If Not code.VerifyCaseInsensitiveMemberUniqueness(code.GetAllDeclaredMembers(entity), entity.FullName, SourceCsdlPath) Then
            Return String.Empty
        End If
    Next
    region.End()

    ''''''''
    '''''''' 
    ''''''''
    region.Begin(CodeGenerationTools.GetResourceString("Template_RegionComplexTypes"))
    For Each  loopComplex As ComplexType in GetSourceSchemaTypes(Of ComplexType)().OrderBy(Function(e) e.Name)
        Dim complex As ComplexType = loopComplex

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(complex)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(complex, region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"<EdmComplexTypeAttribute(NamespaceName:=""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(complex.NamespaceName))

            Me.Write(""", Name:=""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(complex.Name))

            Me.Write(""")>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"<DataContractAttribute(IsReference:=True)>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"<Serializable()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))

            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForType(complex)))

            Me.Write(" Partial Class ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(complex)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Inherits ComplexObject"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        WriteFactoryMethod(complex, code)

        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionSimpleProperties"))
        For Each edmProperty As EdmProperty in complex.Properties.Where(Function(p) p.DeclaringType Is complex AndAlso TypeOf p.TypeUsage.EdmType Is SimpleType)
            VerifyGetterAndSetterAccessibilityCompatability(edmProperty)
            WriteSimpleTypeProperty(edmProperty, code)
        Next
        region.End()

        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionComplexProperties"))
        For Each edmProperty As EdmProperty in complex.Properties.Where(Function(p) p.DeclaringType Is complex AndAlso TypeOf p.TypeUsage.EdmType Is ComplexType)
            VerifyGetterAndSetterAccessibilityCompatability(edmProperty)
            WriteComplexTypeProperty(edmProperty, code)
        Next
        region.End()

            Me.Write("End Class"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        If Not code.VerifyCaseInsensitiveMemberUniqueness(code.GetAllDeclaredMembers(complex), complex.FullName, SourceCsdlPath) Then
            Return String.Empty
        End If
    Next
    region.End()


    ''''''''
    '''''''' 
    ''''''''
    region.Begin(CodeGenerationTools.GetResourceString("Template_RegionEnumTypes"))
    For Each enumType As EnumType in GetSourceSchemaTypes(Of EnumType)().OrderBy(Function(e) e.Name)

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(enumType)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(enumType, region.CurrentIndentLevel)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"<EdmEnumTypeAttribute(NamespaceName:=""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(enumType.NamespaceName))

            Me.Write(""", Name:=""")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(enumType.Name))

            Me.Write(""")>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"<DataContractAttribute()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        If enumType.IsFlags Then

            Me.Write("<FlagsAttribute()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        End If


            Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForType(enumType)))

            Me.Write(" Enum ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(enumType)))

            Me.Write(" As ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(enumType.UnderlyingType.ClrEquivalentType, fullyQualifySystemTypes:= False)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        For Each member As EnumMember In enumType.Members

            Me.Write("    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(member)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(member, region.CurrentIndentLevel + 1)))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <EnumMemberAttribute()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(member)))

            Me.Write(" = ")

            Me.Write(Me.ToStringHelper.ToStringWithCulture(member.Value))

            Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        Next

        '' 
        If enumType.Members.Any() Then
            Me.GenerationEnvironment.Remove(
                Me.GenerationEnvironment.Length - (CurrentIndent.Length + 2), (CurrentIndent.Length + 2))
        Else

            Me.Write("    None"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        End If

            Me.Write("End Enum"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


        If Not code.VerifyCaseInsensitiveMemberUniqueness(code.GetAllDeclaredMembers(enumType), enumType.FullName, SourceCsdlPath)  Then
            Return String.Empty
        End If
    Next
    region.End()

    If (Not String.IsNullOrEmpty(namespaceName)) Then
    PopIndent()

            Me.Write("End Namespace"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


    End If

    If Not code.VerifyCaseInsensitiveTypeUniqueness(code.GetAllGlobalItems(ItemCollection), SourceCsdlPath) Then
        Return String.Empty
    End If

            Return Me.GenerationEnvironment.ToString
        End Function



    ''''''''
    '''''''' 
    ''''''''

    ''''''''
    '''''''' 
    ''''''''

    Private Sub WriteFactoryMethod(structuralType As StructuralType, code As CodeGenerationTools)
        Dim region As CodeRegion = new CodeRegion(Me, 1)

        Dim methodName As String = "Create" + structuralType.Name
        Dim uniqueIdentifier As UniqueIdentifierService = new UniqueIdentifierService()
        Dim instanceName As String = code.Escape(uniqueIdentifier.AdjustIdentifier((code.CamelCase(structuralType.Name))))
        Dim parameters As IEnumerable(Of FactoryMethodParameter) = FactoryMethodParameter.CreateParameters(structuralType.Members.OfType(Of EdmProperty)().Where(Function(p) IncludePropertyInFactoryMethod(structuralType, p)), uniqueIdentifier, Function(t, c) MultiSchemaEscape(t, c), code)

        If (parameters.Count() = 0) Then
            Return
        End If

        If(structuralType.Members.Any(Function(m) m.Name = methodName)) Then
            ' 
            Errors.Add(new System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6029",
                String.Format(CultureInfo.CurrentCulture, _
                   CodeGenerationTools.GetResourceString("Template_FactoryMethodNameConflict"), methodName, structuralType.FullName)))
        End If

        region.Begin(CodeGenerationTools.GetResourceString("Template_RegionFactoryMethod"))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_FactoryMethodComment"), structuralType.Name)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(Function(p) New Tuple(Of String, String)(p.RawParameterName, p.ParameterComment)), region.CurrentIndentLevel)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Public Shared Function ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(methodName))


Me.Write("(")


Me.Write(Me.ToStringHelper.ToStringWithCulture(String.Join(", ", parameters.Select(Function(p) p.ParameterName & " As " & p.ParameterType).ToArray())))


Me.Write(") As ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(structuralType)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        Dim ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(instanceName))


Me.Write(" as ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(structuralType)))


Me.Write(" = New ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(structuralType)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))




        For Each parameter As FactoryMethodParameter in parameters
            If(parameter.IsComplexType) Then
                ' 


Me.Write("        ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(instanceName))


Me.Write(".")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(parameter.Source)))


Me.Write(" = StructuralObject.VerifyComplexObjectIsNotNull(")


Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.ParameterName))


Me.Write(", """)


Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.Source.Name))


Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))




            Else
                ' 


Me.Write("        ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(instanceName))


Me.Write(".")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(parameter.Source)))


Me.Write(" = ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.ParameterName))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



            End If
        Next


Me.Write("        Return ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(instanceName))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Function"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



        region.End()
    End Sub


    ''''''''
    '''''''' 
    ''''''''
    Private Sub WriteSimpleTypeProperty(simpleProperty As EdmProperty, code As CodeGenerationTools)
        Dim ef As MetadataTools = New MetadataTools(Me)


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(simpleProperty)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")


Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(simpleProperty, 1)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <EdmScalarPropertyAttribute(EntityKeyProperty:=")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.CreateLiteral(ef.IsKey(simpleProperty))))


Me.Write(", IsNullable:=")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.CreateLiteral(ef.IsNullable(simpleProperty))))


Me.Write(")>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <DataMemberAttribute()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(simpleProperty))))


Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(simpleProperty)))


Me.Write(" Property ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(simpleProperty)))


Me.Write("() As ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(simpleProperty.TypeUsage, code)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(simpleProperty))))


Me.Write("Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


             If(ef.ClrType(simpleProperty.TypeUsage) = GetType(byte())) Then


Me.Write("                Return StructuralObject.GetValidValue(")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(simpleProperty)))


Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


             Else


Me.Write("            Return ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(simpleProperty)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



                End If


Me.Write("        End Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter((simpleProperty)))))


Me.Write("Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


         If(ef.IsKey(simpleProperty)) Then
                If(ef.ClrType(simpleProperty.TypeUsage) = GetType(byte())) Then


Me.Write("            If (Not StructuralObject.BinaryEquals(")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(simpleProperty)))


Me.Write(", Value)) Then"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



                Else


Me.Write("            If (")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(simpleProperty)))


Me.Write(" <> Value) Then"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



                End If
                PushIndent(CodeRegion.GetIndent(1))
            End If


Me.Write("            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ChangingMethodName(simpleProperty)))


Me.Write("(value)"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ReportPropertyChanging(""")


Me.Write(Me.ToStringHelper.ToStringWithCulture(simpleProperty.Name))


Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(simpleProperty)))


Me.Write(" = ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(BeginCastToEnumType(simpleProperty.TypeUsage, code)))


Me.Write("StructuralObject.SetValidValue(")


Me.Write(Me.ToStringHelper.ToStringWithCulture(BeginCastToUnderlyingType(simpleProperty.TypeUsage, code)))


Me.Write("value")


Me.Write(Me.ToStringHelper.ToStringWithCulture(EndCastToUnderlyingType(simpleProperty.TypeUsage, code)))


Me.Write(Me.ToStringHelper.ToStringWithCulture(OptionalNullableParameterForSetValidValue(simpleProperty, code)))


Me.Write(", """)


Me.Write(Me.ToStringHelper.ToStringWithCulture(simpleProperty.Name))


Me.Write(""")")


Me.Write(Me.ToStringHelper.ToStringWithCulture(EndCastToEnumType(simpleProperty.TypeUsage, code)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ReportPropertyChanged(""")


Me.Write(Me.ToStringHelper.ToStringWithCulture(simpleProperty.Name))


Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ChangedMethodName(simpleProperty)))


Me.Write("()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))


         If(ef.IsKey(simpleProperty)) Then
                PopIndent()


Me.Write("            End If"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



            End If


Me.Write("        End Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Property"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Private ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(simpleProperty)))


Me.Write(" As ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(simpleProperty.TypeUsage, code)))


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.StringBefore(" = ", code.CreateLiteral(simpleProperty.DefaultValue))))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Private Partial Sub ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ChangingMethodName(simpleProperty)))


Me.Write("(value As ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(simpleProperty.TypeUsage, code)))


Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Private Partial Sub ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ChangedMethodName(simpleProperty)))


Me.Write("()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



    End Sub


    ''''''''
    '''''''' 
    ''''''''
    Private Sub WriteComplexTypeProperty(complexProperty As EdmProperty, code As CodeGenerationTools)


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' <summary>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(SummaryComment(complexProperty)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ''' </summary>")


Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(complexProperty, 1)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <EdmComplexPropertyAttribute()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <DesignerSerializationVisibility(Desig"& _ 
        "nerSerializationVisibility.Content)>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <XmlElement(IsNullable:=True)>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <S"& _ 
        "oapElement(IsNullable:=True)>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    <DataMemberAttribute()>"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(NewModifier(complexProperty))))


Me.Write(Me.ToStringHelper.ToStringWithCulture(Accessibility.ForProperty(complexProperty)))


Me.Write(" Property ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.Escape(complexProperty)))


Me.Write("() As ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(complexProperty.TypeUsage, code)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForGetter(complexProperty))))


Me.Write("Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)))


Me.Write(" = GetValidValue(")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)))


Me.Write(", """)


Me.Write(Me.ToStringHelper.ToStringWithCulture(complexProperty.Name))


Me.Write(""", False, ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(InitializedTrackingField(complexProperty, code)))


Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(InitializedTrackingField(complexProperty, code)))


Me.Write(" = True"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            Return ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Get"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.SpaceAfter(Accessibility.ForSetter(complexProperty))))


Me.Write("Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ChangingMethodName(complexProperty)))


Me.Write("(value)"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ReportPropertyChanging(""")


Me.Write(Me.ToStringHelper.ToStringWithCulture(complexProperty.Name))


Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)))


Me.Write(" = SetValidValue(")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)))


Me.Write(", value, """)


Me.Write(Me.ToStringHelper.ToStringWithCulture(complexProperty.Name))


Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(InitializedTrackingField(complexProperty, code)))


Me.Write(" = True"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ReportPropertyChanged(""")


Me.Write(Me.ToStringHelper.ToStringWithCulture(complexProperty.Name))


Me.Write(""")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ChangedMethodName(complexProperty)))


Me.Write("()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End Set"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Property"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Private ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(code.FieldName(complexProperty)))


Me.Write(" As ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(complexProperty.TypeUsage, code)))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Private ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(InitializedTrackingField(complexProperty, code)))


Me.Write(" As Boolean"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Private Partial Sub ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ChangingMethodName(complexProperty)))


Me.Write("(value As ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(MultiSchemaEscape(complexProperty.TypeUsage, code)))


Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    Private Partial Sub ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(ChangedMethodName(complexProperty)))


Me.Write("()"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"    End Sub"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



    End Sub

    Private Sub WriteFunctionParameters(ByVal parameters As IEnumerable(Of FunctionImportParameter))
        For Each parameter As FunctionImportParameter In parameters
                If (Not parameter.NeedsLocalVariable) Then
                    Continue For
                End If


Me.Write("        Dim ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName))


Me.Write(" As ObjectParameter"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        If (")


Me.Write(Me.ToStringHelper.ToStringWithCulture(If(parameter.IsNullableOfT, parameter.FunctionParameterName + ".HasValue", parameter.FunctionParameterName & " IsNot Nothing")))


Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName))


Me.Write(" = New ObjectParameter(""")


Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.EsqlParameterName))


Me.Write(""", ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.FunctionParameterName))


Me.Write(")"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        Else"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"            ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.LocalVariableName))


Me.Write(" = New ObjectParameter(""")


Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.EsqlParameterName))


Me.Write(""", GetType(")


Me.Write(Me.ToStringHelper.ToStringWithCulture(parameter.RawClrTypeName))


Me.Write("))"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"        End If"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



            Next
    End Sub

    Private Sub WriteLazyLoadingEnabled(ByVal container As EntityContainer)
        Dim lazyLoadingAttributeValue As String = Nothing
        Dim lazyLoadingAttributeName As String = MetadataConstants.EDM_ANNOTATION_09_02 & ":LazyLoadingEnabled"
        If MetadataTools.TryGetStringMetadataPropertySetting(container, lazyLoadingAttributeName, lazyLoadingAttributeValue) Then
            Dim isLazyLoading As Boolean = False
            If Boolean.TryParse(lazyLoadingAttributeValue, isLazyLoading) Then


Me.Write("        MyBase.ContextOptions.LazyLoadingEnabled = ")


Me.Write(Me.ToStringHelper.ToStringWithCulture(isLazyLoading.ToString().ToLowerInvariant()))


Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))



            End If
        End If
    End Sub

    ''''''''
    '''''''' 
    ''''''''
    Public Property SourceCsdlPath() As String
    Public Property ModelNamespace() As String
    Public Property ItemCollection() As EdmItemCollection
    Public Property ReferenceCsdlPaths() As IEnumerable(Of String)
    Public Property FullyQualifySystemTypes() As Nullable(Of Boolean)
    Public Property CreateContextAddToMethods As Nullable(Of Boolean)
    Public Property EdmToObjectNamespaceMap() As Dictionary(Of string, string)
        Get
            Return _edmToObjectNamespaceMap
        End Get
        Set
            _edmToObjectNamespaceMap = Value
        End Set

    End Property
    Dim _edmToObjectNamespaceMap As Dictionary(Of string, string) = new Dictionary(Of string, string)

    Public ReadOnly Property SourceEdmVersion As Double
        Get
            If (Not ItemCollection Is Nothing) Then
                Return ItemCollection.EdmVersion
            End If
            Return 0.0
        End Get
    End Property

    Private Sub ApplyUserSettings(userSettings as UserSettings)
        If(SourceCsdlPath Is Nothing) Then
#If NOT PREPROCESSED_TEMPLATE
            If userSettings.SourceCsdlPath = ("$" & "edmxInputFile" & "$")
                Errors.Add(New System.CodeDom.Compiler.CompilerError(Host.TemplateFile, -1, -1, String.Empty,
                    CodeGenerationTools.GetResourceString("Template_ReplaceVsItemTemplateToken")))
                Return
            End If

            SourceCsdlPath = Host.ResolvePath(userSettings.SourceCsdlPath)
#Else
            SourceCsdlPath = userSettings.SourceCsdlPath
#End If
        End If

        ' normalize the path, remove ..\ from it
        SourceCsdlPath = Path.GetFullPath(SourceCsdlPath)

        If(ReferenceCsdlPaths Is Nothing) Then
            ReferenceCsdlPaths = userSettings.ReferenceCsdlPaths
        End If

        If(Not FullyQualifySystemTypes.HasValue) Then
            FullyQualifySystemTypes = userSettings.FullyQualifySystemTypes
        End If

        If(Not CreateContextAddToMethods.HasValue) Then
            CreateContextAddToMethods = userSettings.CreateContextAddToMethods
        End If

        DefaultSummaryComment = CodeGenerationTools.GetResourceString("Template_CommentNoDocumentation")
    End Sub


    ''''''''
    '''''''' 
    ''''''''
    Private Class UserSettings
        Public Property SourceCsdlPath() As String
        Public Property ReferenceCsdlPaths() As String ()
        Public Property FullyQualifySystemTypes() As Boolean
        Public Property CreateContextAddToMethods() As Boolean
        Public Property CamelCaseFields() As Boolean
    End Class

    Private Function GetNamespaceName(code As CodeGenerationTools) As String
        Dim namespaceName As String = code.VsNamespaceSuggestion()

#If PREPROCESSED_TEMPLATE Then
        If String.IsNullOrEmpty(namespaceName) Then
            namespaceName = GetObjectNamespace(ModelNamespace)
        End If
#End If
        Return namespaceName
    End Function

Private Function MultiSchemaEscape(ByVal usage As TypeUsage, ByVal code As CodeGenerationTools) As String
    Dim ef As MetadataTools = New MetadataTools(Me)
    If usage.EdmType IsNot Nothing Then
        If TypeOf usage.EdmType Is StructuralType Then
            Return MultiSchemaEscape(usage.EdmType, code)
        ElseIf TypeOf usage.EdmType Is EnumType Then
            Dim typeName As String = MultiSchemaEscape(usage.EdmType, code)
            If ef.IsNullable(usage) Then
                Return String.Format(CultureInfo.InvariantCulture, "Nullable(Of {0})", typeName)
            End If

            Return typeName
        End If
    End If

    Return code.Escape(usage)
End Function

Private Function MultiSchemaEscape(ByVal type As EdmType, ByVal code As CodeGenerationTools) As String
    If type.NamespaceName <> ModelNamespace Then
        Return code.CreateFullName(code.EscapeNamespace(GetObjectNamespace(type.NamespaceName)), code.Escape(type))
    End If

    Return code.Escape(type)
End Function

Private Function NewModifier(ByVal navigationProperty As NavigationProperty) As String
    Dim baseType As Type = GetType(EntityObject)
    Return NewModifier(baseType, navigationProperty.Name)
End Function

Private Function NewModifier(ByVal edmFunction As EdmFunction) As String
    Dim baseType As Type = GetType(ObjectContext)
    Return NewModifier(baseType, edmFunction.Name)
End Function

Private Function NewModifier(ByVal entitySet As EntitySet) As String
    Dim baseType As Type = GetType(ObjectContext)
    Return NewModifier(baseType, entitySet.Name)
End Function

Private Function NewModifier(ByVal edmProperty As EdmProperty) As String
    Dim baseType As Type
    If edmProperty.DeclaringType.BuiltInTypeKind = BuiltInTypeKind.EntityType Then
        baseType = GetType(EntityObject)
    Else
        baseType = GetType(ComplexObject)
    End If
    Return NewModifier(baseType, edmProperty.Name)
End Function

Private Function NewModifier(ByVal type As Type, ByVal memberName As String) As String
    If HasBaseMemberWithMatchingName(type, memberName) Then
        Return "Shadows"
    End If
    Return String.Empty
End Function

Private Function ChangingMethodName(ByVal member As EdmMember) As String
    Return String.Format(CultureInfo.InvariantCulture, "On{0}Changing", member.Name)
End Function

Private Function ChangedMethodName(ByVal member As EdmMember) As String
    Return String.Format(CultureInfo.InvariantCulture, "On{0}Changed", member.Name)
End Function

Private Function InitializedTrackingField(ByVal edmProperty As EdmProperty, ByVal code As CodeGenerationTools) As String
    Dim namePart As String = edmProperty.Name & "Initialized"
    If code.CamelCaseFields Then
        namePart = code.CamelCase(namePart)
    End If
    Return "_" & namePart
End Function

Private Function OptionalNullableParameterForSetValidValue(ByVal member As EdmMember, ByVal code As CodeGenerationTools) As String
    Dim ef As New MetadataTools(Me)
    Dim list As String = String.Empty
    Dim type As PrimitiveType = TryCast(member.TypeUsage.EdmType, PrimitiveType)
    If type IsNot Nothing AndAlso type.ClrEquivalentType.IsClass Then
        Dim storeGeneratedPatternProperty As MetadataProperty = Nothing
        Dim isNullable As Boolean = ef.IsNullable(member.TypeUsage) OrElse
            (member.MetadataProperties.TryGetValue(MetadataConstants.EDM_ANNOTATION_09_02 & ":StoreGeneratedPattern", False, storeGeneratedPatternProperty) AndAlso
             Object.Equals(storeGeneratedPatternProperty.Value, "Computed"))
        list += ", " & code.CreateLiteral(isNullable)
    End If
    Return list
End Function

Private Shared Function IsVisibleMember(ByVal memberInfo As MemberInfo) As Boolean
    If TypeOf memberInfo Is EventInfo Then
        Dim ei As EventInfo = DirectCast(memberInfo, EventInfo)
        Dim add As MethodInfo = ei.GetAddMethod()
        Dim remove As MethodInfo = ei.GetRemoveMethod()
        Return IsVisibleMethod(add) OrElse IsVisibleMethod(remove)
    ElseIf TypeOf memberInfo Is FieldInfo Then
        Dim fi As FieldInfo = DirectCast(memberInfo, FieldInfo)
        Return Not fi.IsPrivate AndAlso Not fi.IsAssembly
    ElseIf TypeOf memberInfo Is MethodBase Then
        Dim mb As MethodBase = DirectCast(memberInfo, MethodBase)
        If mb.IsSpecialName Then
            Return False
        End If
        Return IsVisibleMethod(mb)
    ElseIf TypeOf memberInfo Is PropertyInfo Then
        Dim pi As PropertyInfo = DirectCast(memberInfo, PropertyInfo)
        Dim getMethod As MethodInfo = pi.GetGetMethod()
        Dim entitySet As MethodInfo = pi.GetSetMethod()
        Return IsVisibleMethod(getMethod) OrElse IsVisibleMethod(entitySet)
    End If

    Return False
End Function

Private Shared Function IsVisibleMethod(ByVal methodBase As MethodBase) As Boolean
    If methodBase Is Nothing Then
        Return False
    End If

    Return Not methodBase.IsPrivate AndAlso Not methodBase.IsAssembly
End Function

Private Shared Function HasBaseMemberWithMatchingName(ByVal type As Type, ByVal memberName As String) As Boolean
    Dim bindings As BindingFlags = BindingFlags.FlattenHierarchy Or BindingFlags.NonPublic Or BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.Static
    Return type.GetMembers(bindings).Where(Function(m) IsVisibleMember(m)).Any(Function(m) m.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase))
End Function

Private Function BeginCastToEnumType(ByVal typeUsage As TypeUsage, ByVal code As CodeGenerationTools) As String
    Dim type As EnumType = TryCast(typeUsage.EdmType, EnumType)
    If type Is Nothing Then
        Return String.Empty
    End If

    Return "CType("
End Function

Private Function EndCastToEnumType(ByVal typeUsage As TypeUsage, ByVal code As CodeGenerationTools) As String
    Dim type As EnumType = TryCast(typeUsage.EdmType, EnumType)
    If type Is Nothing Then
        Return String.Empty
    End If

    Return ", " & MultiSchemaEscape(typeUsage, code) & ")"
End Function

Private Function BeginCastToUnderlyingType(ByVal typeUsage As TypeUsage, ByVal code As CodeGenerationTools) As String
    Dim type As EnumType = TryCast(typeUsage.EdmType, EnumType)
    If type Is Nothing Then
        Return String.Empty
    End If

    Return "CType("
End Function

Private Function EndCastToUnderlyingType(ByVal typeUsage As TypeUsage, ByVal code As CodeGenerationTools) As String
    Dim ef As MetadataTools = New MetadataTools(Me)
    Dim type As EnumType = TryCast(typeUsage.EdmType, EnumType)
    If type Is Nothing Then
        Return String.Empty
    End If

    Dim clrType As String = code.Escape(type.UnderlyingType.ClrEquivalentType, fullyQualifySystemTypes := False)

    If ef.IsNullable(typeUsage) Then
        clrType = String.Format(CultureInfo.InvariantCulture, "Nullable(Of {0})", clrType)
    End If

    Return ", " & clrType & ")"
End Function

Private Function GetSourceSchemaTypes(Of T As GlobalItem)() As IEnumerable(Of T)
    If Path.GetExtension(SourceCsdlPath) <> ".edmx" Then
        Return ItemCollection.GetItems(Of T)().Where(Function(e) e.MetadataProperties.Any(Function(mp) mp.Name = "SchemaSource" AndAlso DirectCast(mp.Value, String) = SourceCsdlPath))
    Else
        Return ItemCollection.GetItems(Of T)()
    End If
End Function

Private Function EndName(ByVal association As AssociationType, ByVal index As Integer) As String
    Return association.AssociationEndMembers(index).Name
End Function

Private Function EndMultiplicity(ByVal association As AssociationType, ByVal index As Integer, ByVal code As CodeGenerationTools) As String
    Return code.CreateLiteral(association.AssociationEndMembers(index).RelationshipMultiplicity)
End Function

Private Function EscapeEndTypeName(ByVal association As AssociationType, ByVal index As Integer, ByVal code As CodeGenerationTools) As String
    Dim entity As EntityType = association.AssociationEndMembers(index).GetEntityType()
    Return code.CreateFullName(code.EscapeNamespace(GetObjectNamespace(entity.NamespaceName)), code.Escape(entity))
End Function

Private Function GetObjectNamespace(ByVal csdlNamespaceName As String) As String
    Dim objectNamespace As String = Nothing
    If EdmToObjectNamespaceMap.TryGetValue(csdlNamespaceName, objectNamespace) Then
        Return objectNamespace
    End If

    Return csdlNamespaceName
End Function

Private Sub UpdateObjectNamespaceMap(objectNamespace As String)
    If Not objectNamespace = ModelNamespace AndAlso Not EdmToObjectNamespaceMap.ContainsKey(ModelNamespace)
        EdmToObjectNamespaceMap.Add(ModelNamespace, objectNamespace)
    End If
End Sub


Private Shared Function FixParameterName(ByVal name As String, ByVal code As CodeGenerationTools) As String
    ' 
    ' 
    If StringComparer.OrdinalIgnoreCase.Equals(name, "id") Then
        ' 
        Return "id"
    End If
    Return code.CamelCase(name)
End Function

Private Function BaseTypeName(ByVal entity As EntityType, ByVal code As CodeGenerationTools) As String
    Return If(entity.BaseType Is Nothing, "EntityObject", MultiSchemaEscape(entity.BaseType, code))
End Function

Private Function IncludePropertyInFactoryMethod(ByVal factoryType As StructuralType, ByVal edmProperty As EdmProperty) As Boolean
    If edmProperty.Nullable Then
        Return False
    End If

    If edmProperty.DefaultValue IsNot Nothing Then
        Return False
    End If

    If (Accessibility.ForReadOnlyProperty(edmProperty) <> "Public" AndAlso Accessibility.ForWriteOnlyProperty(edmProperty) <> "Public") OrElse (factoryType IsNot edmProperty.DeclaringType AndAlso Accessibility.ForWriteOnlyProperty(edmProperty) = "Private") Then
        ' 
        Return False
    End If

    Return True
End Function

Private Class FactoryMethodParameter
    Public Source As EdmProperty
    Public RawParameterName As String
    Public ParameterName As String
    Public ParameterType As String
    Public ParameterComment As String
    Public IsComplexType As Boolean

    Public Shared Function CreateParameters(ByVal properties As IEnumerable(Of EdmProperty), ByVal unique As UniqueIdentifierService, ByVal multiSchemaEscape As Func(Of TypeUsage, CodeGenerationTools, String), ByVal code As CodeGenerationTools) As IEnumerable(Of FactoryMethodParameter)
        Dim parameters As New List(Of FactoryMethodParameter)()
        For Each edmProperty As EdmProperty In properties
            Dim parameter As New FactoryMethodParameter()
            parameter.Source = edmProperty
            parameter.IsComplexType = TypeOf edmProperty.TypeUsage.EdmType Is ComplexType
            parameter.RawParameterName = unique.AdjustIdentifier(FixParameterName(edmProperty.Name, code))
            parameter.ParameterName = code.Escape(parameter.RawParameterName)
            parameter.ParameterType = multiSchemaEscape(edmProperty.TypeUsage, code)
            parameter.ParameterComment = String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_CommentFactoryMethodParam"), edmProperty.Name)
            parameters.Add(parameter)
        Next

        Return parameters
    End Function
End Class

Private Property DefaultSummaryComment() As String

Private Function SummaryComment(ByVal item As MetadataItem) As String
    If item.Documentation IsNot Nothing AndAlso item.Documentation.Summary IsNot Nothing Then
        Return PrefixLinesOfMultilineComment(XMLCOMMENT_START & " ", XmlEntityize(item.Documentation.Summary))
    End If

    If DefaultSummaryComment IsNot Nothing Then
        Return DefaultSummaryComment
    End If

    Return String.Empty
End Function

Private Function LongDescriptionCommentElement(ByVal item As MetadataItem, ByVal indentLevel As Integer) As String
    If item.Documentation IsNot Nothing AndAlso Not String.IsNullOrEmpty(item.Documentation.LongDescription) Then
        Dim comment As String = Environment.NewLine
        Dim lineStart As String = CodeRegion.GetIndent(indentLevel) + XMLCOMMENT_START & " "
        comment += (lineStart & "<LongDescription>") + Environment.NewLine
        comment += lineStart + PrefixLinesOfMultilineComment(lineStart, XmlEntityize(item.Documentation.LongDescription)) + Environment.NewLine
        comment += lineStart & "</LongDescription>"
        Return comment
    End If
    Return String.Empty
End Function

Private Function PrefixLinesOfMultilineComment(ByVal prefix As String, ByVal comment As String) As String
    Return comment.Replace(Environment.NewLine, Environment.NewLine + prefix)
End Function

Private Function ParameterComments(ByVal parameters As IEnumerable(Of Tuple(Of String, String)), ByVal indentLevel As Integer) As String
    Dim builder As New System.Text.StringBuilder()
    For Each parameter As Tuple(Of String, String) In parameters
        builder.AppendLine()
        builder.Append(CodeRegion.GetIndent(indentLevel))
        builder.Append(XMLCOMMENT_START)
        builder.Append(String.Format(CultureInfo.InvariantCulture, " <param name=""{0}"">{1}</param>", parameter.Item1, parameter.Item2))
    Next
    Return builder.ToString()
End Function

Private Function XmlEntityize(ByVal text As String) As String
    If String.IsNullOrEmpty(text) Then
        Return String.Empty
    End If

    text = text.Replace("&", "&amp;")
    text = text.Replace("<", "&lt;").Replace(">", "&gt;")
    Dim id As String = Guid.NewGuid().ToString()
    text = text.Replace(Environment.NewLine, id)
    text = text.Replace(vbCr, "&#xD;").Replace(vbLf, "&#xA;")
    text = text.Replace(id, Environment.NewLine)
    Return text.Replace("'", "&apos;").Replace("""", "&quot;")
End Function

Const XMLCOMMENT_START As String = "'''"

Private Function GetProperties(ByVal type As StructuralType) As IEnumerable(Of EdmProperty)
    If type.BuiltInTypeKind = BuiltInTypeKind.EntityType Then
        Return DirectCast(type, EntityType).Properties
    Else
        Return DirectCast(type, ComplexType).Properties
    End If
End Function

Protected Sub VerifyGetterAndSetterAccessibilityCompatability(ByVal member As EdmMember)
    Dim rawGetterAccessibility As String = Accessibility.ForReadOnlyProperty(member)
    Dim rawSetterAccessibility As String = Accessibility.ForWriteOnlyProperty(member)

    If (rawGetterAccessibility = "Friend" AndAlso rawSetterAccessibility = "Protected") OrElse (rawGetterAccessibility = "Protected" AndAlso rawSetterAccessibility = "Friend") Then

        Errors.Add(New System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6033", String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("GeneratedPropertyAccessibilityConflict"), member.Name, rawGetterAccessibility, rawSetterAccessibility)))
    End If
End Sub

Private Sub VerifyEntityTypeAndSetAccessibilityCompatability(ByVal entitySet As EntitySet)
    Dim typeAccess As String = Accessibility.ForType(entitySet.ElementType)
    Dim setAccess As String = Accessibility.ForReadOnlyProperty(entitySet)

    If typeAccess = "Friend" AndAlso (setAccess = "Public" OrElse setAccess = "Protected") Then
        Errors.Add(New System.CodeDom.Compiler.CompilerError(SourceCsdlPath, -1, -1, "6036", String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("EntityTypeAndSetAccessibilityConflict"), entitySet.ElementType.Name, typeAccess, entitySet.Name, setAccess)))
    End If
End Sub

Private Sub DefineMetadata()
    TemplateMetadata(MetadataConstants.TT_TEMPLATE_NAME) = "VBCodeGen"
    TemplateMetadata(MetadataConstants.TT_TEMPLATE_VERSION) = "5.0"
    TemplateMetadata(MetadataConstants.TT_MINIMUM_ENTITY_FRAMEWORK_VERSION) = "5.0"
End Sub

Private NotInheritable Class UniqueIdentifierService
    Private ReadOnly _knownIdentifiers As HashSet(Of String) = New HashSet(Of string)(StringComparer.OrdinalIgnoreCase)

    ''' <summary>
    ''' 
    ''' 
    ''' </summary>
    Public Function AdjustIdentifier(identifier As String) As String
        ' 
        Dim numberOfConflicts As Int32 = 0
        Dim adjustedIdentifier As String = identifier
        While Not _knownIdentifiers.Add(adjustedIdentifier)
            numberOfConflicts += 1
            adjustedIdentifier = identifier + numberOfConflicts.ToString(CultureInfo.InvariantCulture)
        End While

        Return adjustedIdentifier
    End Function
End Class



' Copyright (c) Microsoft Corporation.  All rights reserved.

Public Shared TemplateMetadata As New Dictionary(Of String, String)()

''' <summary>
''' Responsible for helping to create source code that is
''' correctly formated and functional
''' </summary>
Public Class CodeGenerationTools
    Private ReadOnly _textTransformation As DynamicTextTransformation
    Private ReadOnly _code As VBCodeProvider
    Private ReadOnly _ef As MetadataTools

    ''' <summary>
    ''' Initializes a new CodeGenerationTools object with the TextTransformation (T4 generated class)
    ''' that is currently running.
    ''' </summary>
    Public Sub New(ByVal textTransformation As Object)
        If textTransformation Is Nothing Then
            Throw New ArgumentNullException("textTransformation")
        End If

        _textTransformation = DynamicTextTransformation.Create(textTransformation)
        _code = New VBCodeProvider()
        _ef = New MetadataTools(_textTransformation)
        FullyQualifySystemTypes = False
        CamelCaseFields = True
    End Sub

    ''' <summary>
    ''' When true, all types that are not being generated
    ''' are fully qualified to keep them from conflicting with
    ''' types that are being generated. Useful when you have
    ''' something like a type being generated named System.
    '''
    ''' Default is false.
    ''' </summary>
    Private _FullyQualifySystemTypes As Boolean
    Public Property FullyQualifySystemTypes() As Boolean
        Get
            Return _FullyQualifySystemTypes
        End Get
        Set(ByVal value As Boolean)
            _FullyQualifySystemTypes = value
        End Set
    End Property

    ''' <summary>
    ''' When true, the field names are Camel Cased,
    ''' otherwise they will preserve the case they
    ''' start with.
    '''
    ''' Default is true.
    ''' </summary>
    Private _CamelCaseFields As Boolean
    Public Property CamelCaseFields() As Boolean
        Get
            Return _CamelCaseFields
        End Get
        Set(ByVal value As Boolean)
            _CamelCaseFields = value
        End Set
    End Property

    ''' <summary>
    ''' Returns the NamespaceName suggested by VS if running inside VS. Otherwise, returns
    ''' null.
    ''' </summary>
    Public Function VsNamespaceSuggestion() As String
        Dim suggestion As String = _textTransformation.Host.ResolveParameterValue("directiveId", "namespaceDirectiveProcessor", "namespaceHint")
        If String.IsNullOrEmpty(suggestion) Then
            Return Nothing
        End If

        Return suggestion
    End Function

    ''' <summary>
    ''' Returns a string that is safe for use as an identifier in C#.
    ''' Keywords are escaped.
    ''' </summary>
    Public Function Escape(ByVal name As String) As String
        If name Is Nothing Then
            Return Nothing
        End If

        Return _code.CreateEscapedIdentifier(name)
    End Function

    ''' <summary>
    ''' Returns the name of the TypeUsage's EdmType that is safe for
    ''' use as an identifier.
    ''' </summary>
    Public Function Escape(ByVal typeUsage As TypeUsage) As String
        If typeUsage Is Nothing Then
            Return Nothing
        End If

        If TypeOf typeUsage.EdmType Is ComplexType OrElse TypeOf typeUsage.EdmType Is EntityType Then
            Return Escape(typeUsage.EdmType.Name)
        ElseIf TypeOf typeUsage.EdmType Is SimpleType Then
            Dim clrType As Type = _ef.UnderlyingClrType(typeUsage.EdmType)
            Dim typeName As String = If(TypeOf typeUsage.EdmType Is EnumType, Escape(typeUsage.EdmType.Name), Escape(clrType))
            If clrType.IsValueType AndAlso _ef.IsNullable(typeUsage) Then
                Return String.Format(CultureInfo.InvariantCulture, "Nullable(Of {0})", typeName)
            End If

            Return typeName
        ElseIf TypeOf typeUsage.EdmType Is CollectionType Then
            Return String.Format(CultureInfo.InvariantCulture, "ICollection(Of {0})", Escape(DirectCast(typeUsage.EdmType, CollectionType).TypeUsage))
        End If

        Throw New ArgumentException("typeUsage")
    End Function

    ''' <summary>
    ''' Returns the name of the EdmMember that is safe for
    ''' use as an identifier.
    ''' </summary>
    Public Function Escape(ByVal member As EdmMember) As String
        If member Is Nothing Then
            Return Nothing
        End If

        Return Escape(member.Name)
    End Function

    ''' <summary>
    ''' Returns the name of the EdmType that is safe for
    ''' use as an identifier.
    ''' </summary>
    Public Function Escape(ByVal type As EdmType) As String
        If type Is Nothing Then
            Return Nothing
        End If

        Return Escape(type.Name)
    End Function

    ''' <summary>
    ''' Returns the name of the EdmFunction that is safe for
    ''' use as an identifier.
    ''' </summary>
    Public Function Escape(ByVal edmFunction As EdmFunction) As String
        If edmFunction Is Nothing Then
            Return Nothing
        End If

        Return Escape(edmFunction.Name)
    End Function

    ''' <summary>
    ''' Returns the name of the EnumMember that is safe for
    ''' use as an identifier.
    ''' </summary>
    Public Function Escape(ByVal member As EnumMember) As String
        If member Is Nothing Then
            Return Nothing
        End If

        Return Escape(member.Name)
    End Function


    ''' <summary>
    ''' Returns the name of the EntityContainer that is safe for
    ''' use as an identifier.
    ''' </summary>
    Public Function Escape(ByVal container As EntityContainer) As String
        If container Is Nothing Then
            Return Nothing
        End If

        Return Escape(container.Name)
    End Function

    ''' <summary>
    ''' Returns the name of the EntitySet that is safe for
    ''' use as an identifier.
    ''' </summary>
    Public Function Escape(ByVal edmSet As EntitySet) As String
        If edmSet Is Nothing Then
            Return Nothing
        End If

        Return Escape(edmSet.Name)
    End Function

    ''' <summary>
    ''' Returns the name of the StructuralType that is safe for
    ''' use as an identifier.
    ''' </summary>
    Public Function Escape(ByVal type As StructuralType) As String
        If type Is Nothing Then
            Return Nothing
        End If

        Return Escape(type.Name)
    End Function

    ''' <summary>
    ''' Returns the NamespaceName with each segment safe to
    ''' use as an identifier.
    ''' </summary>
    Public Function EscapeNamespace(ByVal namespaceName As String) As String
        If String.IsNullOrEmpty(namespaceName) Then
            Return namespaceName
        End If

        Dim parts As String() = namespaceName.Split("."c)
        namespaceName = String.Empty
        For Each part As String In parts
            If namespaceName <> String.Empty Then
                namespaceName += "."
            End If

            namespaceName += Escape(part)
        Next

        Return namespaceName
    End Function

    ''' <summary>
    ''' Returns the name of the EdmMember formatted for
    ''' use as a field identifier.
    '''
    ''' This method changes behavior based on the CamelCaseFields
    ''' setting.
    ''' </summary>
    Public Function FieldName(ByVal member As EdmMember) As String
        If member Is Nothing Then
            Return Nothing
        End If

        Return FieldName(member.Name)
    End Function

    ''' <summary>
    ''' Returns the name of the EntitySet formatted for
    ''' use as a field identifier.
    '''
    ''' This method changes behavior based on the CamelCaseFields
    ''' setting.
    ''' </summary>
    Public Function FieldName(ByVal edmSet As EntitySet) As String
        If edmSet Is Nothing Then
            Return Nothing
        End If


        Return FieldName(edmSet.Name)
    End Function

    Private Function FieldName(ByVal name As String) As String
        If CamelCaseFields Then
            Return "_" & CamelCase(name)
        Else
            Return "_" & name
        End If
    End Function

    ''' <summary>
    ''' Returns the name of the Type object formatted for
    ''' use in source code.
    '''
    ''' This method changes behavior based on the FullyQualifySystemTypes
    ''' setting.
    ''' </summary>
    Public Function Escape(ByVal clrType As Type) As String
        Return Escape(clrType, FullyQualifySystemTypes)
    End Function

    ''' <summary>
    ''' Returns the name of the Type object formatted for
    ''' use in source code.
    ''' </summary>
    Public Function Escape(ByVal clrType As Type, ByVal fullyQualifySystemTypes As Boolean) As String
        If clrType Is Nothing Then
            Return Nothing
        End If

        Dim typeName As String
        If fullyQualifySystemTypes Then
            If(Not clrType.IsArray) Then
                typeName = clrType.FullName
            Else
                typeName = clrType.GetElementType().FullName & "()"
            End If

            typeName = "Global." & typeName
        Else
            typeName = _code.GetTypeOutput(New CodeTypeReference(clrType))
        End If
        Return typeName
    End Function

    ''' <summary>
    ''' Returns the abstract option if the entity is Abstract, otherwise returns String.Empty
    ''' </summary>
    Public Function MustInheritOption(entity As EntityType) As String
        If entity.Abstract Then
            Return "MustInherit"
        End If

        Return String.Empty
    End Function

    ''' <summary>
    ''' Returns the passed in identifier with the first letter changed to lowercase
    ''' </summary>
    Public Function CamelCase(ByVal identifier As String) As String
        If String.IsNullOrEmpty(identifier) Then
            Return identifier
        End If

        If identifier.Length = 1 Then
            Return identifier(0).ToString(CultureInfo.InvariantCulture).ToLowerInvariant()
        End If

        Return identifier(0).ToString(CultureInfo.InvariantCulture).ToLowerInvariant() + identifier.Substring(1)
    End Function

    ''' <summary>
    ''' If the value parameter is null or empty an empty string is returned,
    ''' otherwise it retuns value with a single space concatenated on the end.
    ''' </summary>
    Public Function SpaceAfter(ByVal value As String) As String
        Return StringAfter(value, " ")
    End Function

    ''' <summary>
    ''' If the value parameter is null or empty an empty string is returned,
    ''' otherwise it retuns value with a single space concatenated on the end.
    ''' </summary>
    Public Function SpaceBefore(ByVal value As String) As String
        Return StringBefore(" ", value)
    End Function

    ''' <summary>
    ''' If the value parameter is null or empty an empty string is returned,
    ''' otherwise it retuns value with append concatenated on the end.
    ''' </summary>
    Public Function StringAfter(ByVal value As String, ByVal append As String) As String
        If String.IsNullOrEmpty(value) Then
            Return String.Empty
        End If

        Return value + append
    End Function

    ''' <summary>
    ''' If the value parameter is null or empty an empty string is returned,
    ''' otherwise it retuns value with prepend concatenated on the front.
    ''' </summary>
    Public Function StringBefore(ByVal prepend As String, ByVal value As String) As String
        If String.IsNullOrEmpty(value) Then
            Return String.Empty
        End If

        Return prepend + value
    End Function

    ''' <summary>
    ''' Returns false and shows an error if the supplied type names aren't case-insensitively unique,
    ''' otherwise returns true.
    ''' </summary>
    Public Function VerifyCaseInsensitiveTypeUniqueness(types As IEnumerable(Of String), ByVal sourceFile As String) As Boolean
        Return VerifyCaseInsensitiveUniqueness(types, _
            Function(t) String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_CaseInsensitiveTypeConflict"), t), sourceFile)
    End Function

    ''' <summary>
    ''' Returns false and shows an error if the supplied entity set names aren't case-insensitively unique,
    ''' otherwise returns true.
    ''' </summary>
    Public Function VerifyCaseInsensitiveEntitySetUniqueness(entitySets As IEnumerable(Of String), ByVal entityContainerName As String, ByVal sourceFile As String) As Boolean
        Return VerifyCaseInsensitiveUniqueness(entitySets, Function(e) String.Format(CultureInfo.CurrentCulture, _
                GetResourceString("Template_CaseInsensitiveEntitySetConflict"), entityContainerName, e), sourceFile)
    End Function

    ''' <summary>
    ''' Returns false and shows an error if the supplied type members names aren't case-insensitively unique,
    ''' otherwise returns true.
    ''' </summary>
    Public Function VerifyCaseInsensitiveMemberUniqueness(members As IEnumerable(Of String), ByVal declaringType As String, ByVal sourceFile As String) As Boolean
        Return VerifyCaseInsensitiveUniqueness(members, _
            Function(m) String.Format(CultureInfo.CurrentCulture, _
                GetResourceString("Template_CaseInsensitiveMemberConflict"), declaringType, m), sourceFile)
    End Function

    ''' <summary>
    ''' Returns false and shows an error if the supplied strings aren't case-insensitively unique,
    ''' otherwise returns true.
    ''' </summary>
    Private Function VerifyCaseInsensitiveUniqueness(items As IEnumerable(Of String), formatMessage As Func(Of String, String), ByVal sourceFile As String) As Boolean
        Dim hash As HashSet(Of String) = New HashSet(Of String)(StringComparer.InvariantCultureIgnoreCase)
        For Each item As String in items
            If Not hash.Add(item) Then
                _textTransformation.Errors.Add(New System.CodeDom.Compiler.CompilerError(sourceFile, -1, -1, 6023, formatMessage(item)))
                Return False
            End If
        Next
        Return True
    End Function

    ''' <summary>
    ''' Returns the names of the items in the supplied collection that correspond to O-Space types.
    ''' </summary>
    Public Function GetAllGlobalItems(ByVal itemCollection As EdmItemCollection) As IEnumerable(Of String)
        Return itemCollection.GetItems(Of GlobalItem)() _
                .Where(Function(i) TypeOf i Is EntityType OrElse TypeOf i Is ComplexType OrElse TypeOf i Is EnumType OrElse TypeOf i is EntityContainer) _
                .Select(Function(g) GetGlobalItemName(g))
    End Function

    ''' <summary>
    ''' Returns the name of the supplied GlobalItem.
    ''' </summary>
    Private Function GetGlobalItemName(item As GlobalItem) As String
        If TypeOf item Is EdmType Then
            Return CType(item, EdmType).Name
        Else
            Return CType(item, EntityContainer).Name
        End If
    End Function

    ''' <summary>
    ''' Returns the names of the members of the supplied EdmType.
    ''' </summary>
    Public Function GetAllDeclaredMembers(edmType As EdmType) As IEnumerable(Of String)
        Dim entity As EntityType = TryCast(edmType, EntityType)
        If Not entity Is Nothing Then
            Dim declaredMembers As IEnumerable(Of EdmMember) = entity.Members.Where(Function(m) m.DeclaringType Is entity)
            Dim decalredNavigationProperties As IEnumerable(Of NavigationProperty) = entity.NavigationProperties.Where(Function(n) n.DeclaringType Is entity)

            Return declaredMembers.Union(decalredNavigationProperties.Cast(Of EdmMember)()).Select(Function(m) m.Name)
        End If

        Dim structural As StructuralType = TryCast(edmType, StructuralType)
        If Not structural Is Nothing Then
            Return structural.Members.Where(Function(m) m.DeclaringType Is structural).Select(Function(m) m.Name)
        End If

        Dim enumType As EnumType = TryCast(edmType, EnumType)
        If Not enumType Is Nothing Then
            Return enumType.Members.Select(Function(m) m.Name)
        End If

        Return Enumerable.Empty(Of String)()
    End Function

    ''' <summary>
    ''' Retuns as full of a name as possible, if a namespace is provided
    ''' the namespace and name are combined with a period, otherwise just
    ''' the name is returned.
    ''' </summary>
    Public Function CreateFullName(ByVal namespaceName As String, ByVal name As String) As String
        If String.IsNullOrEmpty(namespaceName) Then
            Return name
        End If

        Return (namespaceName & ".") + name
    End Function

    ''' <summary>
    ''' Retuns a literal representing the supplied value.
    ''' </summary>
    Public Function CreateLiteral(ByVal value As Object) As String
        If value Is Nothing Then
            Return String.Empty
        End If

        Dim type As Type = value.GetType()
        If type.IsEnum Then
            Return (type.FullName & ".") + value.ToString()
        End If
        If type Is GetType(Guid) Then
            Return String.Format(CultureInfo.InvariantCulture, "New Guid(""{0}"")", DirectCast(value, Guid).ToString("D", CultureInfo.InvariantCulture))
        ElseIf type Is GetType(DateTime) Then
            Return String.Format(CultureInfo.InvariantCulture, "New DateTime({0}, DateTimeKind.Unspecified)", DirectCast(value, DateTime).Ticks)
        ElseIf type Is GetType(Byte()) Then
            Dim arrayInit As String = String.Join(", ", DirectCast(value, Byte()).Select(Function(b) b.ToString(CultureInfo.InvariantCulture)).ToArray())
            Return String.Format(CultureInfo.InvariantCulture, "New Byte() {{{0}}}", arrayInit)
        ElseIf type Is GetType(DateTimeOffset) Then
            Dim dto As DateTimeOffset = DirectCast(value, DateTimeOffset)
            Return String.Format(CultureInfo.InvariantCulture, "New DateTimeOffset({0}, New TimeSpan({1}))", dto.Ticks, dto.Offset.Ticks)
        ElseIf type Is GetType(Decimal) Then
            Return String.Format(CultureInfo.InvariantCulture, "{0}D", DirectCast(value, Decimal).ToString(CultureInfo.InvariantCulture))
        ElseIf type Is GetType(TimeSpan) Then
            Return String.Format(CultureInfo.InvariantCulture, "New TimeSpan({0})", DirectCast(value, TimeSpan).Ticks)
        End If

        Dim expression As CodePrimitiveExpression = New CodePrimitiveExpression(value)
        Dim writer As StringWriter = New StringWriter()
        Dim code As VBCodeProvider = New VBCodeProvider()
        code.GenerateCodeFromExpression(expression, writer, New CodeGeneratorOptions())
        Return writer.ToString()
    End Function

    ''' <summary>
    ''' Returns a resource string from the System.Data.Entity.Design assembly.
    ''' </summary>
    Public Shared Function GetResourceString(resourceName As String, Optional culture As CultureInfo = Nothing) As String
        If _resourceManager Is Nothing Then
            _resourceManager = New System.Resources.ResourceManager("System.Data.Entity.Design", GetType(System.Data.Entity.Design.MetadataItemCollectionFactory).Assembly)
        End If

        Return _resourceManager.GetString(resourceName, culture)
    End Function
    Shared Private _resourceManager As System.Resources.ResourceManager

    Private Const ExternalTypeNameAttributeName As String = "http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName"

    ''' <summary>
    ''' Gets the entity, complex, or enum types for which code should be generated from the given item collection.
    ''' Any types for which an ExternalTypeName annotation has been applied in the conceptual model
    ''' metadata (CSDL) are filtered out of the returned list.
    ''' </summary>
    ''' <typeparam name="T">The type of item to return.</typeparam>
    ''' <param name="itemCollection">The item collection to look in.</param>
    ''' <returns>The items to generate.</returns>
    Public Function GetItemsToGenerate(Of T As GlobalItem)(itemCollection As ItemCollection) As IEnumerable(Of T)
        Return itemCollection.GetItems(Of T)().Where(Function(i) Not i.MetadataProperties.Any(Function(p) p.Name = ExternalTypeNameAttributeName))
    End Function

    ''' <summary>
    ''' Returns the escaped type name to use for the given usage of an o-space type. This might be
    ''' an external type name if the ExternalTypeName annotation has been specified in the
    ''' conceptual model metadata (CSDL).
    ''' </summary>
    ''' <param name="typeUsage">The o-space type usage to get a name for.</param>
    ''' <returns>The type name to use.</returns>
    Public Function GetTypeName(typeUsage As TypeUsage) As String
        Return If(typeUsage Is Nothing, Nothing, GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace := Nothing))
    End Function

    ''' <summary>
    ''' Returns the escaped type name to use for the given o-space type. This might be
    ''' an external type name if the ExternalTypeName annotation has been specified in the
    ''' conceptual model metadata (CSDL).
    ''' </summary>
    ''' <param name="edmType">The o-space type to get a name for.</param>
    ''' <returns>The type name to use.</returns>
    Public Function GetTypeName(edmType As EdmType) As String
        Return GetTypeName(edmType, isNullable := Nothing, modelNamespace := Nothing)
    End Function

    ''' <summary>
    ''' Returns the escaped type name to use for the given usage of an o-space type. This might be
    ''' an external type name if the ExternalTypeName annotation has been specified in the
    ''' conceptual model metadata (CSDL).
    ''' </summary>
    ''' <param name="typeUsage">The o-space type usage to get a name for.</param>
    ''' <param name="modelNamespace">If not null and the type's namespace does not match this namespace, then a
    ''' fully qualified name will be returned.</param>
    ''' <returns>The type name to use.</returns>
    Public Function GetTypeName(typeUsage As TypeUsage, modelNamespace As String) As String
        Return If(typeUsage Is Nothing, Nothing, GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace))
    End Function

    ''' <summary>
    ''' Returns the escaped type name to use for the given o-space type. This might be
    ''' an external type name if the ExternalTypeName annotation has been specified in the
    ''' conceptual model metadata (CSDL).
    ''' </summary>
    ''' <param name="edmType">The o-space type to get a name for.</param>
    ''' <param name="modelNamespace">If not null and the type's namespace does not match this namespace, then a
    ''' fully qualified name will be returned.</param>
    ''' <returns>The type name to use.</returns>
    Public Function GetTypeName(edmType As EdmType, modelNamespace As String) As String
        Return GetTypeName(edmType, isNullable := Nothing, modelNamespace := modelNamespace)
    End Function

    ''' <summary>
    ''' Returns the escaped type name to use for the given o-space type. This might be
    ''' an external type name if the ExternalTypeName annotation has been specified in the
    ''' conceptual model metadata (CSDL).
    ''' </summary>
    ''' <param name="edmType">The o-space type to get a name for.</param>
    ''' <param name="isNullable">Set this to true for nullable usage of this type.</param>
    ''' <param name="modelNamespace">If not null and the type's namespace does not match this namespace, then a
    ''' fully qualified name will be returned.</param>
    ''' <returns>The type name to use.</returns>
    Private Function GetTypeName(edmType As EdmType, isNullable As System.Nullable(Of Boolean), modelNamespace As String) As String
        If edmType Is Nothing Then
            Return Nothing
        End If

        Dim collectionType = TryCast(edmType, CollectionType)
        If collectionType IsNot Nothing Then
            Return String.Format(CultureInfo.InvariantCulture, "ICollection( Of {0})", GetTypeName(collectionType.TypeUsage, modelNamespace))
        End If

        Dim typeName = If(Escape(edmType.MetadataProperties.Where(Function(p) p.Name = ExternalTypeNameAttributeName).[Select](Function(p) DirectCast(p.Value, String)).FirstOrDefault()), (If(modelNamespace IsNot Nothing AndAlso edmType.NamespaceName <> modelNamespace, CreateFullName(EscapeNamespace(edmType.NamespaceName), Escape(edmType)), Escape(edmType))))

        If TypeOf edmType Is StructuralType Then
            Return typeName
        End If

        If TypeOf edmType Is SimpleType Then
            Dim clrType = _ef.UnderlyingClrType(edmType)
            If Not (TypeOf edmType Is EnumType) Then
                typeName = Escape(clrType)
            End If

            Return If(clrType.IsValueType AndAlso isNullable = True, String.Format(CultureInfo.InvariantCulture, "Nullable(Of {0})", typeName), typeName)
        End If

        Throw New ArgumentException("typeUsage")
    End Function

End Class

''' <summary>
''' Responsible for making the Entity Framework Metadata more
''' accessible for code generation.
''' </summary>
Public Class MetadataTools
    Private ReadOnly _textTransformation As DynamicTextTransformation

    ''' <summary>
    ''' Initializes an MetadataTools Instance with the
    ''' TextTransformation (T4 generated class) that is currently running
    ''' </summary>
    Public Sub New(ByVal textTransformation As Object)
        If textTransformation Is Nothing Then
            Throw New ArgumentNullException("textTransformation")
        End If

        _textTransformation = DynamicTextTransformation.Create(textTransformation)
    End Sub

    ''' <summary>
    ''' This method returns the underlying CLR type of the O-space type corresponding to the supplied <paramref name="typeUsage"/>
    ''' Note that for an enum type this means that the type backing the enum will be returned, not the enum type itself.
    ''' </summary>
    Public Function ClrType(typeUsage As TypeUsage) As Type
        Return UnderlyingClrType(typeUsage.EdmType)
    End Function

    ''' <summary>
    ''' This method returns the underlying CLR type of given the O-space type.
    ''' Note that for an enum type this means that the type backing the enum will be returned, not the enum type itself.
    ''' </summary>
    Public Function UnderlyingClrType(edmType As EdmType) As Type
        Dim primitiveType = TryCast(edmType, PrimitiveType)
        If primitiveType IsNot Nothing Then
            Return primitiveType.ClrEquivalentType
        End If

        Dim enumType = TryCast(edmType, EnumType)
        If enumType IsNot Nothing Then
            Return enumType.UnderlyingType.ClrEquivalentType
        End If

        Return GetType(Object)
    End Function

    ''' <summary>
    ''' True if the EdmProperty is a key of its DeclaringType, False otherwise.
    ''' </summary>
    Public Function IsKey(ByVal edmProp As EdmProperty) As Boolean
        If edmProp IsNot Nothing AndAlso edmProp.DeclaringType.BuiltInTypeKind = BuiltInTypeKind.EntityType Then
            Return DirectCast(edmProp.DeclaringType, EntityType).KeyMembers.Contains(edmProp)
        End If

        Return False
    End Function

    ''' <summary>
    ''' True if the EdmProperty TypeUsage is Nullable, False otherwise.
    ''' </summary>
    Public Function IsNullable(ByVal edmProp As EdmProperty) As Boolean
        Return edmProp IsNot Nothing AndAlso IsNullable(edmProp.TypeUsage)
    End Function

    ''' <summary>
    ''' True if the TypeUsage is Nullable, False otherwise.
    ''' </summary>
    Public Function IsNullable(ByVal typeUsage As TypeUsage) As Boolean
        Dim nullableFacet As Facet = Nothing
        If typeUsage IsNot Nothing AndAlso typeUsage.Facets.TryGetValue("Nullable", True, nullableFacet) Then
            Return CBool(nullableFacet.Value)
        End If

        Return False
    End Function

    ''' <summary>
    ''' If the passed in TypeUsage represents a collection this method returns final element
    ''' type of the collection, otherwise it returns the value passed in.
    ''' </summary>
    Public Function GetElementType(ByVal typeUsage As TypeUsage) As TypeUsage
        If typeUsage Is Nothing Then
            Return Nothing
        End If

        If TypeOf typeUsage.EdmType Is CollectionType Then
            Return GetElementType(DirectCast(typeUsage.EdmType, CollectionType).TypeUsage)
        Else
            Return typeUsage
        End If
    End Function

    ''' <summary>
    ''' Returns the NavigationProperty that is the other end of the same association set if it is
    ''' available, otherwise it returns null.
    ''' </summary>
    Public Function Inverse(ByVal navProperty As NavigationProperty) As NavigationProperty
        If navProperty Is Nothing Then
            Return Nothing
        End If

        Dim toEntity As EntityType = navProperty.ToEndMember.GetEntityType()
        Return toEntity.NavigationProperties.SingleOrDefault(Function(n) n.RelationshipType Is navProperty.RelationshipType AndAlso n IsNot navProperty)
    End Function

    ''' <summary>
    ''' Given a property on the dependent end of a referential constraint, returns the corresponding property on the principal end.
    ''' Requires: The association has a referential constraint, and the specified dependentProperty is one of the properties on the dependent end.
    ''' </summary>
    Public Function GetCorrespondingPrincipalProperty(ByVal navProperty As NavigationProperty, ByVal dependentProperty As EdmProperty) As EdmProperty
        If navProperty Is Nothing Then
            Throw New ArgumentNullException("navProperty")
        End If

        If dependentProperty Is Nothing Then
            Throw New ArgumentNullException("dependentProperty")
        End If

        Dim fromProperties As ReadOnlyMetadataCollection(Of EdmProperty) = GetPrincipalProperties(navProperty)
        Dim toProperties As ReadOnlyMetadataCollection(Of EdmProperty) = GetDependentProperties(navProperty)
        Return fromProperties(toProperties.IndexOf(dependentProperty))
    End Function

    ''' <summary>
    ''' Given a property on the principal end of a referential constraint, returns the corresponding property on the dependent end.
    ''' Requires: The association has a referential constraint, and the specified principalProperty is one of the properties on the principal end.
    ''' </summary>
    Public Function GetCorrespondingDependentProperty(ByVal navProperty As NavigationProperty, ByVal principalProperty As EdmProperty) As EdmProperty
        If navProperty Is Nothing Then
            Throw New ArgumentNullException("navProperty")
        End If

        If principalProperty Is Nothing Then
            Throw New ArgumentNullException("principalProperty")
        End If

        Dim fromProperties As ReadOnlyMetadataCollection(Of EdmProperty) = GetPrincipalProperties(navProperty)
        Dim toProperties As ReadOnlyMetadataCollection(Of EdmProperty) = GetDependentProperties(navProperty)
        Return toProperties(fromProperties.IndexOf(principalProperty))
    End Function

    ''' <summary>
    ''' Gets the collection of properties that are on the principal end of a referential constraint for the specified navigation property.
    ''' Requires: The association has a referential constraint.
    ''' </summary>
    Public Function GetPrincipalProperties(ByVal navProperty As NavigationProperty) As ReadOnlyMetadataCollection(Of EdmProperty)
        If navProperty Is Nothing Then
            Throw New ArgumentNullException("navProperty")
        End If

        Return DirectCast(navProperty.RelationshipType, AssociationType).ReferentialConstraints(0).FromProperties
    End Function

    ''' <summary>
    ''' Gets the collection of properties that are on the dependent end of a referential constraint for the specified navigation property.
    ''' Requires: The association has a referential constraint.
    ''' </summary>
    Public Function GetDependentProperties(ByVal navProperty As NavigationProperty) As ReadOnlyMetadataCollection(Of EdmProperty)
        If navProperty Is Nothing Then
            Throw New ArgumentNullException("navProperty")
        End If

        Return DirectCast(navProperty.RelationshipType, AssociationType).ReferentialConstraints(0).ToProperties
    End Function

    ''' <summary>
    ''' True if this entity type requires the HandleCascadeDelete method defined and the method has
    ''' not been defined on any base type
    ''' </summary>
    Public Function NeedsHandleCascadeDeleteMethod(itemCollection As ItemCollection, entity As EntityType) As Boolean
        Dim needsMethod As Boolean = ContainsCascadeDeleteAssociation(itemCollection, entity)
        ' Check to make sure no base types have already declared this method
        Dim baseType As EntityType = TryCast(entity.BaseType, EntityType)
        While needsMethod AndAlso baseType IsNot Nothing
            needsMethod = Not ContainsCascadeDeleteAssociation(itemCollection, baseType)
            baseType = TryCast(baseType.BaseType, EntityType)
        End While
        Return needsMethod
    End Function

    ''' <summary>
    ''' True if this entity type participates in any relationships where the other end has an OnDelete
    ''' cascade delete defined, or if it is the dependent in any identifying relationships
    ''' </summary>
    Private Function ContainsCascadeDeleteAssociation(itemCollection As ItemCollection, entity As EntityType) As Boolean
        Return itemCollection.GetItems(Of AssociationType)().Where(Function(a) DirectCast(a.AssociationEndMembers(0).TypeUsage.EdmType, RefType).ElementType Is entity AndAlso IsCascadeDeletePrincipal(a.AssociationEndMembers(1)) OrElse DirectCast(a.AssociationEndMembers(1).TypeUsage.EdmType, RefType).ElementType Is entity AndAlso IsCascadeDeletePrincipal(a.AssociationEndMembers(0))).Any()
    End Function

    ''' <summary>
    ''' True if the source end of the specified navigation property is the principal in an identifying relationship.
    ''' or if the source end has cascade delete defined.
    ''' </summary>
    Public Function IsCascadeDeletePrincipal(ByVal navProperty As NavigationProperty) As Boolean
        If navProperty Is Nothing Then
            Throw New ArgumentNullException("navProperty")
        End If

        Return IsCascadeDeletePrincipal(DirectCast(navProperty.FromEndMember, AssociationEndMember))
    End Function

    ''' <summary>
    ''' True if the specified association end is the principal in an identifying relationship.
    ''' or if the association end has cascade delete defined.
    ''' </summary>
    Public Function IsCascadeDeletePrincipal(ByVal associationEnd As AssociationEndMember) As Boolean
        If associationEnd Is Nothing Then
            Throw New ArgumentNullException("associationEnd")
        End If

        Return associationEnd.DeleteBehavior = OperationAction.Cascade OrElse IsPrincipalEndOfIdentifyingRelationship(associationEnd)
    End Function

    ''' <summary>
    ''' True if the specified association end is the principal end in an identifying relationship.
    ''' In order to be an identifying relationship, the association must have a referential constraint where all of the dependent properties are part of the dependent type's primary key.
    ''' </summary>
    Public Function IsPrincipalEndOfIdentifyingRelationship(ByVal associationEnd As AssociationEndMember) As Boolean
        If associationEnd Is Nothing Then
            Throw New ArgumentNullException("associationEnd")
        End If

        Dim refConstraint As ReferentialConstraint = DirectCast(associationEnd.DeclaringType, AssociationType).ReferentialConstraints.Where(Function(rc) rc.FromRole Is associationEnd).SingleOrDefault()
        If refConstraint IsNot Nothing Then
            Dim entity As EntityType = refConstraint.ToRole.GetEntityType()
            Return Not refConstraint.ToProperties.Where(Function(tp) Not entity.KeyMembers.Contains(tp)).Any()
        End If
        Return False
    End Function

    ''' <summary>
    ''' True if the specified association type is an identifying relationship.
    ''' In order to be an identifying relationship, the association must have a referential constraint where all of the dependent properties are part of the dependent type's primary key.
    ''' </summary>
    Public Function IsIdentifyingRelationship(ByVal association As AssociationType) As Boolean
        If association Is Nothing Then
            Throw New ArgumentNullException("association")
        End If

        Return IsPrincipalEndOfIdentifyingRelationship(association.AssociationEndMembers(0)) OrElse IsPrincipalEndOfIdentifyingRelationship(association.AssociationEndMembers(1))
    End Function

    ''' <summary>
    ''' requires: firstType is not null
    ''' effects: if secondType is among the base types of the firstType, return true,
    ''' otherwise returns false.
    ''' when firstType is same as the secondType, return false.
    ''' </summary>
    Public Function IsSubtypeOf(ByVal firstType As EdmType, ByVal secondType As EdmType) As Boolean
        If secondType Is Nothing Then
            Return False
        End If

        ' walk up firstType hierarchy list
        Dim t As EdmType = firstType.BaseType
        While t IsNot Nothing
            If t.Equals(secondType) Then
                Return True
            End If
            t = t.BaseType
        End While
        Return False
    End Function

    ''' <summary>
    ''' Returns the subtype of the EntityType in the current itemCollection
    ''' </summary>
    Public Function GetSubtypesOf(ByVal type As EntityType, ByVal itemCollection As ItemCollection, ByVal includeAbstractTypes As Boolean) As IEnumerable(Of EntityType)
        Dim subTypes As List(Of EntityType) = New List(Of EntityType)
        If type IsNot Nothing Then
            Dim typesInCollection As IEnumerable(Of EntityType) = itemCollection.GetItems(Of EntityType)()
            For Each typeInCollection As EntityType In typesInCollection
                If type.Equals(typeInCollection) = False AndAlso Me.IsSubtypeOf(typeInCollection, type) Then
                    If includeAbstractTypes OrElse Not typeInCollection.Abstract Then
                        subTypes.Add(typeInCollection)
                    End If
                End If
            Next
        End If
        Return subTypes
    End Function

    Public Shared Function TryGetStringMetadataPropertySetting(ByVal item As MetadataItem, ByVal propertyName As String, ByRef value As String) As Boolean
        Dim [property] As MetadataProperty = item.MetadataProperties.FirstOrDefault(Function(p) p.Name = propertyName)
        If [property] IsNot Nothing Then
            value = DirectCast([property].Value, String)
        End If
        Return value IsNot Nothing
    End Function

End Class

''' <summary>
''' Responsible for loading an EdmItemCollection from a .edmx file or .csdl files
''' </summary>
Public Class MetadataLoader
    Private ReadOnly _textTransformation As DynamicTextTransformation

    ''' <summary>
    ''' Initializes an MetadataLoader Instance with the
    ''' TextTransformation (T4 generated class) that is currently running
    ''' </summary>
    Public Sub New(ByVal textTransformation As Object)
        If textTransformation Is Nothing Then
            Throw New ArgumentNullException("textTransformation")
        End If

        _textTransformation = DynamicTextTransformation.Create(textTransformation)
    End Sub

    ''' <summary>
    ''' Load the metadata for Edm, Store, and Mapping collections and register them
    ''' with a new MetadataWorkspace, returns false if any of the parts can't be
    ''' created, some of the ItemCollections may be registered and usable even if false is
    ''' returned
    ''' </summary>
    Public Function TryLoadAllMetadata(ByVal inputFile As String, ByRef metadataWorkspace As MetadataWorkspace) As Boolean
        metadataWorkspace = New MetadataWorkspace()

        Dim edmItemCollection As EdmItemCollection = CreateEdmItemCollection(inputFile)
        metadataWorkspace.RegisterItemCollection(edmItemCollection)

        Dim storeItemCollection As StoreItemCollection = Nothing
        If TryCreateStoreItemCollection(inputFile, storeItemCollection) Then
            Dim storageMappingItemCollection As StorageMappingItemCollection = Nothing
            If TryCreateStorageMappingItemCollection(inputFile, edmItemCollection, storeItemCollection, storageMappingItemCollection) Then
                metadataWorkspace.RegisterItemCollection(storeItemCollection)
                metadataWorkspace.RegisterItemCollection(storageMappingItemCollection)
                Return True
            End If
        End If

        Return False
    End Function

    ''' <summary>
    ''' Create an EdmItemCollection loaded with the metadata provided
    ''' </summary>
    Public Function CreateEdmItemCollection(ByVal sourcePath As String, ByVal ParamArray referenceSchemas As String()) As EdmItemCollection
        Dim edmItemCollection As EdmItemCollection = Nothing
        If TryCreateEdmItemCollection(sourcePath, referenceSchemas, edmItemCollection) Then
            Return edmItemCollection
        End If

        Return New EdmItemCollection()
    End Function

    ''' <summary>
    ''' Attempts to create a EdmItemCollection from the specified metadata file
    ''' </summary>
    Public Function TryCreateEdmItemCollection(ByVal sourcePath As String, ByRef edmItemCollection As EdmItemCollection) As Boolean
        Return TryCreateEdmItemCollection(sourcePath, Nothing, edmItemCollection)
    End Function

    ''' <summary>
    ''' Attempts to create a EdmItemCollection from the specified metadata file
    ''' </summary>
    Public Function TryCreateEdmItemCollection(ByVal sourcePath As String, ByVal referenceSchemas As String(), ByRef edmItemCollection As EdmItemCollection) As Boolean
        edmItemCollection = Nothing

        If Not ValidateInputPath(sourcePath, _textTransformation) Then
            Return False
        End If

        If referenceSchemas Is Nothing Then
            referenceSchemas = New String(-1) {}
        End If

        Dim itemCollection As ItemCollection = Nothing
        sourcePath = _textTransformation.Host.ResolvePath(sourcePath)
        Dim collectionBuilder As New EdmItemCollectionBuilder(_textTransformation, referenceSchemas.Select(Function(s) _textTransformation.Host.ResolvePath(s)).Where(Function(s) s <> sourcePath))
        If collectionBuilder.TryCreateItemCollection(sourcePath, itemCollection) Then
            edmItemCollection = DirectCast(itemCollection, EdmItemCollection)
        End If

        Return edmItemCollection IsNot Nothing
    End Function

    ''' <summary>
    ''' Attempts to create a StoreItemCollection from the specified metadata file
    ''' </summary>
    Public Function TryCreateStoreItemCollection(ByVal sourcePath As String, ByRef storeItemCollection As StoreItemCollection) As Boolean
        storeItemCollection = Nothing

        If Not ValidateInputPath(sourcePath, _textTransformation) Then
            Return False
        End If

        Dim itemCollection As ItemCollection = Nothing
        Dim collectionBuilder As New StoreItemCollectionBuilder(_textTransformation)
        If collectionBuilder.TryCreateItemCollection(_textTransformation.Host.ResolvePath(sourcePath), itemCollection) Then
            storeItemCollection = DirectCast(itemCollection, StoreItemCollection)
        End If
        Return storeItemCollection IsNot Nothing
    End Function

    ''' <summary>
    ''' Attempts to create a StorageMappingItemCollection from the specified metadata file, EdmItemCollection, and StoreItemCollection
    ''' </summary>
    Public Function TryCreateStorageMappingItemCollection(ByVal sourcePath As String, ByVal edmItemCollection As EdmItemCollection, ByVal storeItemCollection As StoreItemCollection, ByRef storageMappingItemCollection As StorageMappingItemCollection) As Boolean
        storageMappingItemCollection = Nothing

        If Not ValidateInputPath(sourcePath, _textTransformation) Then
            Return False
        End If

        If edmItemCollection Is Nothing Then
            Throw New ArgumentNullException("edmItemCollection")
        End If

        If storeItemCollection Is Nothing Then
            Throw New ArgumentNullException("storeItemCollection")
        End If

        Dim itemCollection As ItemCollection = Nothing
        Dim collectionBuilder As New StorageMappingItemCollectionBuilder(_textTransformation, edmItemCollection, storeItemCollection)
        If collectionBuilder.TryCreateItemCollection(_textTransformation.Host.ResolvePath(sourcePath), itemCollection) Then
            storageMappingItemCollection = DirectCast(itemCollection, StorageMappingItemCollection)
        End If
        Return storageMappingItemCollection IsNot Nothing
    End Function

    ''' <summary>
    ''' Gets the Model Namespace from the provided schema file.
    ''' </summary>
    Public Function GetModelNamespace(ByVal sourcePath As String) As String
        If Not ValidateInputPath(sourcePath, _textTransformation) Then
            Return String.Empty
        End If

        Dim builder As New EdmItemCollectionBuilder(_textTransformation)
        Dim model As XElement = Nothing
        If builder.TryLoadRootElement(_textTransformation.Host.ResolvePath(sourcePath), model) Then
            Dim attribute As XAttribute = model.Attribute("Namespace")
            If attribute IsNot Nothing Then
                Return attribute.Value
            End If
        End If

        Return String.Empty
    End Function

    ''' <summary>
    ''' Returns true if the specified file path is valid
    ''' </summary>
    Private Shared Function ValidateInputPath(sourcePath As String, textTransformation As DynamicTextTransformation) As Boolean
        If String.IsNullOrEmpty(sourcePath) Then
            Throw New ArgumentException("sourcePath")
        End If

        If sourcePath = "$edmxInputFile$" Then
            textTransformation.Errors.Add(New CompilerError(If(textTransformation.Host.TemplateFile, CodeGenerationTools.GetResourceString("Template_CurrentlyRunningTemplate")), -1, -1, String.Empty, _
                CodeGenerationTools.GetResourceString("Template_ReplaceVsItemTemplateToken")))
            Return False
        End If

        Return True
    End Function

    ''' <summary>
    ''' base class for ItemCollectionBuilder classes that
    ''' load the specific types of metadata
    ''' </summary>
    Private MustInherit Class ItemCollectionBuilder
        Private ReadOnly _textTransformation As DynamicTextTransformation
        Private ReadOnly _fileExtension As String
        Private ReadOnly _edmxSectionName As String
        Private ReadOnly _rootElementName As String

        ''' <summary>
        ''' FileExtension for individual (non-edmx) metadata file for this
        ''' specific ItemCollection type
        ''' </summary>
        Public ReadOnly Property FileExtension() As String
            Get
                Return _fileExtension
            End Get
        End Property

        ''' <summary>
        ''' The name of the XmlElement in the .edmx <Runtime> element
        ''' to find this ItemCollection's metadata
        ''' </summary>
        Public ReadOnly Property EdmxSectionName() As String
            Get
                Return _edmxSectionName
            End Get
        End Property

        ''' <summary>
        ''' The name of the root element of this ItemCollection's metadata
        ''' </summary>
        Public ReadOnly Property RootElementName() As String
            Get
                Return _rootElementName
            End Get
        End Property

        ''' <summary>
        ''' Method to build the appropriate ItemCollection
        ''' </summary>
        Protected MustOverride Function CreateItemCollection(ByVal readers As IEnumerable(Of XmlReader), ByRef errors As IList(Of EdmSchemaError)) As ItemCollection

        ''' <summary>
        ''' Ctor to setup the ItemCollectionBuilder members
        ''' </summary>
        Protected Sub New(ByVal textTransformation As DynamicTextTransformation, ByVal fileExtension As String, ByVal edmxSectionName As String, ByVal rootElementName As String)
            _textTransformation = textTransformation
            _fileExtension = fileExtension
            _edmxSectionName = edmxSectionName
            _rootElementName = rootElementName
        End Sub

        ''' <summary>
        ''' Selects a namespace from the supplied constants.
        ''' </summary>
        Protected MustOverride Function GetNamespace(ByVal constants As SchemaConstants) As String

        ''' <summary>
        ''' Try to create an ItemCollection loaded with the metadata provided
        ''' </summary>
        Public Function TryCreateItemCollection(ByVal sourcePath As String, ByRef itemCollection As ItemCollection) As Boolean
            itemCollection = Nothing

            If Not ValidateInputPath(sourcePath, _textTransformation) Then
                Return False
            End If

            Dim schemaElement As XElement = Nothing
            If TryLoadRootElement(sourcePath, schemaElement) Then
                Dim readers As New List(Of XmlReader)()
                Try
                    readers.Add(schemaElement.CreateReader())
                    Dim errors As IList(Of EdmSchemaError) = Nothing

                    Dim tempItemCollection As ItemCollection = CreateItemCollection(readers, errors)
                    If ProcessErrors(errors, sourcePath) Then
                        Return False
                    End If

                    itemCollection = tempItemCollection
                    Return True
                Finally
                    For Each reader As XmlReader In readers
                        DirectCast(reader, IDisposable).Dispose()
                    Next
                End Try
            End If

            Return False
        End Function

        ''' <summary>
        ''' Tries to load the root element from the metadata file provided
        ''' </summary>
        Public Function TryLoadRootElement(ByVal sourcePath As String, ByRef schemaElement As XElement) As Boolean
            schemaElement = Nothing
            Dim extension As String = Path.GetExtension(sourcePath)
            If extension.Equals(".edmx", StringComparison.InvariantCultureIgnoreCase) Then
                Return TryLoadRootElementFromEdmx(sourcePath, schemaElement)
            ElseIf extension.Equals(FileExtension, StringComparison.InvariantCultureIgnoreCase) Then
                ' load from single metadata file (.csdl, .ssdl, or .msl)
                schemaElement = XElement.Load(sourcePath, LoadOptions.SetBaseUri Or LoadOptions.SetLineInfo)
                Return True
            End If

            Return False
        End Function

        ''' <summary>
        ''' Tries to load the root element from the provided edmxDocument
        ''' </summary>
        Private Function TryLoadRootElementFromEdmx(ByVal edmxDocument As XElement, ByVal schemaConstants As SchemaConstants, ByVal sectionName As String, ByVal rootElementName As String, ByRef rootElement As XElement) As Boolean
            rootElement = Nothing

            Dim edmxNs As XNamespace = schemaConstants.EdmxNamespace
            Dim sectionNs As XNamespace = GetNamespace(schemaConstants)

            Dim runtime As XElement = edmxDocument.Element(edmxNs + "Runtime")
            If runtime Is Nothing Then
                Return False
            End If

            Dim section As XElement = runtime.Element(edmxNs + sectionName)
            If section Is Nothing Then
                Return False
            End If

            Dim templateVersion As String = Nothing

            If Not TemplateMetadata.TryGetValue(MetadataConstants.TT_TEMPLATE_VERSION, templateVersion) Then
                templateVersion = MetadataConstants.DEFAULT_TEMPLATE_VERSION
            End If

            If schemaConstants.MinimumTemplateVersion > New Version(templateVersion) Then
                _textTransformation.Errors.Add(New CompilerError(If(_textTransformation.Host.TemplateFile, CodeGenerationTools.GetResourceString("Template_CurrentlyRunningTemplate")), -1, -1, String.Empty, _
                    CodeGenerationTools.GetResourceString("Template_UnsupportedSchema")) With { _
                        .IsWarning = True _
                    })
            End If

            rootElement = section.Element(sectionNs + rootElementName)
            Return rootElement IsNot Nothing
        End Function

        ''' <summary>
        ''' Tries to load the root element from the provided .edmx metadata file
        ''' </summary>
        Private Function TryLoadRootElementFromEdmx(ByVal edmxPath As String, ByRef rootElement As XElement) As Boolean
            rootElement = Nothing

            Dim element As XElement = XElement.Load(edmxPath, LoadOptions.SetBaseUri Or LoadOptions.SetLineInfo)

            Return TryLoadRootElementFromEdmx(element, MetadataConstants.V3_SCHEMA_CONSTANTS, EdmxSectionName, RootElementName, rootElement) OrElse TryLoadRootElementFromEdmx(element, MetadataConstants.V2_SCHEMA_CONSTANTS, EdmxSectionName, RootElementName, rootElement) OrElse TryLoadRootElementFromEdmx(element, MetadataConstants.V1_SCHEMA_CONSTANTS, EdmxSectionName, RootElementName, rootElement)
        End Function

        ''' <summary>
        ''' Takes an Enumerable of EdmSchemaErrors, and adds them
        ''' to the errors collection of the template class
        ''' </summary>
        Private Function ProcessErrors(ByVal errors As IEnumerable(Of EdmSchemaError), ByVal sourceFilePath As String) As Boolean
            Dim foundErrors As Boolean = False
            For Each schemaError As EdmSchemaError In errors
                Dim newError As New CompilerError(schemaError.SchemaLocation, schemaError.Line, schemaError.Column, schemaError.ErrorCode.ToString(CultureInfo.InvariantCulture), schemaError.Message)
                newError.IsWarning = schemaError.Severity = EdmSchemaErrorSeverity.Warning
                foundErrors = foundErrors Or schemaError.Severity = EdmSchemaErrorSeverity.Error
                If schemaError.SchemaLocation Is Nothing Then
                    newError.FileName = sourceFilePath
                End If
                _textTransformation.Errors.Add(newError)
            Next

            Return foundErrors
        End Function
    End Class

    ''' <summary>
    ''' Builder class for creating a StorageMappingItemCollection
    ''' </summary>
    Private Class StorageMappingItemCollectionBuilder
        Inherits ItemCollectionBuilder
        Private ReadOnly _edmItemCollection As EdmItemCollection
        Private ReadOnly _storeItemCollection As StoreItemCollection

        Public Sub New(ByVal textTransformation As DynamicTextTransformation, ByVal edmItemCollection As EdmItemCollection, ByVal storeItemCollection As StoreItemCollection)
            MyBase.New(textTransformation, MetadataConstants.MSL_EXTENSION, MetadataConstants.MSL_EDMX_SECTION_NAME, MetadataConstants.MSL_ROOT_ELEMENT_NAME)
            _edmItemCollection = edmItemCollection
            _storeItemCollection = storeItemCollection
        End Sub

        Protected Overloads Overrides Function CreateItemCollection(ByVal readers As IEnumerable(Of XmlReader), ByRef errors As IList(Of EdmSchemaError)) As ItemCollection
            Return MetadataItemCollectionFactory.CreateStorageMappingItemCollection(_edmItemCollection, _storeItemCollection, readers, errors)
        End Function

        ''' <summary>
        ''' Selects a namespace from the supplied constants.
        ''' </summary>
        Protected Overrides Function GetNamespace(ByVal constants As SchemaConstants) As String
            Return constants.MslNamespace
        End Function
    End Class

    ''' <summary>
    ''' Builder class for creating a StoreItemCollection
    ''' </summary>
    Private Class StoreItemCollectionBuilder
        Inherits ItemCollectionBuilder
        Public Sub New(ByVal textTransformation As DynamicTextTransformation)
            MyBase.New(textTransformation, MetadataConstants.SSDL_EXTENSION, MetadataConstants.SSDL_EDMX_SECTION_NAME, MetadataConstants.SSDL_ROOT_ELEMENT_NAME)
        End Sub

        Protected Overloads Overrides Function CreateItemCollection(ByVal readers As IEnumerable(Of XmlReader), ByRef errors As IList(Of EdmSchemaError)) As ItemCollection
            Return MetadataItemCollectionFactory.CreateStoreItemCollection(readers, errors)
        End Function

        ''' <summary>
        ''' Selects a namespace from the supplied constants.
        ''' </summary>
        Protected Overrides Function GetNamespace(ByVal constants As SchemaConstants) As String
            Return constants.SsdlNamespace
        End Function

    End Class

    ''' <summary>
    ''' Builder class for creating a EdmItemCollection
    ''' </summary>
    Private Class EdmItemCollectionBuilder
        Inherits ItemCollectionBuilder
        Private _referenceSchemas As New List(Of String)()

        Public Sub New(ByVal textTransformation As DynamicTextTransformation)
            MyBase.New(textTransformation, MetadataConstants.CSDL_EXTENSION, MetadataConstants.CSDL_EDMX_SECTION_NAME, MetadataConstants.CSDL_ROOT_ELEMENT_NAME)
        End Sub

        Public Sub New(ByVal textTransformation As DynamicTextTransformation, ByVal referenceSchemas As IEnumerable(Of String))
            Me.New(textTransformation)
            _referenceSchemas.AddRange(referenceSchemas)
        End Sub

        Protected Overloads Overrides Function CreateItemCollection(ByVal readers As IEnumerable(Of XmlReader), ByRef errors As IList(Of EdmSchemaError)) As ItemCollection
            Dim ownedReaders As New List(Of XmlReader)()
            Dim allReaders As New List(Of XmlReader)()
            Try
                allReaders.AddRange(readers)
                For Each path As String In _referenceSchemas.Distinct()
                    Dim reference As XElement = Nothing
                    If TryLoadRootElement(path, reference) Then
                        Dim reader As XmlReader = reference.CreateReader()
                        allReaders.Add(reader)
                        ownedReaders.Add(reader)
                    End If
                Next

                Return MetadataItemCollectionFactory.CreateEdmItemCollection(allReaders, errors)
            Finally
                For Each reader As XmlReader In ownedReaders
                    DirectCast(reader, IDisposable).Dispose()
                Next
            End Try
        End Function

        ''' <summary>
        ''' Selects a namespace from the supplied constants.
        ''' </summary>
        Protected Overrides Function GetNamespace(ByVal constants As SchemaConstants) As String
            Return constants.CsdlNamespace
        End Function
    End Class
End Class

''' <summary>
''' Responsible for encapsulating the retrieval and translation of the CodeGeneration
''' annotations in the EntityFramework Metadata to a form that is useful in code generation.
''' </summary>
Public Class Accessibility
    Private Sub New()
    End Sub
    Private Const GETTER_ACCESS As String = "http://schemas.microsoft.com/ado/2006/04/codegeneration:GetterAccess"
    Private Const SETTER_ACCESS As String = "http://schemas.microsoft.com/ado/2006/04/codegeneration:SetterAccess"
    Private Const TYPE_ACCESS As String = "http://schemas.microsoft.com/ado/2006/04/codegeneration:TypeAccess"
    Private Const METHOD_ACCESS As String = "http://schemas.microsoft.com/ado/2006/04/codegeneration:MethodAccess"
    Private Const ACCESS_PROTECTED As String = "Protected"
    Private Const ACCESS_INTERNAL As String = "Internal"
    Private Const ACCESS_PRIVATE As String = "Private"
    Private Shared ReadOnly AccessibilityRankIdLookup As New Dictionary(Of String, Integer)() From _
        { _
            { "Private", 1}, _
            { "Friend", 2}, _
            { "Protected", 3}, _
            { "Public", 4} _
        }

    ''' <summary>
    ''' Gets the accessibility that should be applied to a type being generated from the provided GlobalItem.
    '''
    ''' defaults to public if no annotation is found.
    ''' </summary>
    Public Shared Function ForType(ByVal item As GlobalItem) As String
        If item Is Nothing Then
            Return Nothing
        End If

        Return GetAccessibility(item, TYPE_ACCESS)
    End Function

    ''' <summary>
    ''' Gets the accessibility that should be applied at the property level for a property being
    ''' generated from the provided EdmMember.
    '''
    ''' defaults to public if no annotation is found.
    ''' </summary>
    Public Shared Function ForProperty(ByVal member As EdmMember) As String
        If member Is Nothing Then
            Return Nothing
        End If

        Dim getterAccess As String = Nothing
        Dim setterAccess As String = Nothing
        Dim propertyAccess As String = Nothing
        CalculatePropertyAccessibility(member, propertyAccess, getterAccess, setterAccess)
        Return propertyAccess
    End Function

    ''' <summary>
    ''' Gets the accessibility that should be applied at the property level for a Read-Only property being
    ''' generated from the provided EdmMember.
    '''
    ''' defaults to public if no annotation is found.
    ''' </summary>
    Public Shared Function ForReadOnlyProperty(ByVal member As EdmMember) As String
        If member Is Nothing Then
            Return Nothing
        End If

        Return GetAccessibility(member, GETTER_ACCESS)
    End Function

    ''' <summary>
    ''' Gets the accessibility that should be applied at the property level for a property being
    ''' generated from the provided EntitySet.
    '''
    ''' defaults to public if no annotation is found.
    ''' </summary>
    Public Shared Function ForReadOnlyProperty(ByVal edmSet As EntitySet) As String
        If edmSet Is Nothing Then
            Return Nothing
        End If

        Return GetAccessibility(edmSet, GETTER_ACCESS)
    End Function

    ''' <summary>
    ''' Gets the accessibility that should be applied at the property level for a Write-Only property being
    ''' generated from the provided EdmMember.
    '''
    ''' defaults to public if no annotation is found.
    ''' </summary>
    Public Shared Function ForWriteOnlyProperty(ByVal member As EdmMember) As String
        If member Is Nothing Then
            Return Nothing
        End If

        Return GetAccessibility(member, SETTER_ACCESS)
    End Function

    ''' <summary>
    ''' Gets the accessibility that should be applied at the get level for a property being
    ''' generated from the provided EdmMember.
    '''
    ''' defaults to empty if no annotation is found or the accessibility is the same as the property level.
    ''' </summary>
    Public Shared Function ForGetter(ByVal member As EdmMember) As String
        If member Is Nothing Then
            Return Nothing
        End If

        Dim getterAccess As String = Nothing
        Dim setterAccess As String = Nothing
        Dim propertyAccess As String = Nothing
        CalculatePropertyAccessibility(member, propertyAccess, getterAccess, setterAccess)
        Return getterAccess
    End Function

    ''' <summary>
    ''' Gets the accessibility that should be applied at the set level for a property being
    ''' generated from the provided EdmMember.
    '''
    ''' defaults to empty if no annotation is found or the accessibility is the same as the property level.
    ''' </summary>
    Public Shared Function ForSetter(ByVal member As EdmMember) As String
        If member Is Nothing Then
            Return Nothing
        End If

        Dim getterAccess As String = Nothing
        Dim setterAccess As String = Nothing
        Dim propertyAccess As String = Nothing
        CalculatePropertyAccessibility(member, propertyAccess, getterAccess, setterAccess)
        Return setterAccess
    End Function

    ''' <summary>
    ''' Gets the accessibility that should be applied to a method being generated from the provided EdmFunction.
    '''
    ''' defaults to public if no annotation is found.
    ''' </summary>
    Public Shared Function ForMethod(ByVal edmFunction As EdmFunction) As String
        If edmFunction Is Nothing Then
            Return Nothing
        End If

        Return GetAccessibility(edmFunction, METHOD_ACCESS)
    End Function

    Private Shared Sub CalculatePropertyAccessibility(ByVal item As MetadataItem, ByRef propertyAccessibility As String, ByRef getterAccessibility As String, ByRef setterAccessibility As String)
        getterAccessibility = GetAccessibility(item, GETTER_ACCESS)
        Dim getterRank As Integer = AccessibilityRankIdLookup(getterAccessibility)

        setterAccessibility = GetAccessibility(item, SETTER_ACCESS)
        Dim setterRank As Integer = AccessibilityRankIdLookup(setterAccessibility)

        Dim propertyRank As Integer = Math.Max(getterRank, setterRank)
        If setterRank = propertyRank Then
            setterAccessibility = String.Empty
        End If

        If getterRank = propertyRank Then
            getterAccessibility = String.Empty
        End If

        propertyAccessibility = AccessibilityRankIdLookup.Where(Function(v) v.Value = propertyRank).Select(Function(v) v.Key).Single()
    End Sub

    Private Shared Function GetAccessibility(ByVal item As MetadataItem, ByVal name As String) As String
        Dim accessibility As String = Nothing
        If MetadataTools.TryGetStringMetadataPropertySetting(item, name, accessibility) Then
            Return TranslateUserAccessibilityToCSharpAccessibility(accessibility)
        End If

        Return "Public"
    End Function

    Private Shared Function TranslateUserAccessibilityToCSharpAccessibility(ByVal userAccessibility As String) As String
        If userAccessibility = ACCESS_PROTECTED Then
            Return "Protected"
        ElseIf userAccessibility = ACCESS_INTERNAL Then
            Return "Friend"
        ElseIf userAccessibility = ACCESS_PRIVATE Then
            Return "Private"
        Else
            ' default to public
            Return "Public"
        End If
    End Function

End Class

''' <summary>
''' Responsible for creating source code regions in code when the loop inside
''' actually produces something.
''' </summary>
Public Class CodeRegion
    Private Const STANDARD_INDENT_LENGTH As Integer = 4

    Private ReadOnly _textTransformation As DynamicTextTransformation
    Private _beforeRegionLength As Integer
    Private _emptyRegionLength As Integer
    Private _regionIndentLevel As Integer = -1

    ''' <summary>
    ''' Initializes an CodeRegion instance with the
    ''' TextTransformation (T4 generated class) that is currently running
    ''' </summary>
    Public Sub New(ByVal textTransformation As Object)
        If textTransformation Is Nothing Then
            Throw New ArgumentNullException("textTransformation")
        End If

        _textTransformation = DynamicTextTransformation.Create(textTransformation)
    End Sub

    ''' <summary>
    ''' Initializes an CodeRegion instance with the
    ''' TextTransformation (T4 generated class) that is currently running,
    ''' and the indent level to start the first region at.
    ''' </summary>
    Public Sub New(ByVal textTransformation As Object, ByVal firstIndentLevel As Integer)
        Me.New(textTransformation)
        If firstIndentLevel < 0 Then
            Throw New ArgumentException("firstIndentLevel")
        End If

        _regionIndentLevel = firstIndentLevel - 1
    End Sub

    ''' <summary>
    ''' Starts the begining of a region
    ''' </summary>
    Public Sub Begin(ByVal regionName As String)
        If regionName Is Nothing Then
            Throw New ArgumentNullException("regionName")
        End If

        Begin(regionName, 1)
    End Sub

    ''' <summary>
    ''' Start the begining of a region, indented
    ''' the numbers of levels specified
    ''' </summary>
    Public Sub Begin(ByVal regionName As String, ByVal levelsToIncreaseIndent As Integer)
        If regionName Is Nothing Then
            Throw New ArgumentNullException("regionName")
        End If

        _beforeRegionLength = _textTransformation.GenerationEnvironment.Length
        _regionIndentLevel += levelsToIncreaseIndent
        _textTransformation.Write(GetIndent(_regionIndentLevel))
        _textTransformation.WriteLine("#Region """ + regionName + """")
        _emptyRegionLength = _textTransformation.GenerationEnvironment.Length
    End Sub

    ''' <summary>
    ''' Ends a region, or totaly removes it if nothing
    ''' was generted since the begining of the region.
    ''' </summary>
    Public Sub [End]()
        [End](1)
    End Sub

    ''' <summary>
    ''' Ends a region, or totaly removes it if nothing
    ''' was generted since the begining of the region, also outdents
    ''' the number of levels specified.
    ''' </summary>
    Public Sub [End](ByVal levelsToDecrease As Integer)
        Dim indentLevel As Integer = _regionIndentLevel
        _regionIndentLevel -= levelsToDecrease

        If _emptyRegionLength = _textTransformation.GenerationEnvironment.Length Then
            _textTransformation.GenerationEnvironment.Length = _beforeRegionLength
        Else
            _textTransformation.WriteLine(String.Empty)
            _textTransformation.Write(GetIndent(indentLevel))
            _textTransformation.WriteLine("#End Region")
            _textTransformation.WriteLine(String.Empty)
        End If
    End Sub

    ''' <summary>
    ''' Gets the current indent level that the next end region statement will be written
    ''' at
    ''' </summary>
    Public ReadOnly Property CurrentIndentLevel() As Integer
        Get
            Return _regionIndentLevel
        End Get
    End Property

    ''' <summary>
    ''' Get a string of spaces equivelent to the number of indents
    ''' desired.
    ''' </summary>
    Public Shared Function GetIndent(ByVal indentLevel As Integer) As String
        If indentLevel < 0 Then
            Throw New ArgumentException("indentLevel")
        End If

        Return String.Empty.PadLeft(indentLevel * STANDARD_INDENT_LENGTH)
    End Function
End Class


''' <summary>
''' Responsible for collecting together the actual method parameters
''' and the parameters that need to be sent to the Execute method.
''' </summary>
Public Class FunctionImportParameter
Private _Source As FunctionParameter
    Public Property Source() As FunctionParameter
        Get
            Return _Source
        End Get
        Set(ByVal value As FunctionParameter)
            _Source = value
        End Set
    End Property
Private _RawFunctionParameterName As String
    Public Property RawFunctionParameterName() As String
        Get
            Return _RawFunctionParameterName
        End Get
        Set(ByVal value As String)
            _RawFunctionParameterName = value
        End Set
    End Property
Private _FunctionParameterName As String
    Public Property FunctionParameterName() As String
        Get
            Return _FunctionParameterName
        End Get
        Set(ByVal value As String)
            _FunctionParameterName = value
        End Set
    End Property
Private _FunctionParameterType As String
    Public Property FunctionParameterType() As String
        Get
            Return _FunctionParameterType
        End Get
        Set(ByVal value As String)
            _FunctionParameterType = value
        End Set
    End Property
Private _LocalVariableName As String
    Public Property LocalVariableName() As String
        Get
            Return _LocalVariableName
        End Get
        Set(ByVal value As String)
            _LocalVariableName = value
        End Set
    End Property
Private _RawClrTypeName As String
    Public Property RawClrTypeName() As String
        Get
            Return _RawClrTypeName
        End Get
        Set(ByVal value As String)
            _RawClrTypeName = value
        End Set
    End Property
Private _ExecuteParameterName As String
    Public Property ExecuteParameterName() As String
        Get
            Return _ExecuteParameterName
        End Get
        Set(ByVal value As String)
            _ExecuteParameterName = value
        End Set
    End Property
Private _EsqlParameterName As String
    Public Property EsqlParameterName() As String
        Get
            Return _EsqlParameterName
        End Get
        Set(ByVal value As String)
            _EsqlParameterName = value
        End Set
    End Property
Private _NeedsLocalVariable As Boolean
    Public Property NeedsLocalVariable() As Boolean
        Get
            Return _NeedsLocalVariable
        End Get
        Set(ByVal value As Boolean)
            _NeedsLocalVariable = value
        End Set
    End Property
Private _IsNullableOfT As Boolean
    Public Property IsNullableOfT() As Boolean
        Get
            Return _IsNullableOfT
        End Get
        Set(ByVal value As Boolean)
            _IsNullableOfT = value
        End Set
    End Property


    ''' <summary>
    ''' Creates a set of FunctionImportParameter objects from the parameters passed in.
    ''' </summary>
    Public Shared Function Create(ByVal parameters As IEnumerable(Of FunctionParameter), ByVal code As CodeGenerationTools, ByVal ef As MetadataTools) As IEnumerable(Of FunctionImportParameter)
        If parameters Is Nothing Then
            Throw New ArgumentNullException("parameters")
        End If

        If code Is Nothing Then
            Throw New ArgumentNullException("code")
        End If

        If ef Is Nothing Then
            Throw New ArgumentNullException("ef")
        End If

        Dim unique As New UniqueIdentifierService()
        Dim importParameters As New List(Of FunctionImportParameter)()
        For Each parameter As FunctionParameter In parameters
            Dim importParameter As New FunctionImportParameter()
            importParameter.Source = parameter
            importParameter.RawFunctionParameterName = unique.AdjustIdentifier(code.CamelCase(parameter.Name))
            importParameter.FunctionParameterName = code.Escape(importParameter.RawFunctionParameterName)
            If parameter.Mode = ParameterMode.In Then
                Dim typeUsage As TypeUsage = parameter.TypeUsage
                importParameter.NeedsLocalVariable = True
                importParameter.FunctionParameterType = code.GetTypeName(typeUsage)
                importParameter.EsqlParameterName = parameter.Name
                Dim clrType As Type = ef.UnderlyingClrType(parameter.TypeUsage.EdmType)
                importParameter.RawClrTypeName = If(TypeOf typeUsage.EdmType Is EnumType, code.GetTypeName(typeUsage.EdmType), code.Escape(clrType))
                importParameter.IsNullableOfT = clrType.IsValueType
            Else
                importParameter.NeedsLocalVariable = False
                importParameter.FunctionParameterType = "ObjectParameter"
                importParameter.ExecuteParameterName = importParameter.FunctionParameterName
            End If
            importParameters.Add(importParameter)
        Next

        ' we save the local parameter uniquification for a second pass to make the visible parameters
        ' as pretty and sensible as possible
        For i As Integer = 0 To importParameters.Count - 1
            Dim importParameter As FunctionImportParameter = importParameters(i)
            If importParameter.NeedsLocalVariable Then
                importParameter.LocalVariableName = unique.AdjustIdentifier(importParameter.RawFunctionParameterName & "Parameter")
                importParameter.ExecuteParameterName = importParameter.LocalVariableName
            End If
        Next

        Return importParameters
    End Function

    '
    ' Class to create unique variables within the same scope
    '
    Private NotInheritable Class UniqueIdentifierService
        Private ReadOnly _knownIdentifiers As HashSet(Of String)

        Public Sub New()
            _knownIdentifiers = New HashSet(Of String)(StringComparer.OrdinalIgnoreCase)
        End Sub

        ''' <summary>
        ''' Given an identifier, makes it unique within the scope by adding
        ''' a suffix (1, 2, 3, ...), and returns the adjusted identifier.
        ''' </summary>
        Public Function AdjustIdentifier(ByVal identifier As String) As String
            ' find a unique name by adding suffix as necessary
            Dim numberOfConflicts As Integer = 0
            Dim adjustedIdentifier As String = identifier

            While Not _knownIdentifiers.Add(adjustedIdentifier)
                numberOfConflicts += 1
                adjustedIdentifier = identifier + numberOfConflicts.ToString(CultureInfo.InvariantCulture)
            End While

            Return adjustedIdentifier
        End Function
    End Class
End Class

''' <summary>
''' Responsible for marking the various sections of the generation,
''' so they can be split up into separate files
''' </summary>
Public Class EntityFrameworkTemplateFileManager
    ''' <summary>
    ''' Creates the VsEntityFrameworkTemplateFileManager if VS is detected, otherwise
    ''' creates the file system version.
    ''' </summary>
    Public Shared Function Create(ByVal textTransformation As Object) As EntityFrameworkTemplateFileManager
        Dim transformation As DynamicTextTransformation = DynamicTextTransformation.Create(textTransformation)
        Dim host As IDynamicHost = transformation.Host

        #If Not PREPROCESSED_TEMPLATE Then
        Dim hostServiceProvider = host.AsIServiceProvider()
        If hostServiceProvider IsNot Nothing Then
            Dim dte = DirectCast(hostServiceProvider.GetService(GetType(EnvDTE.DTE)), EnvDTE.DTE)
            If dte IsNot Nothing Then
                Return New VsEntityFrameworkTemplateFileManager(transformation)
            End If
        End If
        #End If
        Return New EntityFrameworkTemplateFileManager(transformation)
    End Function

    Private NotInheritable Class Block
        Public Name As String
        Public Start As Integer, Length As Integer
    End Class

    Private ReadOnly files As New List(Of Block)()
    Private ReadOnly footer As New Block()
    Private ReadOnly header As New Block()
    Private ReadOnly _textTransformation As DynamicTextTransformation

    ' reference to the GenerationEnvironment StringBuilder on the
    ' TextTransformation object
    Private ReadOnly _generationEnvironment As StringBuilder

    Private m_currentBlock As Block

    ''' <summary>
    ''' Initializes an EntityFrameworkTemplateFileManager Instance  with the
    ''' TextTransformation (T4 generated class) that is currently running
    ''' </summary>
    Private Sub New(ByVal textTransformation As Object)
        If textTransformation Is Nothing Then
            Throw New ArgumentNullException("textTransformation")
        End If

        _textTransformation = DynamicTextTransformation.Create(textTransformation)
        _generationEnvironment = _textTransformation.GenerationEnvironment
    End Sub

    ''' <summary>
    ''' Marks the end of the last file if there was one, and starts a new
    ''' and marks this point in generation as a new file.
    ''' </summary>
    Public Sub StartNewFile(ByVal name As String)
        If name Is Nothing Then
            Throw New ArgumentNullException("name")
        End If

        CurrentBlock = New Block() With { .Name = name }
    End Sub

    Public Sub StartFooter()
        CurrentBlock = footer
    End Sub

    Public Sub StartHeader()
        CurrentBlock = header
    End Sub

    Public Sub EndBlock()
        If CurrentBlock Is Nothing Then
            Exit Sub
        End If

        CurrentBlock.Length = _generationEnvironment.Length - CurrentBlock.Start

        If CurrentBlock IsNot header AndAlso CurrentBlock IsNot footer Then
            files.Add(CurrentBlock)
        End If

        m_currentBlock = Nothing
    End Sub

    ''' <summary>
    ''' Produce the template output files.
    ''' </summary>
    Public Overridable Function Process(Optional split As Boolean = True) As IEnumerable(Of String)
        Dim generatedFileNames As List(Of String) = New List(Of String)()

        If split Then
            EndBlock()

            Dim headerText As String = _generationEnvironment.ToString(header.Start, header.Length)
            Dim footerText As String = _generationEnvironment.ToString(footer.Start, footer.Length)
            Dim outputPath As String = Path.GetDirectoryName(_textTransformation.Host.TemplateFile)

            files.Reverse()

            For Each block As Block In files
                Dim fileName As String = Path.Combine(outputPath, block.Name)
                Dim content = headerText + _generationEnvironment.ToString(block.Start, block.Length) + footerText

                generatedFileNames.Add(fileName)
                CreateFile(fileName, content)
                _generationEnvironment.Remove(block.Start, block.Length)
            Next
        End If

        Return generatedFileNames
    End Function

    Protected Overridable Sub CreateFile(ByVal fileName As String, ByVal content As String)
        If IsFileContentDifferent(fileName, content) Then
            File.WriteAllText(fileName, content)
        End If
    End Sub

    Protected Function IsFileContentDifferent(ByVal fileName As String, ByVal newContent As String) As Boolean
        Return Not (File.Exists(fileName) AndAlso File.ReadAllText(fileName) = newContent)
    End Function

    Private Property CurrentBlock() As Block
        Get
            Return m_currentBlock
        End Get
        Set(ByVal value As Block)
            If CurrentBlock IsNot Nothing Then
                EndBlock()
            End If

            If value IsNot Nothing Then
                value.Start = _generationEnvironment.Length
            End If

            m_currentBlock = value
        End Set
    End Property

    #If Not PREPROCESSED_TEMPLATE Then
    Private NotInheritable Class VsEntityFrameworkTemplateFileManager
        Inherits EntityFrameworkTemplateFileManager
        Private templateProjectItem As EnvDTE.ProjectItem
        Private dte As EnvDTE.DTE
        Private checkOutAction As Action(Of String)
        Private projectSyncAction As Action(Of IEnumerable(Of String))

        ''' <summary>
        ''' Creates an instance of the VsEntityFrameworkTemplateFileManager class with the IDynamicHost instance
        ''' </summary>
        Public Sub New(ByVal textTemplating As Object)
            MyBase.New(textTemplating)
            Dim hostServiceProvider = _textTransformation.Host.AsIServiceProvider()
            If hostServiceProvider Is Nothing Then
                Throw New ArgumentNullException("Could not obtain hostServiceProvider")
            End If

            dte = DirectCast(hostServiceProvider.GetService(GetType(EnvDTE.DTE)), EnvDTE.DTE)
            If dte Is Nothing Then
                Throw New ArgumentNullException("Could not obtain DTE from host")
            End If

            templateProjectItem = dte.Solution.FindProjectItem(_textTransformation.Host.TemplateFile)

            checkOutAction = Function(fileName) dte.SourceControl.CheckOutItem(fileName)
            projectSyncAction = Sub(keepFileNames) ProjectSync(templateProjectItem, keepFileNames)
        End Sub

        Public Overloads Overrides Function Process(Optional split As Boolean = True) As IEnumerable(Of String)
            If templateProjectItem.ProjectItems Is Nothing Then
                Return New List(Of String)
            End If

            Dim generatedFileNames As IEnumerable(Of String) = MyBase.Process(split)

            projectSyncAction.EndInvoke(projectSyncAction.BeginInvoke(generatedFileNames, Nothing, Nothing))

            Return generatedFileNames
        End Function

        Protected Overloads Overrides Sub CreateFile(ByVal fileName As String, ByVal content As String)
            If IsFileContentDifferent(fileName, content) Then
                CheckoutFileIfRequired(fileName)
                File.WriteAllText(fileName, content)
            End If
        End Sub

        Private Shared Sub ProjectSync(ByVal templateProjectItem As EnvDTE.ProjectItem, ByVal keepFileNames As IEnumerable(Of String))
            Dim keepFileNameSet = New HashSet(Of String)(keepFileNames)
            Dim projectFiles = New Dictionary(Of String, EnvDTE.ProjectItem)()
            Dim originalOutput = Path.GetFileNameWithoutExtension(templateProjectItem.FileNames(0))

            For Each projectItem As EnvDTE.ProjectItem In templateProjectItem.ProjectItems
                projectFiles.Add(projectItem.FileNames(0), projectItem)
            Next

            ' Remove unused items from the project
            For Each pair As KeyValuePair(Of String, EnvDTE.ProjectItem) In projectFiles
                If Not keepFileNames.Contains(pair.Key) _
                  AndAlso Not (Path.GetFileNameWithoutExtension(pair.Key) + ".").StartsWith(originalOutput + ".") Then
                    pair.Value.Delete()
                End If
            Next

            ' Add missing files to the project
            For Each fileName As String In keepFileNameSet
                If Not projectFiles.ContainsKey(fileName) Then
                    templateProjectItem.ProjectItems.AddFromFile(fileName)
                End If
            Next
        End Sub

        Private Sub CheckoutFileIfRequired(ByVal fileName As String)
            If dte.SourceControl Is Nothing OrElse Not dte.SourceControl.IsItemUnderSCC(fileName) OrElse dte.SourceControl.IsItemCheckedOut(fileName) Then
                Exit Sub
            End If

            ' run on worker thread to prevent T4 calling back into VS
            checkOutAction.EndInvoke(checkOutAction.BeginInvoke(fileName, Nothing, Nothing))
        End Sub
    End Class
    #End If
End Class

''' <summary>
''' Responsible creating an instance that can be passed
''' to helper classes that need to access the TextTransformation
''' members. It accesses member by name and signature rather than
''' by type. This is necessary when the
''' template is being used in Preprocessed mode
''' and there is no common known type that can be
''' passed instead
''' </summary>
Public Class DynamicTextTransformation
    Private _instance As Object
    Private _dynamicHost As IDynamicHost

    Private ReadOnly _write As MethodInfo
    Private ReadOnly _writeLine As MethodInfo
    Private ReadOnly _generationEnvironment As PropertyInfo
    Private ReadOnly _errors As PropertyInfo
    Private ReadOnly _host As PropertyInfo

    ''' <summary>
    ''' Creates an instance of the DynamicTextTransformation class around the passed in
    ''' TextTransformation shapped instance passed in, or if the passed in instance
    ''' already is a DynamicTextTransformation, it casts it and sends it back.
    ''' </summary>
    Public Shared Function Create(ByVal instance As Object) As DynamicTextTransformation
        If instance Is Nothing Then
            Throw New ArgumentNullException("instance")
        End If

        Dim textTransformation As DynamicTextTransformation = TryCast(instance, DynamicTextTransformation)
        If textTransformation IsNot Nothing Then
            Return textTransformation
        End If

        Return New DynamicTextTransformation(instance)
    End Function

    Private Sub New(ByVal instance As Object)
        _instance = instance
        Dim type As Type = _instance.GetType()
        _write = type.GetMethod("Write", New Type() {GetType(String)})
        _writeLine = type.GetMethod("WriteLine", New Type() {GetType(String)})
        _generationEnvironment = type.GetProperty("GenerationEnvironment", BindingFlags.Instance Or BindingFlags.NonPublic)
        _host = type.GetProperty("Host")
        _errors = type.GetProperty("Errors")
    End Sub

    ''' <summary>
    ''' Gets the value of the wrapped TextTranformation instance's GenerationEnvironment property
    ''' </summary>
    Public ReadOnly Property GenerationEnvironment() As StringBuilder
        Get
            Return DirectCast(_generationEnvironment.GetValue(_instance, Nothing), StringBuilder)
        End Get
    End Property

    ''' <summary>
    ''' Gets the value of the wrapped TextTranformation instance's Errors property
    ''' </summary>
    Public ReadOnly Property Errors() As System.CodeDom.Compiler.CompilerErrorCollection
        Get
            Return DirectCast(_errors.GetValue(_instance, Nothing), System.CodeDom.Compiler.CompilerErrorCollection)
        End Get
    End Property

    ''' <summary>
    ''' Calls the wrapped TextTranformation instance's Write method.
    ''' </summary>
    Public Sub Write(ByVal text As String)
        _write.Invoke(_instance, New Object() {text})
    End Sub

    ''' <summary>
    ''' Calls the wrapped TextTranformation instance's WriteLine method.
    ''' </summary>
    Public Sub WriteLine(ByVal text As String)
        _writeLine.Invoke(_instance, New Object() {text})
    End Sub

    ''' <summary>
    ''' Gets the value of the wrapped TextTranformation instance's Host property
    ''' if available (shows up when hostspecific is set to true in the template directive) and returns
    ''' the appropriate implementation of IDynamicHost
    ''' </summary>
    Public ReadOnly Property Host() As IDynamicHost
        Get
            If _dynamicHost Is Nothing Then
                If _host Is Nothing Then
                    _dynamicHost = New NullHost()
                Else
                    _dynamicHost = New DynamicHost(_host.GetValue(_instance, Nothing))
                End If
            End If
            Return _dynamicHost
        End Get
    End Property
End Class


''' <summary>
''' Reponsible for abstracting the use of Host between times
''' when it is available and not
''' </summary>
Public Interface IDynamicHost
    ''' <summary>
    ''' An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue
    ''' </summary>
    Function ResolveParameterValue(ByVal id As String, ByVal name As String, ByVal otherName As String) As String

    ''' <summary>
    ''' An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath
    ''' </summary>
    Function ResolvePath(ByVal path As String) As String

    ''' <summary>
    ''' An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile
    ''' </summary>
    ReadOnly Property TemplateFile() As String

    ''' <summary>
    ''' Returns the Host instance cast as an IServiceProvider
    ''' </summary>
    Function AsIServiceProvider() As IServiceProvider
End Interface

''' <summary>
''' Reponsible for implementing the IDynamicHost as a dynamic
''' shape wrapper over the Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost interface
''' rather than type dependent wrapper. We don't use the
''' interface type so that the code can be run in preprocessed mode
''' on a .net framework only installed machine.
''' </summary>
Public Class DynamicHost
    Implements IDynamicHost
    Private ReadOnly _instance As Object
    Private ReadOnly _resolveParameterValue As MethodInfo
    Private ReadOnly _resolvePath As MethodInfo
    Private ReadOnly _templateFile As PropertyInfo

    ''' <summary>
    ''' Creates an instance of the DynamicHost class around the passed in
    ''' Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost shapped instance passed in.
    ''' </summary>
    Public Sub New(ByVal instance As Object)
        _instance = instance
        Dim type As Type = _instance.GetType()
        _resolveParameterValue = type.GetMethod("ResolveParameterValue", New Type() {GetType(String), GetType(String), GetType(String)})
        _resolvePath = type.GetMethod("ResolvePath", New Type() {GetType(String)})

        _templateFile = type.GetProperty("TemplateFile")
    End Sub

    ''' <summary>
    ''' A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue
    ''' </summary>
    Public Function ResolveParameterValue(ByVal id As String, ByVal name As String, ByVal otherName As String) As String Implements IDynamicHost.ResolveParameterValue
        Return DirectCast(_resolveParameterValue.Invoke(_instance, New Object() {id, name, otherName}), String)
    End Function

    ''' <summary>
    ''' A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath
    ''' </summary>
    Public Function ResolvePath(ByVal path As String) As String Implements IDynamicHost.ResolvePath
        Return DirectCast(_resolvePath.Invoke(_instance, New Object() {path}), String)
    End Function

    ''' <summary>
    ''' A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile
    ''' </summary>
    Public ReadOnly Property TemplateFile() As String Implements IDynamicHost.TemplateFile
        Get
            Return DirectCast(_templateFile.GetValue(_instance, Nothing), String)
        End Get
    End Property

    ''' <summary>
    ''' Returns the Host instance cast as an IServiceProvider
    ''' </summary>
    Public Function AsIServiceProvider() As IServiceProvider Implements IDynamicHost.AsIServiceProvider
        Return TryCast(_instance, IServiceProvider)
    End Function
End Class

''' <summary>
''' Reponsible for implementing the IDynamicHost when the
''' Host property is not available on the TextTemplating type. The Host
''' property only exists when the hostspecific attribute of the template
''' directive is set to true.
''' </summary>
Public Class NullHost
    Implements IDynamicHost
    ''' <summary>
    ''' An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue
    ''' that simply retuns null.
    ''' </summary>
    Public Function ResolveParameterValue(ByVal id As String, ByVal name As String, ByVal otherName As String) As String Implements IDynamicHost.ResolveParameterValue
        Return Nothing
    End Function

    ''' <summary>
    ''' An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath
    ''' that simply retuns the path passed in.
    ''' </summary>
    Public Function ResolvePath(ByVal path As String) As String Implements IDynamicHost.ResolvePath
        Return path
    End Function

    ''' <summary>
    ''' An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile
    ''' that returns null.
    ''' </summary>
    Public ReadOnly Property TemplateFile() As String Implements IDynamicHost.TemplateFile
        Get
            Return Nothing
        End Get
    End Property

    ''' <summary>
    ''' Returns null.
    ''' </summary>
    Public Function AsIServiceProvider() As IServiceProvider Implements IDynamicHost.AsIServiceProvider
        Return Nothing
    End Function
End Class

''' <summary>
''' Responsible for encapsulating the constants defined in Metadata
''' </summary>
Public NotInheritable Class MetadataConstants
    Private Sub New()
    End Sub

    Public Const CSDL_EXTENSION As String = ".csdl"

    Public Const CSDL_EDMX_SECTION_NAME As String = "ConceptualModels"
    Public Const CSDL_ROOT_ELEMENT_NAME As String = "Schema"
    Public Const EDM_ANNOTATION_09_02 As String = "http://schemas.microsoft.com/ado/2009/02/edm/annotation"

    Public Const SSDL_EXTENSION As String = ".ssdl"

    Public Const SSDL_EDMX_SECTION_NAME As String = "StorageModels"
    Public Const SSDL_ROOT_ELEMENT_NAME As String = "Schema"

    Public Const MSL_EXTENSION As String = ".msl"

    Public Const MSL_EDMX_SECTION_NAME As String = "Mappings"
    Public Const MSL_ROOT_ELEMENT_NAME As String = "Mapping"

    Public Const TT_TEMPLATE_NAME As String = "TemplateName"
    Public Const TT_TEMPLATE_VERSION As String = "TemplateVersion"
    Public Const TT_MINIMUM_ENTITY_FRAMEWORK_VERSION As String = "MinimumEntityFrameworkVersion"

    Public Const DEFAULT_TEMPLATE_VERSION As String = "4.0"

    Public Shared ReadOnly V1_SCHEMA_CONSTANTS As New SchemaConstants(
        "http://schemas.microsoft.com/ado/2007/06/edmx",
        "http://schemas.microsoft.com/ado/2006/04/edm",
        "http://schemas.microsoft.com/ado/2006/04/edm/ssdl",
        "urn:schemas-microsoft-com:windows:storage:mapping:CS",
        New Version("3.5"))

    Public Shared ReadOnly V2_SCHEMA_CONSTANTS As New SchemaConstants(
        "http://schemas.microsoft.com/ado/2008/10/edmx",
        "http://schemas.microsoft.com/ado/2008/09/edm",
        "http://schemas.microsoft.com/ado/2009/02/edm/ssdl",
        "http://schemas.microsoft.com/ado/2008/09/mapping/cs",
        New Version("4.0"))

    Public Shared ReadOnly V3_SCHEMA_CONSTANTS As New SchemaConstants(
        "http://schemas.microsoft.com/ado/2009/11/edmx",
        "http://schemas.microsoft.com/ado/2009/11/edm",
        "http://schemas.microsoft.com/ado/2009/11/edm/ssdl",
        "http://schemas.microsoft.com/ado/2009/11/mapping/cs",
        New Version("5.0"))
End Class

Public Structure SchemaConstants
    Public Sub New(ByVal edmxNamespace As String, ByVal csdlNamespace As String, ByVal ssdlNamespace As String, ByVal mslNamespace As String, ByVal minimumTemplateVersion As Version)
        Me.EdmxNamespace = edmxNamespace
        Me.CsdlNamespace = csdlNamespace
        Me.SsdlNamespace = ssdlNamespace
        Me.MslNamespace = mslNamespace
        Me.MinimumTemplateVersion = minimumTemplateVersion
    End Sub

    Public Property EdmxNamespace() As String
        Get
            Return m_EdmxNamespace
        End Get
        Private Set
            m_EdmxNamespace = Value
        End Set
    End Property
    Private m_EdmxNamespace As String

    Public Property CsdlNamespace() As String
        Get
            Return m_CsdlNamespace
        End Get
        Private Set
            m_CsdlNamespace = Value
        End Set
    End Property
    Private m_CsdlNamespace As String

    Public Property SsdlNamespace() As String
        Get
            Return m_SsdlNamespace
        End Get
        Private Set
            m_SsdlNamespace = Value
        End Set
    End Property
    Private m_SsdlNamespace As String

    Public Property MslNamespace() As String
        Get
            Return m_MslNamespace
        End Get
        Private Set
            m_MslNamespace = Value
        End Set
    End Property
    Private m_MslNamespace As String

    Public Property MinimumTemplateVersion() As Version
        Get
            Return m_MinimumTemplateVersion
        End Get
        Private Set
            m_MinimumTemplateVersion = Value
        End Set
    End Property
    Private m_MinimumTemplateVersion As Version
End Structure

    End Class
    #Region "Base class"
    '''<summary>
    '''Base class for this transformation
    '''</summary>
    <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "11.0.0.0")>  _
    Public Class VBCodeGenTemplateV50Base
        #Region "Fields"
        Private generationEnvironmentField As Global.System.Text.StringBuilder
        Private errorsField As Global.System.CodeDom.Compiler.CompilerErrorCollection
        Private indentLengthsField As Global.System.Collections.Generic.List(Of Integer)
        Private currentIndentField As String = ""
        Private endsWithNewline As Boolean
        Private sessionField As Global.System.Collections.Generic.IDictionary(Of String, Object)
        #End Region
        #Region "Properties"
        '''<summary>
        '''The string builder that generation-time code is using to assemble generated output
        '''</summary>
        Protected Property GenerationEnvironment() As System.Text.StringBuilder
            Get
                If (Me.generationEnvironmentField Is Nothing) Then
                    Me.generationEnvironmentField = New Global.System.Text.StringBuilder()
                End If
                Return Me.generationEnvironmentField
            End Get
            Set
                Me.generationEnvironmentField = value
            End Set
        End Property
        '''<summary>
        '''The error collection for the generation process
        '''</summary>
        Public ReadOnly Property Errors() As System.CodeDom.Compiler.CompilerErrorCollection
            Get
                If (Me.errorsField Is Nothing) Then
                    Me.errorsField = New Global.System.CodeDom.Compiler.CompilerErrorCollection()
                End If
                Return Me.errorsField
            End Get
        End Property
        '''<summary>
        '''A list of the lengths of each indent that was added with PushIndent
        '''</summary>
        Private ReadOnly Property indentLengths() As System.Collections.Generic.List(Of Integer)
            Get
                If (Me.indentLengthsField Is Nothing) Then
                    Me.indentLengthsField = New Global.System.Collections.Generic.List(Of Integer)()
                End If
                Return Me.indentLengthsField
            End Get
        End Property
        '''<summary>
        '''Gets the current indent we use when adding lines to the output
        '''</summary>
        Public ReadOnly Property CurrentIndent() As String
            Get
                Return Me.currentIndentField
            End Get
        End Property
        '''<summary>
        '''Current transformation session
        '''</summary>
        Public Overridable Property Session() As Global.System.Collections.Generic.IDictionary(Of String, Object)
            Get
                Return Me.sessionField
            End Get
            Set
                Me.sessionField = value
            End Set
        End Property
        #End Region
        #Region "Transform-time helpers"
        '''<summary>
        '''Write text directly into the generated output
        '''</summary>
        Public Overloads Sub Write(ByVal textToAppend As String)
            If String.IsNullOrEmpty(textToAppend) Then
                Return
            End If
            'If we're starting off, or if the previous text ended with a newline,
            'we have to append the current indent first.
            If ((Me.GenerationEnvironment.Length = 0)  _
                        OrElse Me.endsWithNewline) Then
                Me.GenerationEnvironment.Append(Me.currentIndentField)
                Me.endsWithNewline = false
            End If
            'Check if the current text ends with a newline
            If textToAppend.EndsWith(Global.System.Environment.NewLine, Global.System.StringComparison.CurrentCulture) Then
                Me.endsWithNewline = true
            End If
            'This is an optimization. If the current indent is "", then we don't have to do any
            'of the more complex stuff further down.
            If (Me.currentIndentField.Length = 0) Then
                Me.GenerationEnvironment.Append(textToAppend)
                Return
            End If
            'Everywhere there is a newline in the text, add an indent after it
            textToAppend = textToAppend.Replace(Global.System.Environment.NewLine, (Global.System.Environment.NewLine + Me.currentIndentField))
            'If the text ends with a newline, then we should strip off the indent added at the very end
            'because the appropriate indent will be added when the next time Write() is called
            If Me.endsWithNewline Then
                Me.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - Me.currentIndentField.Length))
            Else
                Me.GenerationEnvironment.Append(textToAppend)
            End If
        End Sub
        '''<summary>
        '''Write text directly into the generated output
        '''</summary>
        Public Overloads Sub WriteLine(ByVal textToAppend As String)
            Me.Write(textToAppend)
            Me.GenerationEnvironment.AppendLine
            Me.endsWithNewline = true
        End Sub
        '''<summary>
        '''Write formatted text directly into the generated output
        '''</summary>
        Public Overloads Sub Write(ByVal format As String, <System.ParamArrayAttribute()> ByVal args() As Object)
            Me.Write(String.Format(Global.System.Globalization.CultureInfo.CurrentCulture, format, args))
        End Sub
        '''<summary>
        '''Write formatted text directly into the generated output
        '''</summary>
        Public Overloads Sub WriteLine(ByVal format As String, <System.ParamArrayAttribute()> ByVal args() As Object)
            Me.WriteLine(String.Format(Global.System.Globalization.CultureInfo.CurrentCulture, format, args))
        End Sub
        '''<summary>
        '''Raise an error
        '''</summary>
        Public Sub [Error](ByVal message As String)
            Dim [error] As System.CodeDom.Compiler.CompilerError = New Global.System.CodeDom.Compiler.CompilerError()
            [error].ErrorText = message
            Me.Errors.Add([error])
        End Sub
        '''<summary>
        '''Raise a warning
        '''</summary>
        Public Sub Warning(ByVal message As String)
            Dim [error] As System.CodeDom.Compiler.CompilerError = New Global.System.CodeDom.Compiler.CompilerError()
            [error].ErrorText = message
            [error].IsWarning = true
            Me.Errors.Add([error])
        End Sub
        '''<summary>
        '''Increase the indent
        '''</summary>
        Public Sub PushIndent(ByVal indent As String)
            If (indent = Nothing) Then
                Throw New Global.System.ArgumentNullException("indent")
            End If
            Me.currentIndentField = (Me.currentIndentField + indent)
            Me.indentLengths.Add(indent.Length)
        End Sub
        '''<summary>
        '''Remove the last indent that was added with PushIndent
        '''</summary>
        Public Function PopIndent() As String
            Dim returnValue As String = ""
            If (Me.indentLengths.Count > 0) Then
                Dim indentLength As Integer = Me.indentLengths((Me.indentLengths.Count - 1))
                Me.indentLengths.RemoveAt((Me.indentLengths.Count - 1))
                If (indentLength > 0) Then
                    returnValue = Me.currentIndentField.Substring((Me.currentIndentField.Length - indentLength))
                    Me.currentIndentField = Me.currentIndentField.Remove((Me.currentIndentField.Length - indentLength))
                End If
            End If
            Return returnValue
        End Function
        '''<summary>
        '''Remove any indentation
        '''</summary>
        Public Sub ClearIndent()
            Me.indentLengths.Clear
            Me.currentIndentField = ""
        End Sub
        #End Region
        #Region "ToString Helpers"
        '''<summary>
        '''Utility class to produce culture-oriented representation of an object as a string.
        '''</summary>
        Public Class ToStringInstanceHelper
            Private formatProviderField  As System.IFormatProvider = Global.System.Globalization.CultureInfo.InvariantCulture
            '''<summary>
            '''Gets or sets format provider to be used by ToStringWithCulture method.
            '''</summary>
            Public Property FormatProvider() As System.IFormatProvider
                Get
                    Return Me.formatProviderField 
                End Get
                Set
                    If (Not (value) Is Nothing) Then
                        Me.formatProviderField  = value
                    End If
                End Set
            End Property
            '''<summary>
            '''This is called from the compile/run appdomain to convert objects within an expression block to a string
            '''</summary>
            Public Function ToStringWithCulture(ByVal objectToConvert As Object) As String
                If (objectToConvert Is Nothing) Then
                    Throw New Global.System.ArgumentNullException("objectToConvert")
                End If
                Dim t As System.Type = objectToConvert.GetType
                Dim method As System.Reflection.MethodInfo = t.GetMethod("ToString", New System.Type() {GetType(System.IFormatProvider)})
                If (method Is Nothing) Then
                    Return objectToConvert.ToString
                Else
                    Return CType(method.Invoke(objectToConvert, New Object() {Me.formatProviderField }),String)
                End If
            End Function
        End Class
        Private toStringHelperField As ToStringInstanceHelper = New ToStringInstanceHelper()
        '''<summary>
        '''Helper to produce culture-oriented representation of an object as a string
        '''</summary>
        Public ReadOnly Property ToStringHelper() As ToStringInstanceHelper
            Get
                Return Me.toStringHelperField
            End Get
        End Property
        #End Region
    End Class
    #End Region
End Namespace
�6��b#�1�o=�����Y��I:���,N�%\� �㨎l�C��7�����q/����l8��kn�D�1��K6ц�Q+�*���lXB)ן1d�-{4|���*��Υ���M�X�q�������O�%���D���*�s$
�[�-o�JZ{�3�L|�<��]�+*�
Y=��|�H{*���j/
n}���Þ~y
��E��΅�!iIe����j����5أ�v���_K�|l��]�n�.�^^6ll�RSDS�z���H��r���:System.Data.Entity.Design.pdb�� �_CorDllMainmscoree.dll�% �`="'�� �8���P�h���� �F��g$�IBCPROFILE_DATA(�б�N��(0K�'Q�Z`,�c[
eF���7	�
�	��#�&�+�,0n2~ (3� ��1^�
" ((	u &*&6\&`@f

���%�H

	0	<	�+�{GXi��	%(JNt����������B#<m��������������������������������������������������������������������������������f��$8�� �0�9F�OQ_lq����������J���)-�6�8�F�H�Q���+�7�@�B�P�-��
�$�=�?�U�l�u�w������.��%'=FHVdl�������K�,���
�^�`���	������
�������C��[�nZ���T��#����?�g�i����������@�1���.�>�?�@�g�i������������� ����.�;L����(�(������F��������7��x��H���.�!7�9�G�	�>�,��T���#<DNep�P�"�������$�"3�"N�"	�;��	�L#K.��57QS�f�����������	�1�
��*
�O-9M�%#���Mbs�
�g)2;O�$�$�C	&	/9�$
�)"
�,
 &
�,
 &
�,
 &�X�O� Z��$2��T�U�������H�I������������������i�q#:W$��)=���������"�'&�5	%'*01�oHH�N�WHYHgH�|T.T'�~"�
2�;�J�L�
X�
`hqsv|}N���4������
��
��
��
��
��
��
��
�������������	��
�
$��$&HCHKGYH[HbIkmqxy��;��HH 1HiH�H�H�4��H�4�H�4��4��H�H�H�H�vH�[|

rrr:'>�GKIrWKY'�TH	H	H'H/7|@4BHP4R�5���H=H�H�H���H�&�&.���?TGR_Tb�qQ}��������L��T%T,T<b�T�T�T�T�T�T�T�T�����T�T�T�T�T�T�F��T�T���
T,T�-����������������������;�;�;�	��	��	��	��
��
��
��
��
��
��
��������7�������
��
T�
T�
T�
T�
T�t	�_*_8_J�N�W`j��
+-Zw����.��*HPaelm����������:<�h�qs��-��IE+��#�{AGnqwx	�'#��2Ec��������	�9
.��!'(*-34���
�D		�*�3	5	C		���	����)��(��
��
���@�c||,|5|P|_9aC� ����
�:�$&|A|R|e|nCv9�9��9�9��9�9��9�9��9�9��9�9��9�9��9�9�9�9��9�9��9�9�9��9�9�	9�	�	9�	9�
�
9�
9�
�7�7��7�7�7�7�
7� �����@"�+-�Z�w����������������������������������������������������������	�	��	��	��
�
��
������������
�
��
��������������������b�Q���O4���,�
��(8*��_� �4�H�]��)�	��%8'��5�'�'	��#�#!��.?OQXt~���	�B$	�B$	�J$�w"5�J�RadjkntuA��CUqs������������	�������;COY{
����[�
�N�E�
�
(�
<C�
��T�

�
�
$1@�
J��
��<�9������H��H	�>�<�	�>�<��>H<H�>H<H�>H<H�������;�������������>T<T	�>�<�	�>�<�	�>�<�	�>�<�	�>�<�	�>�<�	�>�<��:�	�������5��?APY[_fgtv�������������z���!�-�:�G�Q�����?n~�������������������
��
����������|�
O�
p�
.���2�4�C�L�N�\�h�j�y��������J��v�&�a�j�
���wh���3h
�.��f".X���J�g�w�����������������
���������������������k�)+@IKYj�������V�h7��^����"�'57>�'F�'H�`e�'j�`s�'u�'y�'��'��'����
��
�����������3�������8�'�'
��!��!�4�6��v�'��,�>�Q�c�t7�*��/�+�(�����	�!���,���*�)��
W���������G��.@v��������������������������N�P�_�h�j�x��M�#���^�f�����F������$�u�
�.�0pHp`�h�j�m�s�t��z�%�/�
8�F�I�
M�Z�x��
�p	�Ap
p p�(��&��N�!L��TV�y�������������������������q���������:����(�*�8���8:jsu�
�X$(7H�2��7����3�5�P�k�
t�v����:��"�O�
��3D�	�3
�`�$3�$A�$^�$�	��K
��%	�a���X�%�8�C�V��S�
*8@BEKL��R�3DQ�!�i�	�� �#�+�@�C�K�`��U�
�%'�=�Q�S�
�F�
�� �.�6�D��y
#0<IQ^jw�	��	�	nl	�	I�	
�
�	�
�	�	�
�	�
�	��	��	��	��	��	��	��	�
�	�
�	�
�	�
�	�
�	�
�	�
��
j�
'�
ML
�
R+58E�
L�	�($&02<>J�
%�
?***&".+-*;=&�
2�
<$$$"H+$-$;$	�
Q('O
�
=(���)� ��}'?<��y^&F�$!�{�q��0S�& A)S��у������C�Ӄ�����ԃ�����	S�C
" ���������"�����	�������cu"�e
" ʚ������������������������������������ŀ�������䀀�����������"?͜���"�������� ������������������������������������� Yx��������������Ɲ���Ā�Ν��������������������������� q����������B�������6��������9 3S"�	!.C"�i- C������ � � � � �!�!�!���!C��������������������"�"�"�"�#��#�#�#�#�"�#�#�"�#�"�"�"�#�"�"�"�"�"�"����$"x$�	%�	$�$�$�&�&�&�$�%�&�$�"���0"�"�"�#�"�#�"�#�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�'�'����$���0"�"�#�"�"�"�"�#�#�#�"�"�"�"�"�"�#�"�"�"�"�"�"�"�"�"�#�"�"�"�"�"�"�"�(��"�"�#�(�#�#�#�"�"�"�"�"�"�"����$愀0#�"�"܌��$�$ń�0"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"�"����$���0)�*�+���+�,��-��.���-�-�)�)�,
*-�-�)�)�)�)�-�-�)�)�)�*�)�	)�)�	*�)�)�,�+�,�)�,�)�)�+�/�+�+�,�+�)�)�/�0��1�1��1��1�1�1�1�������02��3��4��4�1�1�1�1�4�5���1�1�1�1�0�1�1�1�1�1�1�1�1	11���	�	1�	1�	1�	ن�01�1�4�1�1�1�1�1�1�1���1�1����1�01�1�1�1�1�1�1�1�1�1�1�1�1�����1����0�����1�01�1�1�����1��1ↀ01�1�����1�1�1т�01�1�����������������01�1�1�1���������01�1�1�1�1�1�0�1��4�1�
1�1�1�0�1�
1�
1�
1�
1�
1�
1�
1�1�1�1�1�1�4�4�1�1�1�1�5�5�1�4�1�1�
1�
1�
1�1�0�1�1�1�1�1�1�1�1�1�1�1�1�1��	����퉀0�	�	1�
�	�	�������0�	�	�	�1�	�	�	��	�	�	�	�1�1�1�1�1�1�1�1��1�1�1�1�1�1�1�1�1�1�1�
�1�1�1�1�1�1�1�1�����1�ޅ�04��1����兀0�1��1�1���1�1����څ�01��1�1�0�5�1�4�1�5�0���1�	�	1�	4�5�	4��		-6�6*6c�.�.���.����֋�������������� �G�(�����G�����a��������������,٠�����������L�.�0����=�X��݋���ؽ��-�����������-��.�P���M�����M�����������U��߀�������3������������Ρ�~��������ƍǏ�X�X�M��������� H�x�d�g�j�b�e�h�c�f�i�l�x�
���15�k������������������yq�y������{�{������������������������������������������{�z��"�z�y�z�z�������������������������{�l�k�o�o�o�p�A�m�p�p�o�m����������������������������������ύ�����z�������y���n�����������������A����������������������������������������������������������������������������������������k�����v��������������������ÂՂ����������Ƀۃ������������ӄ�������������Յ�����������Æφ��������������ɇч������������������ˉՉ��������������ϊߊ����������ŋ׋������������������������ˌь׌݌������������ˍٍ�����������������ǎюߎ��������������ɏۏ����������Őϐِ�������������Ñב������������ǒӒ�������������ѓݓ�����������ǔה����������ŕӕ��������������Ö͖ז��������������͗ݗ���������������Ϙߘ����������Ǚә�����������ÚϚۚ�����������śϛߛ�����������ÜϜݜ���������������ӝ�������������͞ݞ�����������͟���������àӠ�����������ۡ�����������ɢݢ���������ӣ���������������Ѥ����������ͥݥ��������٦���������ç٧����������Ǩ٨��������������ǩש������������Ϫ۪�����������ëѫ����������ŬѬ������������ɭݭ���������Ů׮�����������ůׯ�����������ŰѰ������������ͱݱ���������ŲӲ������������ɳ۳�����������Ǵ״�������������ѵߵ���������ɶٶ�������������շ�����������ɸո������������ǹݹ���������úӺ�����������˻ۻ�����������ϼ�����������ͽ߽���������ž׾�����������ɿٿ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������n���������Z�Z�Z�\�Z�[�W�{�|Á�����������w�w�x�v"����System.Collections.GenericSystem.Data.CommonSystem.Threading
SystemSystem.LinqSystem.Data.Metadata.EdmSystem.Data.Common.UtilsSystem.XmlSystem.Data.Mapping����ICollection`1
$List`1%DbProviderFactory2InterlockedjIEnumerable`1kIEnumerator`1l$EnumeratormIList`1nEqualityComparer`1o
IEquatable`1pObjectEqualityComparer`1qIEqualityComparer`1rEnumerables
Dictionary`2tEntityTypeuIDictionary`2vKeyValuePair`2wIReadOnlyDictionary`2xIReadOnlyCollection`1yRowTypez
HashSet`1{	Action`5|EdmSchemaError~IReadOnlyList`1
Func`2
�sEntry�zSlot�sValueCollection��Enumerator�EntityContainer�
EntitySet
�Set`1�EmptyEnumerable`1�ISet`1�SZArrayHelper#��SZGenericArrayEnumerator`1�zEnumerator�
XmlWriter�StoreItemCollection�
XmlReader�EdmItemCollection�$SynchronizedList$�StorageMappingItemCollection����G��AH I �@J	�H
K
 ��L MAA��NAO P Q R 
S T �@U �,V	 ��W X Y 
Z [	A
\
0��	����2CompareExchange	prGToList
	qlHDispose	rsI.ctor	snJget_Default	tnJCreateComparer	uzH.ctor	vzK.ctor	wzLAddIfNotPresent	xrMWhere	yrNSingle	zsOInsert	{sPInitialize	|pQGetHashCode	}sHResize	~sRResize	zQInternalGetHashCode	�zHIncreaseCapacity	�zRSetCapacity	�zPInitialize
	�sSAdd	�sTget_Values
	��U.ctorD	��V=System.Collections.Generic.IEnumerable<TValue>.GetEnumerator
	��U.ctor	��W	MoveNext	��Xget_Current	�sYTryGetValue	�sQ
FindEntry	��HDispose
	�pZEquals	�r[Empty	��\GetEnumeratorу��
?�����?�����
?��������
?�����
?�����
?�����
?�����
?�����
?�����
?�����
?��������?����>�?����?���?����>�?����?���?��?����>�?��?����?���?��?����>�?��?����?���?����>�?����?���?��?����>�?��?����?���?����>�?����?���?��>���?��?�����?��>���?��?�����?��?��>���?��?��?�����?��?��>���?��?��?�����?��>���?��?�����?��?��>���?��?��?�����?��>���?��?�����?����?���?����?���?��?����?���?��?����?���?����?���?��?����?���?����?���
?�����
?�����
?�����
?�����?��>>>��>/�+?����?���?����?��?���
?����
?����
?������
?����
?����
?����?����
?����
?����?���>�?���?���<?���?���?���?���
?�����?�>���?�?�����<?�?�����?�?�����?����
?����<?����?���>�?���?���?���>�?���?���
?�����
?�����
?�����
?�����
?�����
?��������?�����
?�����
?�����?��?����?��?����?��?��?����?��?��?����?��?����?��?��?����?��?����
?��������?�?����<?�?����?�?����
?����
?�����?�?����
?�����
?����
?�����
?�����
?�����
?�����
?�����
?� ���
?�����
?����<?����?����
?�(���?�?����
?�,���
?�����
?����������������>>� 
?����� 
?����� 
?����� 
?����� 
?����� ?��?��>���!
?�H���!
?�����!
?�����������>
���?��x	?��!�	
?��p���	?����q�	
?����>r�	?����s�	?����t�	
?��>��r�	?����u�	?����v�?����w�
?��x��
?��y��
?����>z�
?����>{�?����|�
?��>��z�
?��>��{�
?����>}�
?����>~�
?��>��}�
?��>��~�?�����
?�������
?�������
?�������?����>���?��>�����?����>���?���>���?���>���?���>���?���>���?���>���?���>���?���>���?��>�����?��>�����?���>���?���>���?����>���?����>���
?����������?��?�������?�$��������?�0����>������������?�4�
��>>���
��>>���
��>>���
��>>���
��>>������?�8����?��?�8����?�D�
���?�P
���������o5�PAD$4VS_VERSION_INFO��AA?DVarFileInfo$Translation��StringFileInfo`000004b0TCommentsSystem.Data.Entity.Design.dllLCompanyNameMicrosoft CorporationdFileDescriptionSystem.Data.Entity.Design.dll6FileVersion4.8.4161.0\InternalNameSystem.Data.Entity.Design.dll�/LegalCopyright� Microsoft Corporation.  All rights reserved.dOriginalFilenameSystem.Data.Entity.Design.dllTProductNameMicrosoft� .NET Framework:ProductVersion4.8.4161.08Assembly Version4.0.0.0PADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDING�5 A0�A	*�H��
��A0�@�10	+0L
+�7�>0<0
+�70	���0!0	+5E�{G���v)4��qL�
E���r0��0�Ơ31�ᾧ�
5�10
	*�H��
0w10	UUS10U
Washington10URedmond10U
Microsoft Corporation1!0UMicrosoft Time-Stamp PCA0
190906204006Z
201204204006Z0��10	UUS10U
Washington10URedmond10U
Microsoft Corporation1)0'U Microsoft Operations Puerto Rico1&0$UThales TSS ESN:148C-C4B9-20661%0#UMicrosoft Time-Stamp Service0�"0
	*�H��
�0�
�����^6<���*�<�qB@i��$��:{J{5!�3w�OX�KF��_U�x�H��O�K�T�Y@�CC�-����x��?'�A�c���2&�l�RՓg>ՐnF/eX�
wL�l�7��
����"Rfuz����Q�� ��Cy�n�hÕ{vK���n_�<�����̵�mG�@\&��9;|�j�;���ҭ%��uhb�>	'/A��chc!RQ�'uZh��U�w�
���0�NIK�]���{OZi��	0�0U-s�O�xއ�~��ʮ��0U#0�#4��RFp
�@�v��+��5�0TUM0K0I�G�E�Chttp://crl.microsoft.com/pki/crl/products/MicrosoftTimeStampPCA.crl0X+L0J0H+0�<http://www.microsoft.com/pki/certs/MicrosoftTimeStampPCA.crt0U%0
+0
	*�H��
�lE��������<]5ғ}�]l���`k^��j��
S������ׇE�:G�2�<��C%��
G|ı�9
��I���|5-� ��?�o�D�Yꍷ����&,�h������~�c#'��.5��& jj�ۘ#��G��u��)۹HP \Iq�}�����\'7T��F�M
�h���`h�&<�i
�9$7�֙PO�H��1�Eu�~$}݉��� `�Hr@PA�
na���F��~��u0��)�40�0��3R�@�PV�u�R0
	*�H��
0~10	UUS10U
Washington10URedmond10U
Microsoft Corporation1(0&UMicrosoft Code Signing PCA 20110
190502213746Z
200502213746Z0t10	UUS10U
Washington10URedmond10U
Microsoft Corporation10UMicrosoft Corporation0�"0
	*�H��
�0�
���������t�����ǔߖ�6�+�xL���5���oK��w�U��buAN��[�V7V�p�Cn�3(A6��~��/�k����>��\�6��ɳ����mJ�
�X�%y�D�����*��Or�}Y�Gڗ}tP����M�4dc�睘�*�!�U��}�W����P��e���.����lA ��+4�Ih��z%�x�tr�
����������c� �����i��Zai^���76q�3ހ����0�~0U%0
+�7L+0U��[�e�'f��5kE�0TUM0K�I0G1-0+U$Microsoft Ireland Operations Limited10U
230012+4541360U#0�Hnd�Pӂ�77"�m��u�0TUM0K0I�G�E�Chttp://www.microsoft.com/pkiops/crl/MicCodSigPCA2011_2011-07-08.crl0a+U0S0Q+0�Ehttp://www.microsoft.com/pkiops/certs/MicCodSigPCA2011_2011-07-08.crt0U�00
	*�H��
���D懾��,V�(�-����6@��m�z� 65�W��Q`[�F�y8��t�ھ$�&��C��=�d�R�m���(ߜ����S�]��!��h2]g����"���S��E��v���5@��7�8��t�=0|3e�?�O��%�vS�Y�������ޭ��b�����+O�yDT
�ͅC�8xQ#�+7&�T��",ۮ8��P���h�(�T@�`���T�l������T����G6~�ܷ�f��D�k�IB���	��m������r����aݽ��G>ƚ읶��2>�Ҁ\�����]��r!���K��Q!��(�V�&sLDt�>��QZ�M����W5X��)l�}F�G�M3�s4��O��8v�vT���:�e:����*Ɲ�N�
���hP���z?别2��fwǴ��#cU�b���ӧx�\Ȇ޽�e,��Ul*!����43=+�
�m����
 ��ސ��n���Iy/钒>
�0�0��
ah40
	*�H��
0_10
	�&���,dcom10
	�&���,d	microsoft1-0+U$Microsoft Root Certificate Authority0
070403125309Z
210403130309Z0w10	UUS10U
Washington10URedmond10U
Microsoft Corporation1!0UMicrosoft Time-Stamp PCA0�"0
	*�H��
�0�
���l���H�*|k.���řQ#P���N$�ѧ�L�t0 ��T�I�B���\0&�k�{�������3$����g,�{���N���#Sʍ�E�	�^�аB���l�g�(�FS����(F.'��OUR�,�j��0n��Y0��~֗��!�~����SmR�E��HJGf')f�����J����G	����Ux��P�0F��#F��-T��xA1w̛�;���a�
������"KT���� ���0��0U�0�0U#4��RFp
�@�v��+��5�0U�0	+�70��U#��0�����`@V'��%�*�
S�Y䤡c�a0_10
	�&���,dcom10
	�&���,d	microsoft1-0+U$Microsoft Root Certificate Authority�y��J���LsX�.e0PUI0G0E�C�A�?http://crl.microsoft.com/pki/crl/products/microsoftrootcert.crl0T+H0F0D+0�8http://www.microsoft.com/pki/certs/MicrosoftRootCert.crt0U%0
+0
	*�H��
����\D6�鴭w��yQM�.tq[m�ξ{��.���mb�W�N P��z@�W��X�����x���;�⾏
ȍH��S�O����jՀ���/��*$"p����x�.
��p�N��k
r���9�g-�Q�b\?�� ?�2��1Jv1=+r��p=��
��
a��׸�N��5+^���}B{�Sr!�0ʻxe\[
����<�fX�-/���QV�p�l�9L�y��zb))4wb�=m���,��C���}�㤨t5�N�q#&v<R�qZFC����MgȟB��y!��0f�B^Ȟ"!�C�+��H�,��2�L&*H$_Z�V�ޙ��:o��'t�v!����'T��j=��va�n����G�o��2l���QȌ#�f���d=-�Y���!嵰�c�xT�A.P����x����uْ�u"/2�n�[�%����!��Oɚ�I�eo�}�i��n꧗�1)��[\�M��/�?.Uk���0�z0�b�
a��0
	*�H��
0��10	UUS10U
Washington10URedmond10U
Microsoft Corporation1200U)Microsoft Root Certificate Authority 20110
110708205909Z
260708210909Z0~10	UUS10U
Washington10URedmond10U
Microsoft Corporation1(0&UMicrosoft Code Signing PCA 20110�"0
	*�H��
�0�
���r.��n��M4��X!�B*k�ZP��8I���7k���8™��9�1BӉ
yd�~�`$l��I��h^�ߛS�
,ï٩+�z	�זY�`�fv�2R&/�PϳD�]��.u�h��m�:\��F��8d�nd5x��c-�@����
�\y�I)�
��w��=��+ZMV(�zr�:�I^���C���{�{��>��]�O��/Y�;-�3Xŷ>�2ӳ=����8~ҝ�,�NV�!5%�9ndS���#������_��R������!t%_(��'(8%�9J6�|���#��f�aj�(I�_��%]�!K>RĵW?$��z[/�#�p]QFw��Ἤ�_����UK�9��#I��D|E��rz�r�$߿F����Wۃ��MI0�����[���ݰf��{���K�I)�(��}g��bx_�/��W�\�w((��m�(�,�@7O��D��	L�ԥC/t��n�x X,]`��>O3�ڰ�ޞN�F�l���ֈ����0��0	+�70UHnd�Pӂ�77"�m��u�0	+�7
SubCA0U�0U�0�0U#0�r-:1�C�N���1�#�40ZUS0Q0O�M�K�Ihttp://crl.microsoft.com/pki/crl/products/MicRooCerAut2011_2011_03_22.crl0^+R0P0N+0�Bhttp://www.microsoft.com/pki/certs/MicRooCerAut2011_2011_03_22.crt0��U ��0��0��	+�7.0��0?+3http://www.microsoft.com/pkiops/docs/primarycps.htm0@+042 Legal_policy_statement. 0
	*�H��
�g򆥘�Ty.��tg"���c��B�}�y��e_.,>��r�m���?�
�;�G���i�c�"5��]e��}�FPU��|�K�<B�Rа�k�>.)��=�Եw�9��d�D=xz#�}��t����&F*Š�����h�h.��*?*kXIc	inZ�����F+�;н5�n%��'������(��M=����2���-�[��I9
�
�ƭ�����QEX82q'��'��,: i��Y�hno��t�@�*(>�?Mf��M��o}E�v�@*e��]Rb��c6��������'�ͥ���]cA�[��>w��u�aa������A�(��e/��\��֡F�Y�	KH���)ű��?Ew5�Ң��zz"�H���G#�����k�K���ux��7�yK�ֳ#hu������i;��0�L���umc�=ѝVNO��W"�x2!z�A
�?��̤]����WqVNHE�Bɛv[
�Hk�y���mmj�Rs
zP�1�(&0�("0��0~10	UUS10U
Washington10URedmond10U
Microsoft Corporation1(0&UMicrosoft Code Signing PCA 20113R�@�PV�u�R0	+���0	*�H��
	1
+�70
+�710
+�70#	*�H��
	1�
;6�dP@uZ�%]+F��'�0B
+�71402��Microsoft��http://www.microsoft.com0
	*�H��
�k�:����JQ>�8�ZPX��������-U���w�ɫ|^�o*��y`��B��ȏCp��7�=�/��U^�u
��:��I:w;�a"��AB{̍T}7�u7]��
��t��ȧA�����zm�x�o�p�Kǰ���;|�[n	��X5�P,�$k%�;���/����A�ڸ�A3:vl��|�z�bKLFb[�)��WC��lrOdߗ���<��f53ݟ_���>�eВ�k��%�0�$	*�H��
	1�0�0��0w10	UUS10U
Washington10URedmond10U
Microsoft Corporation1!0UMicrosoft Time-Stamp PCA31�ᾧ�
5�10	+�]0	*�H��
	1	*�H��
0	*�H��
	1
200303190840Z0#	*�H��
	1���N��\�1�VZ3h� 0
	*�H��
��4�Y�WV��9̵wlL��+������B󀷂�I��0��¤������=|�.��ˈ�aFl�!�KO�^*�����'N��˴fQn��<=>������G��l�]�%�Hŗ]���-!Jt��s�,�p�8�=��/=	�G���}���mO�:F08�P�
��,5%�0.Bu��>\��i~����j�UD��*�T���D�JKf����?���&�v˪��]
�
��Lc��O��
�q�P}�,q10�#�
+�71�#�0�#�	*�H��
��#q0�#m10
	`�He0\
+�7�N0L0
+�70	���010
	`�He � �d�^L5�İaߴ���E��SN
xH��
�0�0��3R�@�PV�u�R0
	*�H��
0~10	UUS10U
Washington10URedmond10U
Microsoft Corporation1(0&UMicrosoft Code Signing PCA 20110
190502213746Z
200502213746Z0t10	UUS10U
Washington10URedmond10U
Microsoft Corporation10UMicrosoft Corporation0�"0
	*�H��
�0�
���������t�����ǔߖ�6�+�xL���5���oK��w�U��buAN��[�V7V�p�Cn�3(A6��~��/�k����>��\�6��ɳ����mJ�
�X�%y�D�����*��Or�}Y�Gڗ}tP����M�4dc�睘�*�!�U��}�W����P��e���.����lA ��+4�Ih��z%�x�tr�
����������c� �����i��Zai^���76q�3ހ����0�~0U%0
+�7L+0U��[�e�'f��5kE�0TUM0K�I0G1-0+U$Microsoft Ireland Operations Limited10U
230012+4541360U#0�Hnd�Pӂ�77"�m��u�0TUM0K0I�G�E�Chttp://www.microsoft.com/pkiops/crl/MicCodSigPCA2011_2011-07-08.crl0a+U0S0Q+0�Ehttp://www.microsoft.com/pkiops/certs/MicCodSigPCA2011_2011-07-08.crt0U�00
	*�H��
���D懾��,V�(�-����6@��m�z� 65�W��Q`[�F�y8��t�ھ$�&��C��=�d�R�m���(ߜ����S�]��!��h2]g����"���S��E��v���5@��7�8��t�=0|3e�?�O��%�vS�Y�������ޭ��b�����+O�yDT
�ͅC�8xQ#�+7&�T��",ۮ8��P���h�(�T@�`���T�l������T����G6~�ܷ�f��D�k�IB���	��m������r����aݽ��G>ƚ읶��2>�Ҁ\�����]��r!���K��Q!��(�V�&sLDt�>��QZ�M����W5X��)l�}F�G�M3�s4��O��8v�vT���:�e:����*Ɲ�N�
���hP���z?别2��fwǴ��#cU�b���ӧx�\Ȇ޽�e,��Ul*!����43=+�
�m����
 ��ސ��n���Iy/钒>
�0�z0�b�
a��0
	*�H��
0��10	UUS10U
Washington10URedmond10U
Microsoft Corporation1200U)Microsoft Root Certificate Authority 20110
110708205909Z
260708210909Z0~10	UUS10U
Washington10URedmond10U
Microsoft Corporation1(0&UMicrosoft Code Signing PCA 20110�"0
	*�H��
�0�
���r.��n��M4��X!�B*k�ZP��8I���7k���8™��9�1BӉ
yd�~�`$l��I��h^�ߛS�
,ï٩+�z	�זY�`�fv�2R&/�PϳD�]��.u�h��m�:\��F��8d�nd5x��c-�@����
�\y�I)�
��w��=��+ZMV(�zr�:�I^���C���{�{��>��]�O��/Y�;-�3Xŷ>�2ӳ=����8~ҝ�,�NV�!5%�9ndS���#������_��R������!t%_(��'(8%�9J6�|���#��f�aj�(I�_��%]�!K>RĵW?$��z[/�#�p]QFw��Ἤ�_����UK�9��#I��D|E��rz�r�$߿F����Wۃ��MI0�����[���ݰf��{���K�I)�(��}g��bx_�/��W�\�w((��m�(�,�@7O��D��	L�ԥC/t��n�x X,]`��>O3�ڰ�ޞN�F�l���ֈ����0��0	+�70UHnd�Pӂ�77"�m��u�0	+�7
SubCA0U�0U�0�0U#0�r-:1�C�N���1�#�40ZUS0Q0O�M�K�Ihttp://crl.microsoft.com/pki/crl/products/MicRooCerAut2011_2011_03_22.crl0^+R0P0N+0�Bhttp://www.microsoft.com/pki/certs/MicRooCerAut2011_2011_03_22.crt0��U ��0��0��	+�7.0��0?+3http://www.microsoft.com/pkiops/docs/primarycps.htm0@+042 Legal_policy_statement. 0
	*�H��
�g򆥘�Ty.��tg"���c��B�}�y��e_.,>��r�m���?�
�;�G���i�c�"5��]e��}�FPU��|�K�<B�Rа�k�>.)��=�Եw�9��d�D=xz#�}��t����&F*Š�����h�h.��*?*kXIc	inZ�����F+�;н5�n%��'������(��M=����2���-�[��I9
�
�ƭ�����QEX82q'��'��,: i��Y�hno��t�@�*(>�?Mf��M��o}E�v�@*e��]Rb��c6��������'�ͥ���]cA�[��>w��u�aa������A�(��e/��\��֡F�Y�	KH���)ű��?Ew5�Ң��zz"�H���G#�����k�K���ux��7�yK�ֳ#hu������i;��0�L���umc�=ѝVNO��W"�x2!z�A
�?��̤]����WqVNHE�Bɛv[
�Hk�y���mmj�Rs
zP�1�n0�j0��0~10	UUS10U
Washington10URedmond10U
Microsoft Corporation1(0&UMicrosoft Code Signing PCA 20113R�@�PV�u�R0
	`�He���0
*�H��
	10	*�H��
	1
+�70
+�710
+�70/	*�H��
	1" ��j�A�qi�m2�9�X&&+p�H��Bv�-I�0B
+�71402��Microsoft��http://www.microsoft.com0
	*�H��
��&��Cz���.�
��x�!�(�����Q�SsĴ�s9I�~A��-�������v9*�?�t�%p}��||܃��!ѹ�^��:���p85��6�GV#�h"�-qch��}s<b]÷��6��К�d��#y{��L�ސ}�٧�)!�ъ�]p�Z�(�����<�U���sh���Mď9k'�
6�5g7���,�A%:Z~^����џ�27;ښ	�B|���8�q�׌u���𞍈�;ס��0��
+�71��0��	*�H��
���0��10
	`�He0�Q*�H��
	��@�<0�8
+�Y
010
	`�He ��~ɽ�md"���Uc��8���"�-A3���^O�120200303190842.804Z0��Ф��0��10	UUS10	UWA10URedmond10U
Microsoft Corporation1-0+U$Microsoft Ireland Operations Limited1&0$UThales TSS ESN:2AD4-4B92-FA011%0#UMicrosoft Time-Stamp Service��<0��0�٠3}�EYpE��0
	*�H��
0|10	UUS10U
Washington10URedmond10U
Microsoft Corporation1&0$UMicrosoft Time-Stamp PCA 20100
191023231913Z
210121231913Z0��10	UUS10	UWA10URedmond10U
Microsoft Corporation1-0+U$Microsoft Ireland Operations Limited1&0$UThales TSS ESN:2AD4-4B92-FA011%0#UMicrosoft Time-Stamp Service0�"0
	*�H��
�0�
�����p�fM9�l���7��MD���mle�ԩyv�5w�(k�+��,���}���_�xw�͊l�^<% d��-6���ٌ����r�����ߴ���]02��?P9�v�&)�}���a�N+ŬQ�7�u��#�l���za�0�R
�}��23X�M���j�0Qw���o�a��K��k�c�;�++����sKқ�1��+�I��j[Ƒ��_�}O���Fp^����/�9_�T����ph��0�0U�bI��t*��=�C¾T0U#0��c:\�1��C{|F�3hZ�mU0VUO0M0K�I�G�Ehttp://crl.microsoft.com/pki/crl/products/MicTimStaPCA_2010-07-01.crl0Z+N0L0J+0�>http://www.microsoft.com/pki/certs/MicTimStaPCA_2010-07-01.crt0U�00U%0
+0
	*�H��
�xy.a��f�͝�w�?�3�>Ե�쯛��'��7R�۬�O�e��+	�"7�+L�QzS�]��L�:1���'���:o��L��gr��tX=�X��u��lvO?`�<pU����{��-ҽP��e�<��Oϛ@�^ˢ��gLG�*�&{JD��D�x���Y�aB~fpH����6�y6�Ψ]A0�j�f�S]P�0��eZH��k�sQ7_H�k s���Svn5�Ԥ5t�A�>�	j>�vܥY_��t��$�:ݕ0�q0�Y�
a	�*0
	*�H��
0��10	UUS10U
Washington10URedmond10U
Microsoft Corporation1200U)Microsoft Root Certificate Authority 20100
100701213655Z
250701214655Z0|10	UUS10U
Washington10URedmond10U
Microsoft Corporation1&0$UMicrosoft Time-Stamp PCA 20100�"0
	*�H��
�0�
��
�w�: ����i�ktTե
����|hK,_���a�v�>f+[�S'1A��	�|a0Y�0D�`��TC�M�8�Bݓ��s0W&��E
��G�Ϳ$`2X`F�XG�2�tag�_�T�ϓL��Ħ]�an(������a�F�'$gr!��Kd�Pb�]�w=�Wu���BM@Q��>g�f��D~��K�n�ʱ��z*
1��N���5�x���<�/D����d��� 	�x����D]^�O"M���0��0	+�70U�c:\�1��C{|F�3hZ�mU0	+�7
SubCA0U�0U�0�0U#0��Vˏ�\bh�=��[�Κ�0VUO0M0K�I�G�Ehttp://crl.microsoft.com/pki/crl/products/MicRooCerAut_2010-06-23.crl0Z+N0L0J+0�>http://www.microsoft.com/pki/certs/MicRooCerAut_2010-06-23.crt0��U ���0��0��	+�7.0��0=+1http://www.microsoft.com/PKI/docs/CPS/default.htm0@+042 Legal_Policy_Statement. 0
	*�H��
��Q
���?�q=���!o���1����Wm0���f�j���x�Ǩ�%��kTW+Q�D��S���`�v�@@A��\�\�^5�$VKt�Bȯ���7}Z?�yJ�R�8�/y�e٩�k����zoK0D$"<�����Y)����p�2J'�U�/���3�b_��W@��Ιf���jb��J�&�9�Jqc�{!mÜ��<�}�j�x�m���8ؔ�ƥ
������B�����"8 �%�d��~cY%z.9Wv�q����a�˚�G����ͧ��}���;q	�]t�"aڰPo�����1��:�eGx�H���r~akow��˧	�9����؂�r�����*T9�[��
U�z�s;�-��3.)��/T'!�ȬN�(���ۖ��B���AM�*��f0ӻt2K�c{���/�!�Y���D<�Pqס��U�i�W���0����M�
�]O�8/��X.�
�P5��	'ճ~5��6��_��t�I���0�70����Ф��0��10	UUS10	UWA10URedmond10U
Microsoft Corporation1-0+U$Microsoft Ireland Operations Limited1&0$UThales TSS ESN:2AD4-4B92-FA011%0#UMicrosoft Time-Stamp Service�#
0+���7�ƹĤC���S�����0���~0|10	UUS10U
Washington10URedmond10U
Microsoft Corporation1&0$UMicrosoft Time-Stamp PCA 20100
	*�H��
��c0"20200303221251Z20200304221251Z0w0=
+�Y
1/0-0
��c0
b�0�0
�
5�06
+�Y
1(0&0
+�Y
�
0� �
0��0
	*�H��
����۟����ѥ1�[O�&OR��k��
��G����������s�O���v�M�޺��hE����dlHf�~��o��>����B�	�\1I�3�leR���	�jcM����7�z�0�MU1�
0�	0��0|10	UUS10U
Washington10URedmond10U
Microsoft Corporation1&0$UMicrosoft Time-Stamp PCA 20103}�EYpE��0
	`�He��J0	*�H��
	1
*�H��
	0/	*�H��
	1" r-��d�*������f�&|A��ZQ����0��*�H��
	/1��0��0��0�� �6N�E�J�Q�؈��O�	2��&��Y�G0��0���~0|10	UUS10U
Washington10URedmond10U
Microsoft Corporation1&0$UMicrosoft Time-Stamp PCA 20103}�EYpE��0" Q�IJ_g�$~����3��˂n������(0
	*�H��
�*j�ƭ	�ڻ��K�M�t��Ly�'��
3|�V�R@@Ԁ��;n<��8�'����9U��M�ٔ��g�`���n\��`	������&
���QL֕I��%�@�#K�Fo
��n7�z��"�����[�y<yO�K�/�A�2��~q����T|j�-��娪�mjҢ��=	��	�ʑ~�Y}@�`�Eu���W�C�S�C.A�b'�zmj{��Z�! Lg�\eKF��wuS�]J2dk�&�tB�p8K