MZ@ !L!This program cannot be run in DOS mode. $PELcp\" 0N `  `O KF0> P  H.text  `.rsrcK L@@.reloc D@BH n P"(0 *{-}(1 ( (2 (1 *"(3 *( *(4 rp(5 o6 s7 }w*0 ~v-s v(+&~v* *.({w*0s( -*{w(o9 ,Q,M +6u ,& o: 1  o; r5p(< X i2(= (> **0( -*{w(o9 **R( *0( -*{w(o? **0G}zs}(4 }{}|}}{s5}~*0    (,. +s@ +sA oB _}z{xos(( ,ݛ()oC , ((-or=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 fq0 f1 f2 f3 f4 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 *'n0{z,*(b sc ok ol +V(m (,Ft>  o] of ,$  o] (~sn oo (+  o] oi &(p -o * c0*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 {oo,**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%(1oAo &s *(]o o to o"s *0'VoI (_rpo#([ *2( uQ*{*:(4 }*0rp(@(:rp(A %rmp% (Co o &rp(A o o &o{o](7*0roo +No o-o# +o% rp%s (A o o &o - ,o * Zg 0o u@ (;*0J(A %r p%o %r)p%o (Co o &*0r3p(@%o` o %o` o %o (A o o &(=,9o 1/o o o  o (z o*^r\0[{-@rp%rp%( o6 o o oI (A}o {o &*0oo o (-oo o (,xr3p(@(A o,%rip% (Coo -%rp% (Co o &8rp(@(A o o &rp(A %(4( os rGps (Bo o &oo o (-xrWp(A %rp% (Co o &rp(A %rp% (Co o &(F,Ao 18o o o % o]oo (z o(=*%\0rp(@(:rp(A %rmp% (Co o &rp(A o o &oWo](7*F~rqp(J *0(4os (B*08  ++ uU -s o s o &X i2*0@ +5uU - s o YoI s o &X i2*0S( o (A ( o (A o o &o o &*03( o % (A o o &*0 rp(A o o &*.r{p*0(I  ,o (-o (M 8o_ . 3&teo ( +rtdoh ( +_o5 rpo ( ,o5 r)po ( , o ,oI ( +( % (O(N*Zu`,t`*o *( -o %( ,*(Q(O*0#  + s o &X i2*02 (= rp%o %(> s o &*0( ,%r p*r pr 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( -Xi?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*r pr 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 ~*Rrp}(*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=]@80(f uk o ,**06 o ,*o o o ( ,to 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 rp(too (< s o &o (too s o &(too (too (o (Jo (so &o o &s  `o (_o4rps o o &o o s o &o (too s o &(too (o (Jo (so &o o &s `o (_rpo$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 r5p rMp repo rip(J (]o o%(_o%o o (Ao s(]o.o,oo o -o (too (t(zo,Eo 1;o o o ' (](too (z  oo,Eo 1;o o o ' (](too ({  oo (\s (Yn%(\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 rypU%o s %o s s o &o (H*0%s (]o*o=o o (`o (]o+~%-&~ s  %s (f ( ,to o (]o% (_ o+o o (Hs  o s o  o  o  +( (q( -!o o  o  +B(   o - (p  o  +  o& s o  ( -!o s rpI% s o o s s o &* O]05&o&(r o rp(< o o (_%( os o &s s  (_%( oU%o s %(_os s s  (_%( oU%o s %s s o ,rps +(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 rps o &({o od +$(e o o s o &(j -o o rps o &*Y1j(]o*o6(*0( - (_o2 *2({o *2(ut*0+(4 ((I 3iY(*iY(iY YE    *(*(*03, -~( +3 ~( , o"*{*"}*{*"}*{*"}*{*"}*Rrpr5p(*rEprmp((  rp(J *0(-o! 2o: o" o# *Frprp(*Frprp(*Frpr p(*Fr pr! p(*Fr/ pr7 p(*FrG prO p(*Fr/ pr p(*FrG pr! p(*Frpr_ p(*Fr prs p(*Fr/ pr_ p(*FrG prs p(*Fr/ pr p(*FrG pr p(*Frpr7 p(*Fr prO p(*Frpr p(*Fr pr p(*0A r 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 ( 89X3: (  , .+j  ( +]  (  (+EX3>rp( ,,o} +r/ p( ,, o} o, o- % :*010(s.   89o: 9o ';(E 2=aiz8X @ (9 ( +vY -o +k, ( (+O+G+?,; ( +.,(o} +,(o} o, o- % :*6(o( *0f r po! /Q*r p(: X ~o/ / o Q+ Yo; QPr po , Po Q*0N1(o) o0 + o1 o3(o} o - ,o * *,@ 02Qo [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^ 04Q ~o2 2*( o3 0r p(9x o4 8jo5 E 999 9"84r p( , o6 &8r p(, o4 8r p(, 8r5 p(-rG p(, o4 8rO p(9 o4 8ra p( , o6 &8rG 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(*2r p(* . 0.  `3****0/7 o= r p(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(`rA p%(H /oI oA +(`rA poA (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*(]oo<(`oD(`oF(o (H(o o 9%o r p(< o (o` o (]o,(,M(](o (o` o o ( (o` oh o oo,oo -oo +o o ( %oS ((`o oS _(]o)o (((((]o)o ((((o ;Xo,Eo 1;oT o o ' (](o (|  osU o. sV 9 sW   r poX  oY (](o%o & (_o3(\sV r ps oZ o` oh  oT (Zn% 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  (Zn%U%s %o s % s s[ s o &o,Eo 1;o o o '(](o ({ oo 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 to *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 *0A( ((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 *0C(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>*0Do ,bo 1Ys^ o o ,o 1o_ o` o_ % (](o ({  ooS _ (]o)(((((*4G%\0 8E(o o (9(o (:((\r pU%(sa %(s %(o s %(s s o &( s s o &(s o &*(o o uq ,Hob -( (c ,1(_(r pU%(s s o &*(s o &*0@FoT oS _ (]o)(((((*0G(\((U%sU s o &(\r pU%(s s o &,<o 13o o % (](o (| o(o o (, (8(o o (, (8(o o (,X(o o to o (,(o ((+G(o ((+.(o o (,(sU s o &(\rG pU%(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 *0HsU -y(o o tq s  o  ob od ,(o s o  ((_(rs po s s o &*(s o &*0.I.( (_os .(e s *0}JsU -`((\rs pU%(%%(s s s o &( s s o &*(s o &*00K(o` of uk ,oa (og ,**0LVo o (,(_tq(08(,(_td(](4+o( ,gto 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 *0Ook 9o o (H9o -o5 (l o ,*E, 4#+2s *(*(*(*(*(***0@Pt- iU  +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 %(_o5U%(r (s 5s s s *02T (_o5U%(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*:oo*0SK{, (o` (]o,(K,*(o` of uk ,oa og ,**2(u8*&(*N(]o*o9*J(]( o*0BG,7o 1.o o o  (](w oo* \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{ *0Voo (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 */@0Xo 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 oos o s o o & o(o (L oo o (,Cs  o   os o  (_(r po s +o  os 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 Xi2s 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 rpo ,rp*(?*6(C(< *F(A~(< *"~*2rp(< *2rp(< *2r#p(< *2rWp(< *r(-T*tqo T*o: 1#o .3o %.o *%.o *2rp(< *0'I (L-*(c ,*o5 (c *0R^Q~o +%( ( og , ( Q ( -Co **2@0@%rp%rp%rp%r5pr=p(7*.rUp( *.rp( *frp%%( *Vr!p%( *vrIp%%%( *Vr{p%( *Vrp%( *Vrp%( *vr_p%%%( *frp%%( *frp%%( *r p%%%%( *vrSp%%%( *frp%%( *rp%%%%( *Vr?p%( *vrsp%%%( *Vrp%( *Vrp%( *Vrp%( *r9p%%%%%%( *vrop%%%( *.rp( *Vrp%( *fr+p%%( *frp%%( *Vrp%( *frp%%( *VrWp%( *.rp( *Vrp%( *Vrp%( *VrGp%( *frp%%( *rp%%%%( *Vrp%( *vrsp%%%( *Vrp%( *frp%%( *frp%%( *.rKp( *Vrp%( *Vrp%( *Vrp%( *VrEp%( *Vrp%( *Vrp%( *Vr)p%( *Vrip%( *frp%%( *frp%%( *vr p%%%( *.r3p( *Vrp%( *Vrp%( *Vrp%( *.rIp( *frp%%( *Vrp%( *Vrp%( *Vrp%( *fr7p%%( *vrgp%%%( *vrp%%%( *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(+&(*0arq-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.>%Ew - &;4(+S#0cs s o o ( (   o , ((o  o o s o ( ~1( , ((zso*!6 Jo s *Jo s *09do +( o ,sz( -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 tQr;/po tQr/po tQ~W Qr 0po 9 o 8o to o 8o to r)pog ,ro r0pog ,^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 0gXr0p}rX1p}r1p}r2p}Xr2p}r2p}r63p}r3p}Xr4p}r^4p}r4p}r 5p}r5p**s *0H#?. #3~*#?3(*#@3~*~*s s s *F(4 (*(4 r5p( +&r5p( +&(*0}h(4 r5p(+&r5p( +&r5p( +&o+(+ i. r5p(zo+~$%-&~#@s %$(+(*0ir6p(+&(-oo r6p(z,"r5p((9 (X ,(z,Cr5p((; (X ,(zoo ( ,oo (z}-+(+}}}s}(%*{*{*2{o*6s}*{*"}*J~4}(*fr06p(}(*0:jrj6p((&s o ( ( ,o *& / jr6p(+&(&(*0:jrj6p((&s o ( ( ,o *& / jr6p(+&(&(*0\k{,}}}s= s }(,1{~1( ,( o<{s (${s {ok ol 8(m o_ . .?+\(-to  (-to  += o<+,t> {!  s o  + o_ (z(p :lo 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( ,:r6p ( (  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<+{**A4JiN 4% ^)*:_*>#(*E0_l{,8r-7prC7p(+ {{{]%](*{{{](*0&m{{{{s o*0 ,n{,{,{~2( ,*{~&%-&~#As %&(+ o, 8o- sG },(. 9o {(8 s}+o  Hs/ (+(+o  ~'%-&~#Cs1 %'(+~(%-&~#Ds1 %((+(+(+,o] ( o<8( o$ {o% o4   o$  (5  {  }6  {}7  p%r7p s8 }9  }:  };  s< }=  s< }>  s?   o$  o@ {"{ (+oB o :< ,o *AV! 0*oo (8 o oC o s8 *0psD s r7p(< {(8 ooE o} +(~ ()oF ( -4o {sG oH +(I  oJ (K -eo *9*c03qsL 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 :Oho *(3Pk#0JroR oW +(X {!oT oU , (Y -ko ** ,80QsoR oW +)(X {!oT oZ , o o  (Y -ko * 6B0t{ok ol +t(m o_ 3ct( o[ o} +0(~ { o\ -{ to o] ( -4o (p -o *<=y05u{, {,* {ok ol +(m o^ o (p -o ( ,r7p {-Fr7po! 1 o; r7p(< (9}+r7p(< (9}{-{.o 1 o; r 8p(< (;}+r 8p(< (;}{r7po! 1o; r 8p(< (;}*$#G>{-(z*0Kvo (( {o o{(8 s_ {"{o` *0w{"{oa ,*sD sb s {o o{(8 oo o} +b(~ o o oc   -(-{  od -% ()  oF  ,  o oe ( -4o {sf {"{og *^o0Cxo (8 o oC sh o (*{"{oi *0[yoh r8poj ,Hs rG8p ( ( oh r8pok oj s o o  }*0zo 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 {(8 sm 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 *gE0~o o - v*o o  (,-o[ ~)%-&~#Es %)( + ++o[ ~*%-&~#Fs %*(!+ o o -o o +_,o o s *v*0o 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*0xo o to tt s (5{o o(8 o s o` tQo o o  oJ *0Ho ooa od +(e o o(j -o *!90>o ( ,( o ( ,( o (7*0To o to tt {"{o o (8 o s o *0 (; o *&C(:*0sb %.o  + (<oe X i2r p +o rqp(J Xo Y2o Yo (< *&C(<*0Qo  +( -_X i2s ( -o ( -( (< *(4 - r8p(z} } } } }*2(=*{ *{ *{ *{ *{*0r8pr09pr9pr9pr:pr@:prr:pr:pr:pr:pr:pr ;p .!*b(4 rS-p(}"*"(E*{"*Jr p(}"*0OsI }-r ;p("+&{-rD;p( Js (M ,o *+C 0*r ;p("+&(T (K(#+($+*0RsK }.r ;p("+&{.rZ;p(+&r06p((LLs (M*0Lo (  ( ,((zo o (  ( ,((z*0)(Q,Q*o QP(U*0(r ;p("+&(T (O(#+($+*0r06p((Lr ;p("+&(So%+o +~o o o o +J(  o ,o ,,tJo +o] (s 7s o ( -o o :w ,o (P*OW4 03~0%-&~/Os %0(&+ ('+($+*(RPo - Po 1**0-Q{" ,. +s@ Q+sA Q(S**o Q*0Es o o ( QP~3(x ,~3P( s o *0o o s~ ~s@ oE oF &o%+o 8 o (V,#o] (q 's o 8o 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 0Jo ok ol +(m o o , (p -o **'80Ks o +!( ( (a( oL ( -~o * .;0)sO rmpoP oQ oR oS *0s ~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 &*0Us 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;pUs +s o U%s %s o s o &*" 0Iн( r;ps н( U%=s s o o &*>sP%}5*>sX%};*.r;ps *nr;pU%s s *o: ~#1(\((+(]*%(]*0$]o oo ~! ( o (J *0Xs  `o o ~s o &o (s o &o ~ s o &*0is  o{ o ~o o ~s o &o (s o &o ~ s o &*r #P$ (%*0 ~( ,#@o *~( ,#@o *~( ,#?o *(( ,#?o *o ( ( o *0  s *0Qr06p((f P~?%-&~>bs %?()+-o ( P(h&*( -( s o **&s *Nr06p((i*.s *0r;p(*+&r;p(+&r<p(+&r06p(o ( (x , r;p(z(k P~@%-&~>cs %@()+-o ( P(h&*(*0er<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( ,r3p*r 5p*~0( ,r1p*~1( ,r63p*r4p*~0( ,rX1p*~1( ,r2p*r^4p*2~5(++*0No -o .o , o 3o -o rT<p( , o (y*Q*0Ir0p( -r2p( -r4p( -+~0Q*~1Q*~2Q*Q*0V~0~1~2~13~24%~0%~1%~25*0O~W }9(4 r^<p(rp( +&r5p(}<}8s}7*{:*{;*{@*"}@*0s ~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  +* (  {N o%  (  o  ( - o o$ {No% ({?~2( ,{7o~2( ,(({Oo  + ( {No%  ( - o oe(-1}:{N};{M}={Ls }>E(,*('% ss oq+ {7ooes *A|F- M7#22d9E2k 0:jrj6p((s o ( ( ,o *& / 0 blr6p(+&(r<pr<p(+ (}{<{={>{8{9{?]%](*6~1(*0qr^<p( +&rp( +&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>Q0"o-+ o ok o o &*o ,(-(k(( (z*>{:-(z*05o, +o+ o 3 o - ,o ** ' 0qo 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 0o o   s o ,ho  (  ,r7p s8 8  -o o (X+o o ([ us o 8o9{?~2( ,* on,4{L o -% o4   o$ r7p (5 s8 +f  ,D{M o ,3 o {M o &{L o ,{L o & e(U s o ss 8o oo-o(,yo-= ro=po-o o o(^ |s o op(<os8 o +d ro=po-o -o o=(Y+o o=(\ us o Xo  / o9o f(<{Fo, p%+p{<o } o (X -+o } os< } os< } os< } os< }= }9 o }: s?   o$  or,{O o *{L o &*0oo,( ( **0~W s {7{Goo  +>o! t> oK(X ,( -(o"   o# o - ,o ( -(*#Jm 0o$ (-*~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( 8o)  o ~e%-&~`s* %e(/+o( +Uo) o` o` o ,7o ,,  o o` (r s o  o - ,o  -o :E ,o  ,{E o+ +*{L o &{Io, &{I o, & o$   or*bP p 0vo6 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 **-I0To/ +.(0 o oEo3 , o ,  (2 -o * *;B0To/ +.(0 o oEo3 , o -  (2 -o * *;B05o o o s o {Io4 *05o. e o. e {Io5 {Io5 8o 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~ *0o o o[ o o` tt   o[ o} +)(~ o o _ o o ` ( -4o  _,3o[ (o (o o (pQ*r pQ*56k{7{Gos6 (*{7{Gos6 (*{7{Gos6 (*0es7 sb o  +c o! t@o(u,#o8 ,o9 o: o;  o< o, ovoe o - , o o8 , o9 *o 0s }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(  8s   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 Xi2{Fo= oto{<{hsf o$ ,. +$oi+'oi{KoC &+{Lo &or* 0ao= o -s ( sD o$  om oE o - {L o & or*0sE sb QoF 8`oG o-ozoo-zo-8-ozoov(V+ozoov(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 :ooN oS   (T 2+ (U -)ooN 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 9o:}oN oR :looN oS   (T 2+ (U -)ooN 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 9 o:oN oR :o|oN oS   (T 2+ (U -)o|oN oV   (T 0+ (U ,x(yor=po|=oN oS oN oV ove(b vs o PovoH 8oW 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? 2o 1Q+QP*0{Ko\ >( -*{Ko] +x(^ {Ho_ ols (w,r<pr=p(w(  o r<pr)p(x(  o o   ((` :|o **0s 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 {7ooq ( 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%-&~qs %r(&+(6+,*((#+($+*r-p(v r[.p(v r06p(s(*0M( ~s%-&~qs %s(&+(6+,*((#+($+*0wrq-p(+&r-p(+&r06p((-s %(o *sx rq.poy (s( ,o *E&k 0M( ~t%-&~qs %t(&+(6+,*((#+($+*0rq-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%-&~qs %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 *0s ~0( ,( s o  r(h- `(m( ,( C{B( oo{Cooo oo ,Js }xo(7+s (8+o oo , ݷoo ,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%-&~qs %v()+-o( o ,,({ ,( *s0( o ,o *  0o  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%-&~qs %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%rAp%rAp%rAp% rAp% rAp% rAp% rBp% r Bp%rBp%r-Bp%r=Bp%rSBp%reBp%rwBp%rBp%rBp%rBp%rBp%rBp%rBp%rBp%rBp%rCp%rCp%r%Cp%r3Cp% rCCp%!rOCp%"raCp%#rkCp%$ruCp%%rCp%&rCp%'rCp%(rCp%)rCp%*rCp%+rCp%,rCp%-rCp%.rCp%/rDp%0r Dp%1rDp%2r%Dp%3rDp%4rDp%5rDp%6rDp%7rDp%8rDp%9rDp%:rDp%;rDp%rEp%?r)Ep%@r;Ep%ArOEp%Br_Ep%CriEp%DrsEp%ErEp%FrEp%GrEp%HrEp%IrEp%JrEp}_s %rEprEpoL %rEprEpoL %rEprEpoL %rEprFpoL %rFprFpoL %rFprFpoL %rFprFpoL }`sb %r!Fpoe %r%Fpoe %r+Fpoe %r3Fpoe %r9Fpoe %rAFpoe %rKFpoe %rQFpoe %rWFpoe %r]Fpoe %reFpoe %rmFpoe %rwFpoe %rFpoe %rFpoe %rFpoe %rFpoe %rFpoe %rFpoe %rFpoe %rFpoe %rGpoe %r Gpoe %rGpoe %rGpoe %r)Gpoe %r1Gpoe %r;Gpoe %rGGpoe %rQGpoe %r_Gpoe %riGpoe %rsGpoe %rGpoe %rGpoe %rGpoe %rGpoe %rGpoe %rGpoe %rGpoe %rGpoe %rGpoe %rGpoe %rGpoe %r Hpoe %rHpoe %r/Hpoe %rEHpoe %rOHpoe %rYHpoe %riHpoe %rwHpoe %rHpoe %rHpoe %rHpoe %rHpoe %rHpoe %rHpoe %rHpoe %rHpoe %rHpoe %rHpoe %rIpoe %rIpoe %r+Ipoe %r5Ipoe %rGIpoe }as %rSIprcIpoL %ruIprIpoL %rIprIpoL %rIprIpoL %rIprIpoL %rIprIpoL %rJprJpoL %r+Jpr9JpoL %rGJprWJpoL %rkJprqJpoL %r{JprJpoL %rJprJpoL %rJprJpoL %rJprJpoL %rKprKpoL %rKpr#KpoL %r/Kpr7KpoL %rCKprMKpoL %rWKpraKpoL %rmKpr{KpoL %rKprKpoL %rKprKpoL %rKprKpoL %rKprKpoL %rKprLpoL %rLprLpoL %r#Lpr1LpoL %rALprOLpoL %r_LpryLpoL %rLprLpoL %rLprLpoL %rLprLpoL %rLprLpoL %rMprMpoL %rMpr1MpoL %rCMprOMpoL %r[MproMpoL %rMprMpoL %rMprMpoL %rMprMpoL %rMprMpoL %rMprNpoL %rNprNpoL %r)Npr5NpoL %rCNprONpoL %r]NpriNpoL %ryNprNpoL %rNprNpoL %rNprNpoL %rNprNpoL }bs %rNprNpoL %rOprOpoL %rOpr-OpoL %rAOprMOpoL %r]OpriOpoL %ryOprOpoL %rOprOpoL %rOprOpoL %rOprOpoL %r PprPpoL %r1PprCPpoL %rSPpriPpoL %r}PprPpoL %rPprPpoL %rPprPpoL %rPprQpoL %rQprQpoL %r'Qpr9QpoL %rIQpr]QpoL %roQprQpoL %rQprQpoL %rQprQpoL %rQprQpoL %rRprRpoL %rRpr%RpoL %r/RprARpoL %rQRpraRpoL %roRprRpoL %rRprRpoL }cs %rRprRpoL %rRprRpoL %rSpr+SpoL %rASprYSpoL %rsSprSpoL %rSprSpoL %rSprSpoL %rSprSpoL %rSprTpoL %rTpr#TpoL %r7TprGTpoL %rYTpreTpoL %rsTprTpoL %rTprTpoL %rTprTpoL %rTprTpoL %rTprTpoL %rTprTpoL %rUprUpoL %r-Upr=UpoL %rOUpr[UpoL %riUprwUpoL %rUprUpoL %rUprUpoL }ds %rUprUpoL %rUprUpoL %rVprVpoL %rVpr/VpoL %rEVprQVpoL %raVproVpoL %rVprVpoL %rVprVpoL %rVprVpoL %rVprVpoL %r WprWpoL %r%Wpr3WpoL %rEWprWWpoL %rmWpryWpoL %rWprWpoL %rWprWpoL %rWprWpoL %rWprWpoL %r XprXpoL %r)Xpr5XpoL %rEXprQXpoL %raXprmXpoL %r}XprXpoL %rXprXpoL %rXprXpoL %rXprXpoL %rXprYpoL %r#Ypr3YpoL %rEYprSYpoL %rcYprqYpoL %rYprYpoL %rYprYpoL %rYprYpoL %rYprYpoL %rZprZpoL %rZpr)ZpoL %r9ZprGZpoL %rWZpriZpoL %r}ZprZpoL %rZprZpoL %rZprZpoL %rZprZpoL %rZpr[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{aprapoL %raprapoL %raprapoL %raprapoL %raprapoL %raprapoL %raprapoL %r bpr bpoL %rbprbpoL %r%bpr%bpoL %r3bpr3bpoL %rAbprAbpoL %rObpr]bpoL %rmbprybpoL %rbprbpoL %rbprbpoL %rbprbpoL %rbprbpoL %rbpr cpoL }esb %rAFpoe %rmFpoe %rGpoe %rFpoe %rFpoe %rFpoe %rEpoe }fs %r)Npr5NpoL %rNprNpoL %rcpr-cpoL %rEcprWcpoL %rkcpr}cpoL %rcprcpoL %rcprcpoL %rcprcpoL %rcprdpoL %rGIprdpoL %r#dpr/dpoL %r=dprIdpoL %rWdprcdpoL %rKprKpoL %rqdprdpoL %rdprdpoL %rdprdpoL %rdprepoL %repr'epoL %r;eprKepoL %r]eprmepoL %reprepoL %reprepoL %reprepoL %reprepoL %repr fpoL %rfpr'fpoL %r7fprCfpoL %rQfpr]fpoL %rkfprwfpoL %rfprfpoL %rfprfpoL %rfprfpoL %rfprfpoL %rfprfpoL %rfpr gpoL %rgpr3gpoL %rSgprogpoL %rgprgpoL %rgprgpoL %rgprhpoL %r/hprGhpoL %rahpryhpoL %rhprhpoL %rhprhpoL %rhpripoL %r)iprAipoL %r[iprsipoL %ripripoL %ripripoL %riprjpoL %rjpr1jpoL %rIjpr_jpoL %rwjprjpoL %rjprjpoL %rjprjpoL %rkprkpoL %r/kprEkpoL %r]kprskpoL %rkprkpoL %rkprkpoL %rkprkpoL %rlpr+lpoL %rClprYlpoL %rqlprlpoL %rlprlpoL %rlprlpoL %rlprmpoL %rmpr1mpoL %rGmpr[mpoL %rqmprmpoL %rmprmpoL %rmprmpoL %rmprnpoL %rnpr-npoL %rCnprWnpoL %rmnprnpoL %rnprnpoL %rnprnpoL %rnprnpoL %ropr)opoL %r?oprSopoL %riopr}opoL %ropropoL %ropropoL %ropropoL %rppr%ppoL %r;pprOppoL %reppryppoL %rpprppoL %rpprppoL %rpprppoL }gs %rLprLpoL %rJprJpoL %rMprMpoL %r qpr)qpoL %rIqpriqpoL %rqprqpoL %rqprqpoL %rrprrpoL %r9rprhpoL %rUrprqrpoL %rrprrpoL %rrprrpoL %rrprspoL %r-sprGspoL %raspryspoL %rsprspoL %rsprspoL %rsprtpoL %rtpr3tpoL %rItpr_tpoL %rutprtpoL %rtprtpoL %r[MproMpoL %rtprtpoL %rtprupoL %rupr-upoL %rAuprUupoL %riupr}upoL %ruprupoL %ruprupoL }hs %ruprupoL %r vprvpoL }is %r-vpr;vpoL %rMvpr[vpoL %rmvprwvpoL %rvprvpoL %rvprvpoL }j(rvps (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 }]*0crvp( +&{Ro ,*{Ro ,*(-{](o o ,*oo ,**0lrvp( +&{Ro ,*{Ro ,*(-{\(o o ,*(-oo ,**rvp( +&s  (*0X{Ro , {Ro *(,*( (,(< *(,(< *{]o o - o,(< *{So ,{So (< *sb %rvpoe ~z%-&~ys  %z((,(< *sb %rvpoe %rvpoe ~{%-&~ys  %{((,(< *sb %rvpoe ~|%-&~ys  %|((,(< *sb %rfpoe ~}%-&~ys  %}((,(< *sb %r wpoe ~~%-&~ys  %~((,(< *sb %rwpoe ~%-&~ys  %((,(< *sb %rwpoe %r%wpoe %r-wpoe ~%-&~ys  %((,(< *{To ,{To (< *{Vo ,{Vo (< *sb %r5wpoe ~%-&~ys  %((,(< *sb %r?wpoe %rGwpoe ~%-&~ys  %((,(< *{[o ,{[o (< *sb %rOwpoe %rUwpoe %r[wpoe ~%-&~ys  %((,(< *sb %rawpoe %riwpoe %rqwpoe %rywpoe %rwpoe s  ((,(< *sb %rwpoe %rwpoe %rwpoe ~%-&~ys  %((,(< *sb %rwpoe %rwpoe %rwpoe %rwpoe %rwpoe ~%-&~ys  %((,(< *rwp(o ,o: Yo" rwp(J *{Uo ,{Uo (< *sb %rwpoe %rwpoe %rwpoe %rwpoe %rwpoe ~%-&~ys  %((,(< *rwp(o -rwp(o , rwp(J *rwp(o , rwp(J *rwp(J *rvp( +&s  (*09s {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 ~%-&~ys  %((,(< *{sb %r xpoe %rxpoe ~%-&~ys  %((,(< *{sb %rxpoe ~%-&~ys  %((,(< *{sb %r)xpoe ~%-&~ys  %((,(< *{sb %r5xpoe ~%-&~ys  %((,(< *{sb %r?xpoe ~%-&~ys  %((,(< *{sb %rGxpoe %rQxpoe %r[xpoe ~%-&~ys  %((,(< *{T{o ,{T{o (< *{V{o ,{V{o (< *{sb %rexpoe ~%-&~ys  %((,(< *{sb %rsxpoe %r}xpoe ~%-&~ys  %((,(< *{[{o ,{[{o (< *{sb %rxpoe %rxpoe %rxpoe %rxpoe %rxpoe ~%-&~ys  %((,(< *{sb %rxpoe %rxpoe %rxpoe ~%-&~ys  %((,(< *{sb %rxpoe %rxpoe %rxpoe %rxpoe %rypoe ~%-&~ys  %((,(< *{rwp(o ,%{{o: Yo" rwp(J *{U{o ,{U{o (< *{sb %rypoe %rypoe %rypoe %r'ypoe %r/ypoe s  ((,(< *{sb %r7ypoe ~%-&~ys  %((,(< *{sb %r7ypoe %r?ypoe %rGypoe ~%-&~ys  %((,(< *{rOyp(o , {{o: Yo" (< *{r[wp(o , {(< *{rwp(o , {{o: Yo" (< *{(< *0Qo (,>o: -*o: s o ( o &o o &oI **0- o Xo; QXo *J( -( **o ( -o o , rWyp( ,**0_rvp( +&{^((-;(o o -royp(o -{_o (=+,**(,o: 1{ao o ,**0nrwyp( +&ryp( +&{Ro ,ryp(ryps z{Ro ,rwyp(rwyps z{Ro *ryp(o -o: Yo" ryp(< **{k*"}k*ryp(>+&o rvp( ,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 BsY ~p~%-&~s %%~o(*0 BsY ~r~%-&~s %%~q(*0 BsY ~t~%-&~s %%~s(*0 Js! ~w~%-&~s %%~u%~v(*2{lo *{l*0w{ls ( o o o  +o &o o &o -( o ,o ,o *"?a Rk 0o o o o -%( -(  (J o +o *s  8! s s o +7(   oB_,# oC- (+  (( -o o ,Mo ,$(  o &rypo &(  o &rypo &o &rypo &o ,Mo ,$(  o &rypo &(  o &rypo &o &rypo &X i?s o ,,(  o &rypo &(  o &o &( -(  o &o &oI o *qD0s rypo?(rypo@(oA o?-o@- oA+ ,rzp r)p(o , rzpo &rypo &o &rypo &*09o , rzpo &o &rqpo &o &r)zpo &r9zpo o ( ( (< o &s o o o o &*0[r=zporAzpprpqrprr%psr-ptrtpurpvrpw*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( -rp( -rp( - +T*T*T*T*fo o o ss*0( -.*.*Vrp|rp}*b( rp( (1*>( (2*{*{*{*{*{*{*{*{*{*{*{*{*2( o *s!*0rp( s }( {o r0p( s }( {o rBp( s }( {o rRp( s }( {o rdp( s }( {o rxp( s }( {o rp( s }( {o rp( s }( {o rp=( s }( {o rp( s }( {o rެp( s }( {o rp ( s }( {o *0 ( rpo }( r0po }( rBpo }( rRpo }( rdpo }( rxpo }( rpo }( rpo }( rpo }( rpo }( rެpo }( rpo }*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( rp( (j*>( (k*{*{*{*{*{*{*{*{*{*{*{*{*{*sY*0wryp( s }( {o ryp( s }( {o r6p( s }( {o rJp( s }( {o rp=( s }( {o rp ( s }( {o r`p( s }( {o rrp=( s }( {o r=p=( s }( {o rp=( s }( {o r=p=( s }( {o rp ( s }( {o rȭp ( s }( {o rp ( s }( {o *05( rypo }( rypo }( r6po }( rJpo }( rpo }( rpo }( r`po }( rrpo }( r=po }( rpo }( r=po }( rpo }( rȭpo }( rpo }*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*0Jo  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(*F6(`(*F6(h(*2(ls *2(ms *6(is *s *"s *b(B+&(w-(z*rp}(4 }}}}*0 ss  (*0Po  s oo~oo+o  +o  oo - ,o o+o  + o o ( ,o o - , o o >( s s o o o ( o  so  + (   o ( - o o (  o o *(>X n+ #0N o oI +rp~W o rpo -+rp~W o rpo -*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 to (  -(! ,4o ( ,r>p ryp(J {r7p o  {:{rVpo" (o {rjpo# (o {rzpo$ (o {rpo (o {rpo% x(o +,o ,$o ,{rp (o o& ,{rpo& o o' ,{rpo' o o( ,{r=po( o o  o  +( (( -!o o 9:o o o o_ 3jo o o to o t{r7po {rpo ({o {o  {o *0|{rpo {r)po o {rK=po o (o {-!{r<po (o {o *0{rFpo {r)po o of ,{r^pof (o oC+od +(e ((j -o {o *Vr0{rppo {r)po o oy oz +({ ((} -to o o) +(*  ((+ -o {o *2Nh0R{rpo oE o} +(~ (( -4o {o *80J{rpo rįpo o (rدpo o[ ({o *0v-{o {rpo o  +;{rpo {r)po, o o {o X o- 2{o *0 {rpo {rpo o o o to ( {rK=po {rpo (o o ,r0po ({o *{o {rBpoI o {o *E+rPp*rTp*rXp*~W *0|{rbpo {r)po o of ,{r^pof (o o| ,{rxprpo o o 9o o o` 3m{rpo  +@{rpo {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{rpo {r)po o {r°po0 oh o {rܰpo1 o o {rpoR 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 (rpo +#{ oW ( oj (o (; :o *A4G0w  (Vrp( ,rp**-*oR ,*oj -*o< -oj o= o ,**0v{,IoW rp( -5oW rFp( -#oW r8p( -oW rfp( **oW r8p( -oW rfp( **0*@( rzp$(> o? t*o5 ( (c ,oI ( o *oI *r{, o (*o *0!( o_ 3o *(*o_ . *of ,o {(X -*0{{-+(s {r=po@ {rpo {ṟprرpo {,,{~2( ,{rprC7prpo4 {-2( -{rpo ( -{r,po   ++] {rXp(A (B oC X i2*0?{rdpo {r)poo o {,Ho= r6po2 ,6{rp(rC7po= r6po3 o? (o4 ok ol +@(m o_ . 3t>(+t(+ o_ (z(p -o o ~%-&~s %(+o, + o- ( o - , o {o *M ) 0{rpo {r)po o {rppo (o oR oW +(X ((Y -ko {o *Nj0M{rpo {rpoD o {rȲpoT o o {o *0{rȲpo {r)po o {rbpo (o (o= rܲpo> ,6o? ,.{rܲpo {oE oF {o +ro= r=po> ,$o? ,{oG o? oI o o= rpo> ,$o? ,{oG o? oI o {o *0wo= ~%-&~sH %(D+oI +0oJ oG (,{ o? oI o4 o - ,o *0 *6 (K **oL *0pr$p(E+&uy,~M *u -o5 oI ((z( oN u -r4po5 oI ((z*0 s *0'o  +oO o ,*X 2*"(*0&-,! +o (9 -*X o: 2*0/-,*o: (  +o (9 -*X 2*0,s r po &(r po &oI *NrJp~W (*0-* sb o" +-o -+rPp% (oe o -uL,o , (G oP oQ +(R -o &o & (S -o *9Lw,6( (> *0a( ,r p*rXpr\po rhprlpo rvprzpo rprpo rprpo *0A-:o 2 o: 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 rp(F+&rp(+&rֳp(+&}}}(s}*r6p(+&((o *0rp{o@ r"p{oo o rPp{oo o {{oV oW +#(X {{oo ((Y -o {{oZ o[ +((\ {{o] ((^ -o {{o +( (( -Uo {{o_ +&(`   oa   ob    ((c -o o *4S05;3n0rvp{o@ rpoh o rpo o (. 9o o o t o o td rp{o@ rp{o@ r$poh o oE o} +((~ {{o (( -4o o o o *50o o od :r6p{o@ r)po o o r$po o oh o rbpo o o  +.o{{oe (X o os 2o *0o od :r6p{o@ r)po o r$po oh o ( rbpoT o o oR oW +%(X {{ oe  ((Y -ko ( o[ o} +(~ o , (( -4o o *q2(rp{o@ rJpo o rprpo o *0( oR o o of *0: o o o) + (*  (+ -o **0rp{o@ r)poD o oT o o od +0(e te {{o (  ((j -o o *8=u0Xog ( oD o o ( ,2 + o o 3 o[ o *X o o 2*rp{o@ r)po o (o *rܵp{o@ r$po oh o (o *0rp{o@ rbpo o o o o} +6(~ {{oh ,{{o (( -4o o *3Cvr p{o@ r)po o rJpo o o *r>p{o@ rNprZpo *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 rbpo ,o rhprqpo *(t * *0(u (o sV (-rlpsv z -rζpsv z-r*psv z(u ~~W o rq.p(< (rxp(< (rp(< (( (( ,o * 0op ( ,o *  0  ow ox o rp( , 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{6 X}6{6{4o: ~$[>T*{2*07{13{3( 3 }1 +sP {5}4*(V*f(4 }7( }9*0{7 ,.F*}7{:}<}=+={<{= (^(_}8}7*}7{=X}={={<i2}<*{8*07{73{9( 3 }7 +sX {;}:*(^*.sa>**o *0s }E~%-&~s  %s}Fs }Hs }Is }Js }Ks }Ls}Ms }Os }Ps }Qs }Rs }Ss }T(4 }V*0s }*:{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 *0XR{N(prqp(J oI+ ,1{V~2o /Po . Po 3RQ**0S{U-D{NoJ+o +o (,o }Uo - ,o {U*)B &(r*0Ro ,I-~{Mo ,{Mo o *u -s {Mo *0i,( -oI }\+}\,( -oI }]+}],( -oI }^+}^}_*Reeo *.(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 t rpGo }lrp( Go }mrηp( Go }nrp( Go }orp+( Go }p*b{o{ko t*R{n{ko *b{m{ko t*R{m{ko *R{p{ko *0n{l{ko? t M o -+o s o o o (o ( o &~W *M0I-#~4( , (s*(s*~4( , (s*(s*.sq*~W ( -(  oI (J *oI *6{x(*.sy*jo: Yo" rvp(< *jo: Yo" rCp(< *jo: Yo" r2p(< *jo: Yo" r<p(< *jo: Yo" rFp(< *jo: Yo" rNp(< *jo: Yo" rwp(< *jo: Yo" r7yp(< *2rwp(< *2rwp(< *jo: Yo" ryp(< *2rwp(< *jo: Yo" rTp(< *jo: Yo" rZp(< *jo: Yo" rdp(< *jo: Yo" rnp(< *jo: Yo" rxp(< *jo: Yo" rp(< *Bo: Yo" *jo: Yo" rwp(< *Bo: Yo" *jo: Yo" rp(< *jo: Yo" rp(< *j{{o: Yo" *R{{o *.s*2~1(x * *0n~%-&~s %(K+~%-&~s %(L+~%-&~s %(M+*2ryp(N+*2r6p(N+*2rp(O+*0n~%-&~s %(K+~%-&~s %(L+~%-&~s %(M+*0n~%-&~s %(K+~%-&~s %(L+~%-&~s %(M+*0n~%-&~s %(K+~%-&~s %(L+~%-&~s %(M+*2rp(N+*2rެp(N+*N(o}{*>((*6o}{*Z{{o ts* *:{{(P+*:{{(P+*:{{(P+*:{{(Q+*:{{(Q+*:{{(Q+*:{{(Q+*:{{t*:{{( *:{{t*:{{( *>{{ t*>{{ ( *rp*Z{{o ts* *:{{(P+*:{{(Q+*:{{(Q+*>{{ t*>{{ ( *>{{ t*>{{ ( *rp*{*:(}*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 to {o 3(o o o to {o **{o o o o Q{o o o o Q*.s*.s*Frqprpo *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#USe#GUIDfv#BlobW+ 3}*35 = 2Q}[0LU.NUmJ؈ϋN"JN_NN""M"JlLlMl?OltNlNlCLl`LlLKJLlJl!OltOUV N_3J_ LZ bOZ_x|_uwk O_ B_}m^Z ~j^ 2}|^m,ymm cl} z} }_ms_qms"rmqm^^ ^s_x^& ^ ~݅d~^F^^~#@^⩢Z_ B_ QfB_ fB_[ f ~lul݅ulTulJul\FlfMl ~"y]y^q I^*Z_]箨]d|]F]+]K]/]]e_m^^ l݅D^@^|^^^k^K؈M_DmS_SSUTSl{ 3B_ fB_ ZB_ B_ ڭB_ gB_] Z#^xl)ZoVtVt VtVtCpm&^s_xr 2+^~ -?^0__݅v^m0Se+N؈9t^ } w} } n}rl_o݅- - xVta ukk{ J؈s_r Cr_m^mMz_S _|i"zi3uiMiɓir] SiU_z_ mzv ^z ї}WmB^m +mmEmc`m~_~ ~=/GwZZ AnB___/_&;l Z gB_ oB_KkKk JZsw_ B_;[ 1wĖ tnĖ TFĖ~V_ Ė WCB_ GlB_ nB_~^ mB_ mB__ fB_eAFqۮ_!U_/_ /lB_ hB_ nB_ bhB_ `pB__SwO_ gB_S _F_ B_ڢ袼q_q_G_~^X _{7XӴ^I|ZqZ1_-]l]Dv]HS0Vt~0_ B^H/S S~/_{S_r_ B_/_=]KVtn[ ^^t^{{.h3fhehpVt+Vta0m_ lAX= "é7wGwx m vF o &Z &C = nnVtVt ٯZ _5? []u^l^ݽr ~s_s_s S,r_r_zUjW|i K6QS B_^}pZ0|l|l&  ^L uXO y }NZ}xX/ց}49}H\SZ}X Xc\uu}|dnA(O(HT\RTF@`@rXW)}ו}7'!`}N'!`}v!`}W}!`q}!`!`}Oq!`3!`}p!`Vs!`Y!`ɕ!`}R[!`}!`} !`=!`} =!`D3!`}DƆ!`}"Eo!`}&ev!`}&f !`}&m!`}0m!`}6{6}!`}A:!`}Bu }Po*R='RSkb(}k"[}lbya}l9ya}x*a~!!na!aE5!naYaEnF[it}it}[it}rit}w(it}Q}zQyQyQ yQ}2}}7 }!}"!?%lD%ā%n })!}* u90!}9 r9<!H}<!}#>}+G}-I}.K!}/M}1P]}7X!}>`!Ad!H}EdCWs i9\s!}`~a}h}j}}k!}qX}x!}y}}!}ju}` v.!}}} !}<9!}F}})TSSSPS[SSESf!SF!S<SAS=S*=S/SLSwSvSSIS^S$S,S:cSmS~SmSS=S8SSS(SSSzSQWStS"TS S*SAS@]S0S{BSBS[BSc¦S¦S¦S!GSGSFSS9SSLkSjSkSq7S~SSYSSS[SSS8SjSSE9SSfS柦SS.VS㻦SS?S8SSSϣSS0SISkS^S S SSiSGSS|S SjSSߠSS#SSS"SSaSS䐦S㛦S5S_SGS_SS0!S\S=S0zS`"yTŋT$˨TQTmTT^TTچTTe)Te)T1%IT1TچThTRTQ;T;TET'#æ1T1TQT,U1 UQ#1 U1 U1 UUVTVYTVTVHTVbYTV TVHTV?TVXTVTVT_UQYQQWQHU$VQ;UV%UV!%UV,%UV%UVӳ%UR)UR)UQoQ,2j>TmT3C.U3C.UQ9Q-:Q:Q:Vw4v3UR<3U3U3Uʶ3UpU3U_3U!ׂ8U!8U!EU!VUV$V%V#%V+&V1V1Vp1V1V6iUDmUzv}U_qU+vUUUUUV*UV*U[TuUV)UO1A3UU螗UU)U>3UU?UUS:SMS S 12U1?U1LU3d6 U6 U6UQQrQ{1~UUG~UU 38mT}UdUz%TTUVUV+UV?<UUUVV11kGUVOBVVBVV[BVVBVVOBVV=BVV,BVV:cBVVBVV!BVVyBVVٳBVVBVVBVVoBVV,BVVBVV[BVVcBVVBVV9!BVV!BVVqBVVoqBVV{BBVVBBVV[BBVVBVVBVV8BVVtBVVcBVV!BVVBVV9BVVvBVVBVV BVVeBVVރBVVBVVBVVBVV_BVV-BVVE9BVUGV5GV-GV`GVUGV GVu-GV`GVYGV7GVFGVdIGVQQ QrQQQQQiQGQ?QQGQIsLVVGVGV-GVXGVDaGV.GVV6tXV yXgEXX4X@X xX(XXXaXXiYk Y6YnrV6YVrV8HUͲY UY #Y 5Y?YP Y  t  Tw!  yDY  F IY FUOYt!FUt !FUVY!]Y !bY !fY ("*zY$CP<%%SY&sY&ߩY0'kuYd'kuY't,Y'(Y'uY(yY(yY"6(yY%P(yY)(yY-(y Z1)96p)Z6))#Z6)),Z7)69*(#Z;*2<*2<*&w!<*66Z=*ҁ;Z=*Q9=*~@Z=+FZ=+MZ>+TZ?(+ A+-g]ZA,FgfZBK,^CX,(YC`,oZCp,euZD-M~ZF!eZI!eZK-FKZM-FKZP .3ZS.IZW /TZX<1eZ[19t ]1JZ^2bZ`H2xZb2xZd2JZe43!MZf`3bYgl3ZgR4;k [ii4[j4[l4$[o5+/[r"7ß6[tL7@[v\7I[x7=S[{7bY| 8Y[|8eb[~08>T8XKa8^i[n8o[}8l]u[8\u[8zh~[8R[8腎[8o[8(Y8ҁ;Z8 h[!bY9[(9 ;[;A[;G<Ѿ</[<̛b[>Sb[d?[?Qÿ[B$[C1"[D9[F[xF8B[Fdg[F^ 8\Fb[LG Heb[8H>\HXKiH^!xH\Iַ\CIKI TI\IeI!mI!vI<\~I<"\IXt IXt IõoIt Jt JYt .J|Yt @JHt RJeHt dJ`Yt vJDYt Jt Jt Jt Jt J t Jt JHt KHt K=t *K#t Uuw^Uweb[Wwb[XXKYx#b[Y({^Z5{R9Z@{"^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}hu~E<u&~uI~ul~u~u~Ȝu~u~xTu~_u~bYu(_uX46%_u46,_v463_wH46:_xe46A_y46I_{q46P_|Ft }q9t ~7t 7t /W_8F6t E9t R6t _:t lv ]_:S[Ȃ5t ؂p8[] 0h_|bYȃeԃePt_[z__.Ez_Df!z_ZF!z_p<_At_=t_„*=_/_Lt_w_>vz_T_rIz_^z_$z_,_:c_ie ~z_ mt_:t_T=z_j8t_Sz_$ez_z_҆zz_QWt_t_$"Tz_: _X*z_nAt_@]t_0e{Bz_ćBz_ڇ[Bz_cz_z_z_2!Gz_HGz_^Ft_xt_9_eLkz_҈jz_kz_m7e ~t_$z_:Yz_Pz_ft_[___މ8t_jeeE9t_*e6beBeNz_d.Vt_~t_z_?z_Ċ8_t_ z_ ϣt_ ,t_F0z_\Iz_rke~^z_ e eeit_ҋGz_z_xe efe"e.۠e:eFeROe^"ejev]eeeߛe1e_eGeʌ[e֌e0!z_Xe=t_0zz_4`"t_N]_V,_^<_el_l #!h_"R#"΍&_#ݍ^w!%^ &mw((_((5-_*0-_,&-_015-_30-_5&-_9_:T_;6_<ĎN_=> \>08qY?8Kq\?Ku_@S*`@|*`B*-`E*:`GtM`Jl>sj`Ql>sw`T>s`WJ`YFZZMZ[`\0]FE`^gV^o9^zZG^^Ɣ`^)\a :1a%Aa4Aa%`b-̞`b5`b=bEbn`b)^d:>dG>d`eƕ)`eΕ`eؕދ`e8M^`jbYlu alealԙbYmYman<aqȚR(at}xamx&9ax&?ax˛9yӛyܛ8Faz8Qaz {dg|S}؜Sg~0Fa8gSgآ_a,uiaduaDܑa=iaGaaPza QEa,a|iaaܭasa m@b7*b԰\$bx0b'x7b@AbKbXblwbbwzby6b52t @d2bʹy6t ش0b5bq&~UE0Yb}bbY4\MV8qY^Kq\tcbcbcbxbз[bGc<Gc8x-cwe@cz^cչ|cdc4Ec0cHc*c"cܿ "cP{d d){d5.%dM{+d5d6AdLS?HdNd%bYDΐUdwmfdwm}dUd{md md >md>mdL aT#e3#e83#e(re*exX3#eh$1e $#e8$#e "R$#e!Ohd;e"\eBe#eMe%bY't&'}*l*9**Fa+Ve+)ie,Lie.0g1Roe2`oe4D&e7je:&e;Nl<`e<ɤe=De?CeAeB|peC ,eFHeIW@fJŒfLd%fP /=fSL.=fULfW\af\D$fb edGzeen7effg`&EfkDfpfuBgz,$g g&.g:g&9a&?a?a4w! i:w!8;Dgf\8qYKq\u_*Lg*:`b*bg*-`*rg*`*g*`H*ggdgddg*g0hDhI0h8a%h 1h11h` 1h1h?C5h!bYh##wt#-##,е*? #TOSEQ#OZ@hе# #EQw!Ow! Y#xxw#,Rw!$Rw!x!IRw!!ARw!)6RKhD*~#Who*#*ȝ#*Q#+`##H+/# +*w!/# + F^h+FdhY#xw#,Rw!IRw!,&kh:,D,>thw,7#h, ,oh-`-AG-:-.ed-_h-h.h`.@h.fh/+pX/?ph/-h/ h1id2t#i3bY k3G0i 3yDi3r954ZGɳ U E 5 %A G9 w_9 h/9 9 R9 !9 L\9 &B s\9 + [9T4,+Si4c[i4[aiVhiuoi ]:,4bY5 5%05Pbui85`ui@5yauiH5buiP5%9-i9Ux9U99(9-X:-l:`:`:U8;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%&?&DBk&C{{i&CD'C>%'C-i(CU(DU(,DE)DP)D3*D3* E$7+hE37+|E.9,E.,E<-PF<-dFW.FW.Fc/8Gc/TGc0Gc0G<-1(HF-1DH92H2H93I34I94Iѹ4I\95I[95Id\95I\95I0]95J]95J \95.J]95AJ[95TJ35Jci5K?`i6^K]i7pK_S!9Ki;Kmi=K}i>KIi@K$iA L]iB$LǯiCiLLBiMLiNLiOL8iPL/iRL/jSV,jUMsjVMjXPM],j\tM]BjaN] @j\]4j]?j]̩k^᫂Y$`k` a6k@bkb6$kUcbYcc.> pc0c/id+k7d#@d#!td#7kdT>kdTEkdLHOkejOYeURt XfD;\kf AekgE,lkgxkg@ gDkg?kgkgDk-h@kr01l:,Prt)8lrVt ssCl s*Lls *SlssCl4t*LlxudalssClu*LlssClu*Ll:,u_jl:,uqluuGG0v9v w ^wϧw K(wxlkwbswbY:,w w!5-w!0-l&-l5-l0-l&-lwZwbY:,wlw l wG l w~lwlwlTxlxJ)lxlxlxl!x_.#xR.#xbY#:,#w<w!#yyY$8y(ybY(:,(y[(yy[)y<l*z,m+z}m, zR^- z ^.:,/z9 m/:,0(z`0:,05z`0=zbY0:,0Izm0Xz1!GG2tz92\{ N2wϧ2\{ K2d{_m2{b2{2!GG3{93Z| [3wϧ3Z| K3d|$m3|b3|bY3:,3|m3|m4|/m5}6m6}|Am6}Hm7}Om8}EXm9~bm;(~]mm;~uxm=~CAm>~TAm@~>mB4$EBmEBmGmImMmOUQEQ3QCmQȀQ(*R|=UR9RbYR:,R*mR2mS: mTfqmUfmVn{mWv`mX:,Y~H^Y:,ZnZ["\n\W]ƃ.W]ۃv@h^I_|Gn_фbYa:,a|ma|mb|Amc|md|me݄%nf:,h--nhbYi:,iw!i9\w!jT w!koLw!lw!mw!nw!oۅw!pBw!qw!r.w!s+! w!t+ w!u8w!vSw!wn w!xWw!yVw!zw!{چbw!|w!}w!~w!2 w!w! w!چ(w!:,M= w!:,h#}bY:,6n=nFnYn#W Yn0`n@WFn<Yn#z Yn0`nFnYn# Yn0`n8FnYn Yn0`n̉gnDiVhiuoi ɳ UE(57%AFG9Uw_9dh/9s9qR9!9L\9&Bs\9+Ί[9ފ]̉nnDiVhiuoi ɳU(E75%AdG9sw_9Uh/99R9!9ΊL\9-&B=s\9M+][9m]tkunxzn:,|nxzn|nxznbY:,[8nċ:ޤm)BkKkfnUnvBnnn\ni9Jno.nanTnn"nInbY:,ww!bY:,`w!̏GG$9 2 M FnwϧM KX]nb:,w^Jt5Q@<@<@<!X@<mۆȧ.i___+@wwx+qwx+qf,**ӷf,*ӷ*ӷwf,*wf,*wEE| 3@<E2ۆ@O zf)bKZ>ۆKZbKZbKZ&6bKZ&6ExۆcZxbcZbKZ0>OOcZcZcZ_mo_2moLmoӮmoܶ]ikmo2mo S2moܶۆDKZۆhhExQۆu~ +KZKZ%%%(#((#(ۆKZKZP8E,<QQQQ<<<  <<<<<<<<<<<<<<<<<<<<2<#,[yv,%[yv[yv%[yvW:<W:W:<<@<W:G2<W:2<W:2<ٶ<@<<<#<#<#@<Qۆ______Կ__OԿO1TԿۆ$VD -@<E -Dۆk>KZKZȧWE;t2<ȧ!uxȧۆk>AKZKZAKZ=f)TTJTJ̘A8ԿJ QJ NDn,2<2<QQQQQ<E1Zw>Dۆ_k>KZKZ@<ۆ_KZ7KZ7KZ7KZ@KZۆ?KZKZKZKZ>T>EEЯEE|@<@<@<@<@<@< 3@<BB]DxxxxxyXxxܶ@<8888@<@<@<@<E?@<OE@<t@<t_=                  9                                    66D%&D%D%D%&D%D%Q(#)|]R)|]R.XA(#)|]R)|]R.XAQQQQ`qQȧȧڇVVVWyȧVV*ti*ti*tvV)P1AQ)>Qf^R++@+O^wd2~2~ 38*m 382~ 38QQd,4v,4vvv iH~* i;hA i i i i i iE iiH+ i i iQ iB@ iii iii3A ii ib_uEʏ iwU*ڏ iwڏm* *5}2}2K5@<KV@<V@<`qQlWlldldllld=l{=6l{=6l=6ldl6{=T{̨'j66ʷJ(UU#z{D eU4meݙݙdUd eݙݙdlvlݙlvlݙd e# e e e e e# e e e e[y e2 e:,U 3Q͚͚d͚d,4v:,U:,UdDpd& iE iEC i iK iO= i iR iƷDE7ERB7RR iEzWk iiRiY, i i i i>D iRD iRD iR۸  iR۸u~ iu~ i&Q(333`qQVWdVWVWdVWȧdȧȧڇdȧڇVjd[y eVdydVGdjdVjV-*zt3 5QQ:QQQQSQO:QQQQ#######l#s#####wZ%wZQ####LF#LF#P#LFk#:,U:,UKe͚͚͚͚͚ ^/o͚Up ^Go͚<  ԇ"<  ԇ2<QUp͚KeUp͚+Quu!|~QQQQQQQQQQQQu!|~QQQQQQQQQQQQQD]RQ9Q9Q69 999 3f,~--/sP73/s   3 982~f,f,~6d9v{ZwGdvoIGdzvoIw{`Gd zIEpD@D3O O :laEExx/,:1tEu/,/,+@{${`z~O _E_-=QQ"Q"W!|z{I/P5ܶ@<W&6]RǙ_EEF eEE}}GdvvvopvvEZvbE%vEZEvvEZvEZvEZvEZvQQh_}}Q}Q||WW||t3|d||5w8H%(#<<.XA(#ۆ_ۆ_.XA޵ ۆDۆDۆDۆDf)?f)? f)D ۆf)> f)Dۆf)>f)>@<f,*]RSS5w5w5w5w5w5w%8H8H]R]Rd۸۸O EEEEE 5?EEV@<DX''߶5w(QQQ,d]R]R]R]R]R%%%%%%%%%%%%%%%%%%%%%%%%%%%%%''''''''''''uUp͚uuUp͚uW5wQʷ\z>z>%   %  %%8H!16;1==?=N N=NN1N5__=__1_5``=``1`5|&|=|"|1|5  )19AQYaiqy &,A2YaZGi9 FiiKڅXyڅb$F,څX4F<څXDFLڅXa tSP D9;,FUWxU'  9F.!i͗WA]{Weaayi=U'o< a80v |Yqq0qRq7|ixVIKXQAGIAGaIAGj_ A?Yݘ1FdlڅtFd*06d*t9O|څF09ݕrAE)cA{Aص x q!W#^(9.@)9,9F)i9W9fڅF99R20OB9>9)$^0DY+I?>DڅXFGY,M09/U1a:^q&dd)R.99vB96ں9E   xPjv0##cR _R =_(V59^OW0;`&Ә,xU1t $Fj6=!!K1V)vXUݘǠڅF9QQQ+ @ +>D!0i9iA@ FIQM1FSIW[ aI0I2I4A@AA<F֥<<sMG1,! y 1<0@QWAڅ F 9+^G0yS{ YڅF9!z$1 ^!K9 l#Iԝ |uP: QOK)PK Q {y=U6  G S aS af iS څF9G, ' : p9څF9@yM څF9y y y CHSI IPZCHSӸFO I IZCHSӸFO 9oU 0W*Z^S^Z څn  @9!  ! " " H9r9g69H9r9g69=U Y1 ` څF$ӸF$O 9y  \\ \R*\uP \^Z\mw\ < R n,,@4څX<FdGI9q Dҙ2H (Q GW,D^SLcRT^!!ceYZY RZG)!G!wn!h9!-) )$ 9g+91څb9 &) څb909OI1 ;IDSAI!+H9RQG[9+ugQAGYtA\QG!jY_dyi>Dd@lZdڅtFt9|څXFlR*F|,څXFlk,څF9>I+@Gkڅ8 8YP9kڅ8 9ZڅXF9 WAA A&A@?IGE:<2NfYY#_@l/kkQsA G@I,$!K$@!$څ,FYw,94l<څ8D 4@D9irL^lW*l^STڅ\F\9luP GKdW*dZ>DlZuP tluP: duP t@JZ)k|Z|#|xPiwl^Si-ZduP ZZ^SY_I LڅFZ9Ci^Ay[A˺f0 s0 Z^ӍK|^S$*$^kBOxwӸFO *^S==C+Nt^tkZ p =UA'&dam5-FڅXF]~OT$QJ9Q /@il}Y QVa !_q gVHa ڲdv#څn  ӸFO 99s=k ^uyv `M  =U I%Ayyh}Y!ΐY=U1 eG!YZa1(^-9_J^S9g39JYMYW9JAX9=lr9Y6 QQ0Q_QaڅXF$Z,څ4F49<څDFD9L ҽIpXAUa^YYYYpYpYSiYittimQpiݕT^\^i%  !QpD!  M!  _S!A˺Y!aacw!4e G 2d!A&?"L9IAE" =t IP"QG["Qx+b"fkS9x bGs"\<`3,z" ( 1]">/2"1i ,ji)""TAG"H1 D"\."\W#d\#l\-#\d tڅR#|Fd^S\OZ|9\h#dW*\wt#lW*\е*\ #l^SdZlZTT#Tе*T #TEQ#TOS t\kj#t*#W#5-SH#L #L #~!&VTOZ 3 ; AS$څXFA`AAGaoX )x~$!$Y 1v$!ڡ$a $1r9i ;/$5-Sa $ =$   " څF9WL $)W$ 9 39 O %1ZG ZG [%!!3!%Y څbA$%Q 0%Q ^7%>%-E%A$7!3^R%e]h%)sx%)~%qq%q%yy%L#%TڅXFڅXL%IPjI[%QG%LڅF9QxVQ:Qi{ &#ϴQ!Q%&Q9QQT ?5& ?5&QK9QK9QL9QM<&Q KQNQEڅF9^捭&n<#A&w T#T^(QT&|څF څXFz: P#'99PK9"0'5-Q ӸFO QTN'0QT0$څX,F3@'#% ('('4^t(tڅ<F<9) D9 l DڅR#LFL9 TڅR#\F^S\9څdFl Fl d9:9^STxPm)|W*t|tZtW*|Z|uP @0)))IOIO) Qt V)z*id eX *! &dd) *1 9,9\<9`Y* j9 "*څF_9*9ص  dQ99*,$l<**ZZkuP uP ZuP _*Y!u*څXF\W*\^S\Z***9"+9E+ P/+tyS4D+A`$AY\+Q +I 4Q>8><>@2?Dw?H?L@P`@T@X@\!A`fAdAhAl5BpzBtBxB|1C`CCCDHDDDDDEEEE,FgFFF&GIGtGGG7H$H(HTHhHlHpHtHxH|HHHHHHHHIII*IHHHH/I\I}IIIII0JJ4qJ8J<J@KD-KHZKLKPKx*I|HKK=LLHLL *I$H@*IDHHHLHPHMMNN*N3N@NKNvNNN N$O(mO,O0#P4P8P<@QQQQQ QQQQQ Q$Q(Q,Q0Q4Q8Q<Q@QDQHQLRPRT RXR\R`Rd!Rh&Rl+Rp0Rt5Rx:R|?RDRIRNRSRXR]RbRgRlRqRvR{RRRRRRRRRR SS =SZSPySTSXS\S` SdShSlSpTt!TxDT|OTdTTT*I HH*IH H$H(H,H0H4H8H<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.3p.;H.Cp.Kp.Sp.[p.c q.k%q.sEq.{zq.zq.q.q.p.q.q.u.5uCvcvH#v >uC3H H3p3p{p {p# {pC {pc H H H H H H HC Hc H H H H H H H# Hd H kv H H HC Hc H H H H H3pH#HcHHH3paHH H(H!(H*H!*Ha-H ;H@;H`;H;HA3p`BHBHG+HH+H H+H@H+H`H+H I3p@I3p`I3pI3pI3pKuKuL HOHOHTHUHYH YH@YH`YH\H ]H@]H$_HfsHmsHHHH H@H`HHHH H`HHHHHH H`HHHHHH-v$HdHHHHHHHHHĨHz)8lRr)/5j~Eci'hnwd 'bt  C L 9 H N U ^ j s |   & 0 > ] l r  !;,n|{a'p$0UdvDc~ 9?|&4rFh+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~2348:;=>?@NV_`ceipqrx| >toDFoo,oW)oo%o2o2oW)oց.oQ%o~3o _9oW)o _?oREoІKoW)oց.ohEo _Po _Vooo #oE\o,oEao _qoo _woE}o _o<o %oRo|RoW1o1o%o%o0o%<oE:o _o _o _oV%ol}oI<}o}o}o}o}o̜}o}oiU}o_}ooomo(o0ooq7ojooofo柡oko o oo|o ojooߠoo#oSo"ooaoo䐡o㛡o5o_oGo_oo\olo _oӳoOqovoVo%o)qo>1oA}ooОoo)o>}oo-oood~Po}mob(o%oVoo:<oopOqood~Pomp%o(oOqovo" ppDF$p:o2e*p/p0pCp6pͳoVoo!5oAoG%o{_%ol/%o%oS%ot9oP\%oABow\%o+o[%o]oTbY?[@[A]B]C_D_EaFaGcHcIeJeKgLgMiNi[k\m]o^q_s`uawbyc{d}efgopqrstuvwxyz{|}~78SU[]epvwxy}        $&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~!Zc7 >08LU=E1 ; D X a m K _ z u~&p  ,DWcodQZf}CsW` ;OY%/@} "+4=^S]G \ !""" ###H#^#####$7$@$O$$%%&a&j&&&'''''''$((((((())0*F*\*r*|******K+w++++,),!`,u,_,2,E,],  ,j,7w,nO<|LMNO P QRSTUVWX%Y'Z'['\,],^,_,`,a.b1c1d1e1f1g1h1i3j3k3l6m6n9o:p;q;r;s;t;uBvBwDxDyEzK{c|c}xhh J^ 7-q}}/W / , qq*,/,5,c,,,,aae g   ,Ce , f, OO  "a%" "9"C  ,#  f.$,f/B&',',K( C **i U+k U+k +o o +6 6+<>9__31_10b__31_10b__29_10d__20<>c__DisplayClass20_0<>9__0_0<.ctor>b__0_0<>c__DisplayClass0_0<>9__11_0b__11_0<>c__DisplayClass11_0<>9__31_0b__31_0<>c__DisplayClass31_0<>9__41_0b__41_0b__41_0<>c__DisplayClass51_0<>9__1_0b__1_0<>9__12_0<.cctor>b__12_0b__12_0<>9__22_0b__22_0<>9__13_0b__13_0b__13_0b__13_0<>9__53_0b__53_0<>9__14_0b__14_0<>9__4_0b__4_0<>9__15_0b__15_0b__15_0<>c__DisplayClass15_0<>9__55_0b__55_0<>9__5_0<.ctor>b__5_0<>9__16_0b__16_0<>c__DisplayClass16_0<>9__6_0b__6_0<>9__37_0b__37_0<>9__7_0b__7_0<>9__18_0<.ctor>b__18_0<>9__38_0b__38_0<>c__DisplayClass38_0<>9__29_0b__29_0<>9__39_0b__39_0<>9__9_0b__9_0<>c__DisplayClass9_0<>9__0b__0b__0b__0b__0b__0b__0b__0p0constraint0<>9__31_11b__31_11<>9__29_11b__29_11T1EdmxNamespaceUriV1MementoV1FunctionDetailsReaderV1get_UnableToGenerateForeignKeyPropertiesForV1<>9__31_1b__31_1<>c__DisplayClass51_1get_EdmVersion1_1<>9__12_1<.cctor>b__12_1b__12_1<>9__13_1b__13_1<>9__53_1b__53_1<>9__14_1b__14_1<>9__4_1b__4_1<>9__15_1b__15_1<>9__55_1b__55_1<>9__38_1b__38_1<>9__29_1b__29_1<>9__39_1b__39_15__1b__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_12b__29_12b__12Int32T2VBTemplateCodeGenResourceV2CSharpTemplateCodeGenResourceV2_vbCodeGeneratorTypeV2_csharpCodeGeneratorTypeV2EdmxNamespaceUriV2CreateVBCodeGeneratorV2CreateCSharpCodeGeneratorV2<>9__31_2b__31_2<>9__12_2<.cctor>b__12_2b__12_2<>9__13_2b__13_2<>9__14_2b__14_2<>9__15_2b__15_2<>9__29_2b__29_2<>9__39_2b__39_2b__2Func`2Tuple`2Memoizer`2KeyValuePair`2BidirectionalDictionary`2get_Template_GeneratedCodeCommentLine2get_Item2Version2<>7__wrap2str2<>m__Finally2<>9__31_13b__31_13<>9__29_13b__29_13d__3390EEE9F1BE125B634A197AA7BD83E6811BE8B6F3VBTemplateCodeGenResourceV3CSharpTemplateCodeGenResourceV3_vbCodeGeneratorTypeV3_csharpCodeGeneratorTypeV3EdmxNamespaceUriV3MementoV3FunctionDetailsReaderV3CreateVBCodeGeneratorV3CreateCSharpCodeGeneratorV3<>9__31_3b__31_3<>9__12_3<.cctor>b__12_3b__12_3<>9__13_3b__13_3<>9__14_3b__14_3<>9__15_3b__15_3<>9__38_3b__38_3<>9__29_3b__29_3<>9__39_3b__39_3Func`3get_Template_GeneratedCodeCommentLine3StoreSchemaMappingVersion3StoreSchemaDefinitionVersion3ConceptualSchemaDefinitionVersion3p3<>9__31_14b__31_14Int64<>9__31_4b__31_4<>9__38_4b__38_4<>9__29_4b__29_4<>9__39_4b__39_4p4<>9__31_5b__31_5<>9__29_5b__29_5Action`5p5__StaticArrayInitTypeSize=6<>9__31_6b__31_6<>9__29_6b__29_6<>9__31_7b__31_7<>9__29_7b__29_7d__28get_UTF8<>9__31_8b__31_8<>9__29_8b__29_8d__29<>9<>9__31_9b__31_9<>9__29_9b__29_9FK_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_guidk__BackingFieldk__BackingFieldk__BackingFieldk__BackingFieldk__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.GetEnumeratorSystem.Collections.Generic.IEnumerable.GetEnumeratorSystem.Collections.Generic.IEnumerable.GetEnumeratorSystem.Collections.Generic.IEnumerable.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.CurrentSystem.Collections.Generic.IEnumerator.CurrentSystem.Collections.Generic.IEnumerator.CurrentSystem.Collections.Generic.IEnumerator.CurrentSystem.Collections.IEnumerator.CurrentSystem.Collections.Generic.IEnumerator.get_CurrentSystem.Collections.Generic.IEnumerator.get_CurrentSystem.Collections.Generic.IEnumerator.get_CurrentSystem.Collections.Generic.IEnumerator.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!OnContextCreated name=!connectionString!EntityConnectionconnectionObjectQueryCreateQuery[] AddToAddObjectExecuteFunctionParameterHasValue<KeyProperties>!</KeyProperties>public abstractpartial'Public MustOverridePartial Private End Suboverride sealedOverridesNotOverridablesetinternalSet FriendgetprivateGetPrivateprotectedProtected public Public static classstatic  {}// class @ ClassEnd Class!MustOverride SubFunctionSubPropertyEnd PropertyEnd SubEnd FunctionEnd GetEnd Set GetterAccessSetterAccessMethodAccessTypeAccessInternaleSystem.Data.Objects.DataClasses.EdmSchemaAttributeReference5InitializeRelatedReference'RelationshipManager Value7InitializeRelatedCollectionEntityReference!EntityCollection'GetRelatedReference)GetRelatedCollection valueGetValidValue-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 writerhttp://schemas.microsoft.com/ado/2009/02/edm/annotation:LazyLoadingEnabledannotationohttp://schemas.microsoft.com/ado/2009/02/edm/annotationReturnType_ResultApplication Target ModelContext+StoreGeneratedPatternhttp://schemas.microsoft.com/ado/2009/02/edm/annotation:StoreGeneratedPattern types?Edm_EntityMappingGeneratedViewscSystem.Data.Mapping.EntityViewGenerationAttribute-ViewsForBaseEntitySetsOSystem.Data.Mapping.EntityViewContainer-EdmEntityContainerName1StoreEntityContainerName-HashOverMappingClosure-HashOverAllExtentViewsViewCountGetViewAt<Summary></Summary>#mappingCollectionoutputPathoutputWriter indexGetViewToStringviewString AppendedmCollectionstoreCollectionreaders-entityFrameworkVersiondataSpace Edmx+providerInvariantNamefiltersContainer storehttp://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator Type Tables Views nullNullablePrecision ScaleMaxLength Schema{0}({1})_TemplateCodeGenerators.CSharpCodeGenTemplate.csYTemplateCodeGenerators.CSharpCodeGenTemplategTemplateCodeGenerators.CSharpCodeGenTemplateV5.0.cs_TemplateCodeGenerators.CSharpCodeGenTemplateV50WTemplateCodeGenerators.VBCodeGenTemplate.vbQTemplateCodeGenerators.VBCodeGenTemplate_TemplateCodeGenerators.VBCodeGenTemplateV5.0.vbWTemplateCodeGenerators.VBCodeGenTemplateV501/d:PREPROCESSED_TEMPLATE fishois sheep deerpos itisism bisonflounder pliers breamgallowsproceedingsbreechesgraffiti rabiesbritchesheadquarters salmon carp herpesscissorschassishigh-jinkssea-bassclippershomework seriescodinnings shearscontretempsjackanapesspecies corpsmackerel swine debrismeasles troutdiabetes mews tuna djinn mumpswhiting eland newswildebeestelkpincers police hairice chaos milk cotton[pneumonoultramicroscopicsilicovolcanoconiosisinformationaircraftscabiestraffic corn millet ricehay hemptobaccocabbage okrabroccoliasparaguslettuce beef porkvenison mutton cattleoffspringmolassesshamblesshinglesamareiswas werehas haveIweyouheshe theyitmeushimher them myselfourselvesyourselfhimselfherself itselfoneselfoneselvesmyour yourhis theirits mine yours hers theirs this that these thoseallanotheranyanybody anyoneanything both each other eithereveryoneeverybodyeverything most muchnothing nobody noneone others somesomebodysomeonesomething whatwhatever whichwhicheverwhowhoever whomwhomever whosebrotherbrothers childchildrencow cowsephemerisephemerides genie genies money moneysmongoosemongooses mythos mythoioctopusoctopusesox oxensoliloquysoliloquies trilbytrilbys crisis crisessynopsissynopses rose rosesgas gasesbus buses axis axes memo memos casinocasinos silo silos stereostereos studiostudios lens lenses aliasaliasespie pies corpuscorpora viscusviscerahippopotamushippopotami trace traces person people chilichiliesanalysisanalyses basis basesneurosisneuroses oasis oasessynthesissyntheses thesis theses changechangeslie liescaloriecaloriesfreebiefreebies case cases house houses valve valves clothclothestie ties movie movies bonusbonusesspecimenspecimens alumnaalumnae alga algaevertebravertebrae codexcodices murexmurices silexsilicesaphelionapheliahyperbatonhyperbataperihelionperiheliaasyndetonasyndetanoumenonnoumenaphenomenonphenomenacriterioncriteriaorganon organaprolegomenonprolegomenaagendum agenda datum dataextremumextremabacteriumbacteriadesideratumdesideratastratum stratacandelabrumcandelabraerratum errata ovumova forum foraaddendumaddendastadium stadiaautomatonautomatapolyhedronpolyhedra albinoalbinosgeneralissimogeneralissimosmanifestomanifestosarchipelagoarchipelagos ghettoghettos medicomedicosarmadilloarmadillos guano guanos octavooctavoscommandocommandosinfernoinfernos photo photos ditto dittos jumbo jumbospro pros dynamodynamos lingo lingos quartoquartos embryoembryoslumbagolumbagos rhino rhinos fiascofiascosmagnetomagnetos stylo stylos stamenstaminaforamenforamina lumen luminaanathemaanathemata enemaenemata oedemaoedemata bema bemata enigmaenigmatasarcomasarcomatacarcinomacarcinomata gummagummata schemaschematacharismacharismata lemmalemmata soma somatadiplomadiplomatalymphomalymphomata stigmastigmata dogmadogmata magmamagmata stomastomata dramadramatamelismamelismata traumatraumata edemaedemata miasmamiasmataabscissaabscissaeformulaformulae medusamedusae amoebaamoebae hydra hydrae nebulanebulaeantennaantennaehyperbolahyperbolae nova novae auroraaurorae lacunalacunaeparabolaparabolae apex apices latexlatices vertexvertices cortexcorticespontifexpontifices vortexvorticesindicessimplexsimplices iris iridesclitorisclitorides alto alticontraltocontraltisopranosoprani basso bassicrescendocrescendi tempo tempi canto canti solo soliaquariumaquariainterregnuminterregnaquantum quantacompendiumcompendialustrum lustrarostrum rostraconsortiumconsortiamaximum maximaspectrumspectracranium crania medium mediaspeculumspeculacurriculumcurriculamemorandummemoranda dictum dictamilleniummilleniatrapeziumtrapeziaemporiumemporiaminimum minimaultimatumultimataenconiumenconiamomentummomenta vacuum vacuagymnasiumgymnasiaoptimum optima velum velahonorariumhonoraria phylum phyla focus foci nimbus nimbisuccubussuccubi fungus funginucleolusnucleoli torus tori genius genii radius radiiumbilicusumbiliciincubus incubi stylus styli uterus uteristimulusstimuliapparatusimpetusprospectus cantus nexus sinus coitus plexus status hiatus afreetafreeti afrit afriti efreetefreeti cherubcherubimgoy goyim seraphseraphimalumnus alumnienterpriseenterprisespurchasepurchasessurprisesurprisesreleasereleasesdiseasediseasespromisepromises refuserefuses whoses phase phases noise noises nurse nursesfranchisefranchisessupervisesupervisesfarmhousefarmhousessuitcasesuitcasesrecourserecoursesimpulseimpulseslicenselicensesdiocesedioceses exciseexcises demisedemises blouseblouses bruisebruises misusemisuses curse curses prose proses purse purses goose gooses tease teases poise poises vase vases fuse fuses muse musesslaughterhouseslaughterhousesclearinghouseclearinghousesendonucleaseendonucleasessteeplechasesteeplechasesmetamorphosemetamorphosesintercourseintercoursescommonsensecommonsensesintersperseinterspersesmerchandisemerchandisesphosphatasephosphatasessummerhousesummerhouseswatercoursewatercoursescatchphrasecatchphrasescompromisecompromisesgreenhousegreenhouseslighthouselighthousesparaphraseparaphrasesmayonnaisemayonnaisesracecourseracecoursesapocalypseapocalypsescourthousecourthousespowerhousepowerhousesstorehousestorehousesglasshouseglasshouseshypotenusehypotenusesperoxidaseperoxidasespillowcasepillowcasesroundhouseroundhousesstreetwisestreetwisesexpertiseexpertisesdiscoursediscourseswarehousewarehousesstaircasestaircasesworkhouseworkhousesbriefcasebriefcasesclubhouseclubhousesclockwiseclockwisesconcourseconcoursesplayhouseplayhousesturquoiseturquoisesboathouseboathousescellulosecellulosesepitomiseepitomisesgatehousegatehousesgrandiosegrandiosesmenopausemenopausespenthousepenthousesracehorseracehorsestransposetransposesalmshousealmshousescustomisecustomisesfootloosefootloosesgalvanisegalvanisesprincesseprincessesuniverseuniversesworkhorseworkhorsesatherosclerosisatheroscleroseselectrophoresiselectrophoresespsychoanalysispsychoanalysesphotosynthesisphotosynthesesamniocentesisamniocentesesmetamorphosistoxoplasmosistoxoplasmosesendometriosisendometriosestuberculosistuberculosespathogenesispathogenesesosteoporosisosteoporosesparenthesisparenthesesanastomosisanastomosesperistalsisperistalseshypothesishypothesesantithesisantithesesapotheosisapotheosesthrombosisthrombosesdiagnosisdiagnosesparalysisparalysesprognosisprognosescirrhosiscirrhosessclerosissclerosespsychosispsychosesapoptosisapoptosessymbiosissymbiosesconsensusconsensuses censuscensuses sphinxsphinxes larynxlarynges lynx lynxespharynxpharynxesphalanxphalanxesen wordman louse mouse tooth foot zooncissisxis trixeauieuchshssalfelfolfeafarf nife life wifeayeyiyoyuyyiesaoeoiooouoosesxmen lice mice teeth geese feetzoa ches shes sses trices eaux ieux alves elves olves eaves arves nives lives wivesayseysiysoysuysaoseosiosoosuoscessesxesoes[^a-zA-Z\s]esesingular plural deafvescultureAND() NOT ( WHERECatalogNameSchemaName% OR AND  LIKE @pvm 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 to 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 tvfE 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 INOUT INOUTsp 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=GetAssociatedFacetDescriptionsNamespace Alias Self+UseStrongSpatialTypes falseProvider+ProviderManifestToken xmlnsEntityContainer%LazyLoadingEnabledAssociationSetEntitySetDefiningQuery TableCollection({0})factoryGetService, {0}& &amp;< &lt;> &gt;' &apos;" &quot;lookupsstoreContainermodelContainer-EntityContainerMapping-StorageEntityContainer%CdmEntityContainer+FunctionImportMappingFunctionName%FunctionImportNameResultMapping%ComplexTypeMappingTypeName+AssociationSetMappingStoreEntitySetCondition IsNullEndProperty!EntitySetMapping#EntityTypeMappingMappingFragmentScalarPropertyMapping SpaceC-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 ~`B&U     %   e m  9   9 54999y            -          0        ) 0 0    4         %)%)         MM MM  - Y ] %   %U]]9%]9]]q]  ]5 9  ]]q U U  E U U U      Y    e a    q%  UuUAa%Im  y % } } e  a      U  %  %% m%]qq %  U% U UU U  UU3 %UUU  AUUU %U U %H 0 Ia a@ ) 4444 4   44D H44HH 4944494D49444 HH   )    ' ] 9XI     I IPLPL PL m i;%mUUq Uq  %Um %mq  U q!U! X%) ))- U       15 55qe e  %aIP P%=AP%EUU %U % I% M%IM%M%%IM%% M%   M% %%> QMUUUUYM  UQM Y Y M aa a aa  -MMM M   ttt  txxx x u 'yy9uuy u uyu9u: yy}9y yq4 yuuu y yu uyu 'u- u    & `u5551u            `        d99EEE   E 9 9 - % %       EE EE EE MM0 9l%9      % %AQQ    %*   H     E   / E  % %     EYM  E M M  E  M MM$ EMYiMM iii MY  MY  MM ii  % i Y  M I IY   p   t ,9 9   q     B9Q]a  5 5 MYM Y M+ AYM  U 9=   Ua    u u        I  @!%)-9EE%)% ! - %-9 EE%)!59 ! 5!?uuu5-5 u  u  0 e}9iMH%%A%U %U9EE9EBYMYME99 E E9  i   IM!Mq!9E H9qq   G9)))Q))))9 m m m)% m) ) m )m QQm%)5U UU!5Yuuu u']Maaee ]aMa i ma MaqMa u]a 5a % y}   #9uuu  u u.  = q q q|  u  uy  yu } q q                     91   9EEE     E E                 9 3 99 9    -%%  ii q  % )m))m9mm)m9m)a aQMM 9 9  9) % =51 9 9uu P      Y!      ' u9      08 P %% |     0   99 )Q aQ!% Q!%  q q E E E E E   -yyz\V4?_ :FEntityStoreGeneratorSchemaNotLoadedFEntityModelGeneratorSchemaNotLoaded:StonglyTypedAccessToNullValue&NoPrimaryKeyDefined0InvalidTypeForPrimaryKeyRCannotCreateEntityWithNoPrimaryKeyDefinedNTableReferencedByAssociationWasNotFound>TableReferencedByTvfWasNotFound&UnsupportedDataTypeSerialization_UnknownGlobalItem"ReservedNamespace4ColumnFacetValueOutOfRange6AssociationMissingKeyColumnDSingleStoreEntityContainerExpectedCodeGenSourceFilePathIsNotAFile>InvalidAttributeSuppliedForType8InvalidMemberSuppliedForType>InvalidInterfaceSuppliedForTypeFInvalidAttributeSuppliedForPropertyLInvalidGetStatementSuppliedForPropertyLInvalidSetStatementSuppliedForProperty>PropertyExistsWithDifferentCase@EntitySetExistsWithDifferentCase6ItemExistsWithDifferentCase(NullAdditionalSchema$DuplicateClassNamepTargetEntityFrameworkVersionToNewForEntityClassGenerator8MissingPropertyDocumentation>MissingComplexTypeDocumentation(MissingDocumentation4MissingDocumentationNoName"NamespaceComments6FactoryMethodSummaryComment4FactoryParamCommentGeneral$CtorSummaryComment.EmptyCtorSummaryCommentNGeneratedNavigationPropertyNameConflictLGeneratedPropertyAccessibilityConflictJEntityTypeAndSetAccessibilityConflictDGeneratedFactoryMethodNameConflictNMetadataItemErrorsFoundDuringGenerationRUnableToGenerateForeignKeyPropertiesForV1VUnableToGenerateFunctionImportParameterNameTypeComments.GetViewAtMethodComments&ConstructorComments,IndividualViewCommentsDTargetVersionSchemaVersionMismatchTemplate_CommentNoDocumentationDTemplate_CommentFactoryMethodParamDTemplate_GeneratedCodeCommentLine1DTemplate_GeneratedCodeCommentLine2DTemplate_GeneratedCodeCommentLine3DTemplate_ContextDefaultCtorCommentBTemplate_ContextCommonCtorComment:Template_FactoryMethodComment8Template_RegionRelationships.Template_RegionContextsDTemplate_RegionObjectSetProperties6Template_RegionAddToMethodsTemplate_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 ModelApplicationhttp://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| `]uU<@4y PLL% I%IM%IM%%Mptx  ]  e` 1  <DHT\  E h    x  E   i         E m m)qa q   E EEE     EE MM    y  |        `         % % 8  )   E QM UY ` 0a a \a Xa Xa e im] e Pm] $a ]] m y}y} } } }} }  a  U U%U       m   U    <  < <    D  4HH  4 y yy y     X  mi )  %ii i  m% a%`  m] m  8 0U %%  U U U m% %% y  a] a ae    a%% % %% % % %M %% %% %M% %%MU]eiiL - )  q        t x p u uu   yy       y%  ] %  e          d  d d d d d d d d % d d d EdE MYdEE dEE  dE dMM  MdMMY MdMY             a  A A auuuuuu    u  1 15)!5   E     %   MY EMME2 EMq q'  q  5 5 M   u uu  u  u  u q        1  E 10 EEE1  1 1 A     E    99q 9  = = M" M    E  i  Y   % )m ) m  % %  M   y  = = =  u               y     9   X  X ` ` ` %`% ` %`%     9 9     i         q     E  m )m    q q   EE 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.3761.0 4.0.0.0 en-US)$f:\dd\tools\devdiv\EcmaPublicKey.snkH@002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a235e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f302d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd911f0571aaf3d54da12b11ddec375b3a5a866e1ee186f807668209f3b11236ace5e21f117803a3143abb126dd035d7d2f876b6938aaf2ee3414d5420d753621400db44a49c486ce134300a2106adb6bdb433590fef8ad5c43cba82290dc49530effd86523d9483c00f458af46890036b0e2c61d077d7fbac467a506eba29e467a87198b053c749aa2a4d2840c784e6dTWrapNonExceptionThrowsE@System.Data.EntityModel.ClientApiGenerator+d__33JESystem.Data.Entity.Design.EntityViewGenerator+d__28]XSystem.Data.Entity.Design.EntityViewGenerator+d__29b]System.Data.Entity.Design.EntityStoreSchemaGenerator+LoadMethodSessionState+d__20 Item94Catalog={Catalog}, Schema={Schema}, Name={TableName}OlSystem.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089#System.Resources.RuntimeResourceSettPADPADP/8mmmD77O^<͎!fKU̧D_G[|ջyDS c,s&a= &°E{[apwܠsc="Dmq͒ NiƹOX:(? ڴ(h{!L搠O"yNE <>v:n xT1EGW5> 4V q IBv6RkKyjP8! >$t*2+,.ٺ/(16q30!48,:Sv&CodeGenSourceFilePathIsNotAFile14ColumnFacetValueOutOfRangej&ConstructorComments$CtorSummaryCommentRDbProviderServicesInformationLocationPath4DefaultTargetVersionTooLow$DuplicateClassNameT8DuplicateEntityContainerNameInvalidAttributeSuppliedForTypeDInvalidEntityContainerNameArgumentNLInvalidGetStatementSuppliedForProperty>InvalidInterfaceSuppliedForType8InvalidMemberSuppliedForType,8InvalidNamespaceNameArgumentiMissingComplexTypeDocumentation(MissingDocumentation4MissingDocumentationNoNameE8MissingPropertyDocumentationkBModelGeneration_UnGeneratableType"NamespaceComments&NoPrimaryKeyDefined(NullAdditionalSchema4ParameterDirectionNotValid>PropertyExistsWithDifferentCasenDProviderFactoryReturnedNullFactory(ProviderSchemaErrors?"ReservedNamespace>Serialization_UnknownGlobalItem SharedForeignKeyDSingleStoreEntityContainerExpected:StonglyTypedAccessToNullValue<NTableReferencedByAssociationWasNotFoundr>TableReferencedByTvfWasNotFoundpTargetEntityFrameworkVersionToNewForEntityClassGeneratorDTargetVersionSchemaVersionMismatchRTemplate_CaseInsensitiveEntitySetConflict LTemplate_CaseInsensitiveMemberConflictHTemplate_CaseInsensitiveTypeConflictDTemplate_CommentFactoryMethodParam>Template_CommentNoDocumentationPTemplate_ConflictingGeneratedNavPropNameBTemplate_ContextCommonCtorCommentqDTemplate_ContextDefaultCtorCommentBTemplate_CurrentlyRunningTemplate Template_RegionSimpleProperties!FTemplate_ReplaceVsItemTemplateToken"4Template_UnsupportedSchema"TypeCommentsJ#RUnableToGenerateForeignKeyPropertiesForV1#VUnableToGenerateFunctionImportParameterName $,UnmappedFunctionImport$&UnsupportedDataTypeB%8UnsupportedDataTypeForTarget%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 TemplateThe 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<T> 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 PropertiesPlease 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.)// ------------------------------------------------------------------------------ // // 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. // // ------------------------------------------------------------------------------ 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; /// /// Class to produce the template output /// [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "11.0.0.0")] public partial class CSharpCodeGenTemplate : CSharpCodeGenTemplateBase { /// /// Create the template output /// 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// \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(@" // //------------------------------------------------------------------------------ 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()) { 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()) { this.Write("\r\n/// \r\n/// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(container))); this.Write("\r\n/// "); 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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_ContextDefaultCtorComment"), container.Name, container.Name))); this.Write("\r\n /// \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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_ContextCommonCtorComment"), container.Name))); this.Write("\r\n /// \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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_ContextCommonCtorComment"), container.Name))); this.Write("\r\n /// \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()) { VerifyEntityTypeAndSetAccessibilityCompatability(set); this.Write("\r\n /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(set))); this.Write("\r\n /// "); 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 addToMethods = CreateContextAddToMethods.Value ? container.BaseEntitySets.OfType() : Enumerable.Empty(); foreach (EntitySet set in addToMethods) { string parameterName = code.Escape(FixParameterName(set.ElementType.Name, code)); this.Write("\r\n /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_GenCommentAddToMethodCs"), set.Name))); this.Write("\r\n /// \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 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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(edmFunction))); this.Write("\r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel))); this.Write(this.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(p => new Tuple(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(" /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(edmFunction))); this.Write("\r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel))); this.Write("\r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(p => new Tuple(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().OrderBy(e => e.Name)) { this.Write("\r\n/// \r\n/// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(entity))); this.Write("\r\n/// "); 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().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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(navProperty))); this.Write("\r\n /// "); 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(" /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(navProperty))); this.Write("\r\n /// "); 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().OrderBy(c => c.Name)) { this.Write("\r\n/// \r\n/// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(complex))); this.Write("\r\n/// "); 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 parameters = FactoryMethodParameter.CreateParameters(structuralType.Members.OfType().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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_FactoryMethodComment"), structuralType.Name))); this.Write("\r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(p => new Tuple(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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(primitiveProperty))); this.Write("\r\n /// "); 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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(complexProperty))); this.Write("\r\n /// "); 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 ReferenceCsdlPaths{ get; set; } public Nullable CreateContextAddToMethods{ get; set; } public Dictionary EdmToObjectNamespaceMap { get { return _edmToObjectNamespaceMap; } set { _edmToObjectNamespaceMap = value; } } public Dictionary _edmToObjectNamespaceMap = new Dictionary(); 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 hash = new HashSet(); IEnumerable allTypes = GetSourceSchemaTypes().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 GetSourceSchemaTypes() where T : GlobalItem { if (Path.GetExtension(SourceCsdlPath) != ".edmx") { return ItemCollection.GetItems().Where(e => e.MetadataProperties.Any(mp => mp.Name == "SchemaSource" && (string)mp.Value == SourceCsdlPath)); } else { return ItemCollection.GetItems(); } } 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 CreateParameters(IEnumerable properties, UniqueIdentifierService unique, Func multiSchemaEscape, CodeGenerationTools code) { List parameters = new List(); 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 + "" + Environment.NewLine; comment += lineStart + PrefixLinesOfMultilineComment(lineStart, XmlEntityize(item.Documentation.LongDescription)) + Environment.NewLine; comment += lineStart + ""; return comment; } return string.Empty; } string PrefixLinesOfMultilineComment(string prefix, string comment) { return comment.Replace(Environment.NewLine, Environment.NewLine + prefix); } string ParameterComments(IEnumerable> parameters, int indentLevel) { System.Text.StringBuilder builder = new System.Text.StringBuilder(); foreach (Tuple parameter in parameters) { builder.AppendLine(); builder.Append(CodeRegion.GetIndent(indentLevel)); builder.Append(XMLCOMMENT_START); builder.Append(String.Format(CultureInfo.InvariantCulture, " {1}", parameter.Item1, parameter.Item2)); } return builder.ToString(); } string XmlEntityize(string text) { if (string.IsNullOrEmpty(text)) { return string.Empty; } text = text.Replace("&","&"); text = text.Replace("<","<").Replace(">",">"); string id = Guid.NewGuid().ToString(); text = text.Replace(Environment.NewLine, id); text = text.Replace("\r", " ").Replace("\n"," "); text = text.Replace(id, Environment.NewLine); return text.Replace("\'","'").Replace("\"","""); } const string XMLCOMMENT_START = "///"; IEnumerable 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 _knownIdentifiers; public UniqueIdentifierService() { _knownIdentifiers = new HashSet(StringComparer.Ordinal); } /// /// /// /// 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 TemplateMetadata = new Dictionary(); /// /// Responsible for helping to create source code that is /// correctly formated and functional /// public class CodeGenerationTools { private readonly DynamicTextTransformation _textTransformation; private readonly CSharpCodeProvider _code; private readonly MetadataTools _ef; /// /// Initializes a new CodeGenerationTools object with the TextTransformation (T4 generated class) /// that is currently running /// 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; } /// /// 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. /// public bool FullyQualifySystemTypes { get; set; } /// /// When true, the field names are Camel Cased, /// otherwise they will preserve the case they /// start with. /// /// Default is true. /// public bool CamelCaseFields { get; set; } /// /// Returns the NamespaceName suggested by VS if running inside VS. Otherwise, returns /// null. /// public string VsNamespaceSuggestion() { string suggestion = _textTransformation.Host.ResolveParameterValue("directiveId", "namespaceDirectiveProcessor", "namespaceHint"); if (String.IsNullOrEmpty(suggestion)) { return null; } return suggestion; } /// /// Returns a string that is safe for use as an identifier in C#. /// Keywords are escaped. /// public string Escape(string name) { if (name == null) { return null; } return _code.CreateEscapedIdentifier(name); } /// /// Returns the name of the TypeUsage's EdmType that is safe for /// use as an identifier. /// 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"); } /// /// Returns the name of the EdmMember that is safe for /// use as an identifier. /// public string Escape(EdmMember member) { if (member == null) { return null; } return Escape(member.Name); } /// /// Returns the name of the EdmType that is safe for /// use as an identifier. /// public string Escape(EdmType type) { if (type == null) { return null; } return Escape(type.Name); } /// /// Returns the name of the EdmFunction that is safe for /// use as an identifier. /// public string Escape(EdmFunction function) { if (function == null) { return null; } return Escape(function.Name); } /// /// Returns the name of the EnumMember that is safe for /// use as an identifier. /// public string Escape(EnumMember member) { if (member == null) { return null; } return Escape(member.Name); } /// /// Returns the name of the EntityContainer that is safe for /// use as an identifier. /// public string Escape(EntityContainer container) { if (container == null) { return null; } return Escape(container.Name); } /// /// Returns the name of the EntitySet that is safe for /// use as an identifier. /// public string Escape(EntitySet set) { if (set == null) { return null; } return Escape(set.Name); } /// /// Returns the name of the StructuralType that is safe for /// use as an identifier. /// public string Escape(StructuralType type) { if (type == null) { return null; } return Escape(type.Name); } /// /// Returns the NamespaceName with each segment safe to /// use as an identifier. /// 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; } /// /// Returns the name of the EdmMember formatted for /// use as a field identifier. /// /// This method changes behavior based on the CamelCaseFields /// setting. /// public string FieldName(EdmMember member) { if (member == null) { return null; } return FieldName(member.Name); } /// /// Returns the name of the EntitySet formatted for /// use as a field identifier. /// /// This method changes behavior based on the CamelCaseFields /// setting. /// 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; } } /// /// Returns the name of the Type object formatted for /// use in source code. /// /// This method changes behavior based on the FullyQualifySystemTypes /// setting. /// public string Escape(Type clrType) { return Escape(clrType, FullyQualifySystemTypes); } /// /// Returns the name of the Type object formatted for /// use in source code. /// 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; } /// /// Returns the abstract option if the entity is Abstract, otherwise returns String.Empty /// public string AbstractOption(EntityType entity) { if (entity.Abstract) { return "abstract"; } return String.Empty; } /// /// Returns the passed in identifier with the first letter changed to lowercase /// 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); } /// /// 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. /// public string SpaceAfter(string value) { return StringAfter(value, " "); } /// /// 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. /// public string SpaceBefore(string value) { return StringBefore(" ", value); } /// /// If the value parameter is null or empty an empty string is returned, /// otherwise it retuns value with append concatenated on the end. /// public string StringAfter(string value, string append) { if (String.IsNullOrEmpty(value)) { return String.Empty; } return value + append; } /// /// If the value parameter is null or empty an empty string is returned, /// otherwise it retuns value with prepend concatenated on the front. /// public string StringBefore(string prepend, string value) { if (String.IsNullOrEmpty(value)) { return String.Empty; } return prepend + value; } /// /// Returns false and shows an error if the supplied type names aren't case-insensitively unique, /// otherwise returns true. /// public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable types, string sourceFile) { return VerifyCaseInsensitiveUniqueness(types, t => string.Format(CultureInfo.CurrentCulture, GetResourceString("Template_CaseInsensitiveTypeConflict"), t), sourceFile); } /// /// Returns false and shows an error if the supplied strings aren't case-insensitively unique, /// otherwise returns true. /// private bool VerifyCaseInsensitiveUniqueness(IEnumerable items, Func formatMessage, string sourceFile) { HashSet hash = new HashSet(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; } /// /// Returns the names of the items in the supplied collection that correspond to O-Space types. /// public IEnumerable GetAllGlobalItems(EdmItemCollection itemCollection) { return itemCollection.GetItems().Where(i => i is EntityType || i is ComplexType || i is EnumType || i is EntityContainer).Select(g => GetGlobalItemName(g)); } /// /// Returns the name of the supplied GlobalItem. /// public string GetGlobalItemName(GlobalItem item) { if (item is EdmType) { return ((EdmType)item).Name; } else { return ((EntityContainer)item).Name; } } /// /// 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. /// public string CreateFullName(string namespaceName, string name) { if (String.IsNullOrEmpty(namespaceName)) { return name; } return namespaceName + "." + name; } /// /// Retuns a literal representing the supplied value. /// 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(); } /// /// Returns a resource string from the System.Data.Entity.Design assembly. /// 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"; /// /// 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. /// /// The type of item to return. /// The item collection to look in. /// The items to generate. public IEnumerable GetItemsToGenerate(ItemCollection itemCollection) where T: GlobalItem { return itemCollection.GetItems().Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName)); } /// /// 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). /// /// The c-space type usage to get a name for. /// The type name to use. public string GetTypeName(TypeUsage typeUsage) { return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null); } /// /// 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). /// /// The c-space type to get a name for. /// The type name to use. public string GetTypeName(EdmType edmType) { return GetTypeName(edmType, isNullable: null, modelNamespace: null); } /// /// 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). /// /// The c-space type usage to get a name for. /// If not null and the type's namespace does not match this namespace, then a /// fully qualified name will be returned. /// The type name to use. public string GetTypeName(TypeUsage typeUsage, string modelNamespace) { return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace); } /// /// 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). /// /// The c-space type to get a name for. /// If not null and the type's namespace does not match this namespace, then a /// fully qualified name will be returned. /// The type name to use. public string GetTypeName(EdmType edmType, string modelNamespace) { return GetTypeName(edmType, isNullable: null, modelNamespace: modelNamespace); } /// /// 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). /// /// The c-space type to get a name for. /// Set this to true for nullable usage of this type. /// If not null and the type's namespace does not match this namespace, then a /// fully qualified name will be returned. /// The type name to use. 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"); } } /// /// Responsible for making the Entity Framework Metadata more /// accessible for code generation. /// public class MetadataTools { private readonly DynamicTextTransformation _textTransformation; /// /// Initializes an MetadataTools Instance with the /// TextTransformation (T4 generated class) that is currently running /// public MetadataTools(object textTransformation) { if (textTransformation == null) { throw new ArgumentNullException("textTransformation"); } _textTransformation = DynamicTextTransformation.Create(textTransformation); } /// /// This method returns the underlying CLR type of the o-space type corresponding to the supplied /// Note that for an enum type this means that the type backing the enum will be returned, not the enum type itself. /// public Type ClrType(TypeUsage typeUsage) { return UnderlyingClrType(typeUsage.EdmType); } /// /// 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. /// 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); } /// /// True if the EdmProperty is a key of its DeclaringType, False otherwise. /// public bool IsKey(EdmProperty property) { if (property != null && property.DeclaringType.BuiltInTypeKind == BuiltInTypeKind.EntityType) { return ((EntityType)property.DeclaringType).KeyMembers.Contains(property); } return false; } /// /// True if the EdmProperty TypeUsage is Nullable, False otherwise. /// public bool IsNullable(EdmProperty property) { return property != null && IsNullable(property.TypeUsage); } /// /// True if the TypeUsage is Nullable, False otherwise. /// public bool IsNullable(TypeUsage typeUsage) { Facet nullableFacet = null; if (typeUsage != null && typeUsage.Facets.TryGetValue("Nullable", true, out nullableFacet)) { return (bool)nullableFacet.Value; } return false; } /// /// If the passed in TypeUsage represents a collection this method returns final element /// type of the collection, otherwise it returns the value passed in. /// public TypeUsage GetElementType(TypeUsage typeUsage) { if (typeUsage == null) { return null; } if (typeUsage.EdmType is CollectionType) { return GetElementType(((CollectionType)typeUsage.EdmType).TypeUsage); } else { return typeUsage; } } /// /// Returns the NavigationProperty that is the other end of the same association set if it is /// available, otherwise it returns null. /// 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)); } /// /// 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. /// public EdmProperty GetCorrespondingPrincipalProperty(NavigationProperty navProperty, EdmProperty dependentProperty) { if (navProperty == null) { throw new ArgumentNullException("navProperty"); } if (dependentProperty == null) { throw new ArgumentNullException("dependentProperty"); } ReadOnlyMetadataCollection fromProperties = GetPrincipalProperties(navProperty); ReadOnlyMetadataCollection toProperties = GetDependentProperties(navProperty); return fromProperties[toProperties.IndexOf(dependentProperty)]; } /// /// 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. /// public EdmProperty GetCorrespondingDependentProperty(NavigationProperty navProperty, EdmProperty principalProperty) { if (navProperty == null) { throw new ArgumentNullException("navProperty"); } if (principalProperty == null) { throw new ArgumentNullException("principalProperty"); } ReadOnlyMetadataCollection fromProperties = GetPrincipalProperties(navProperty); ReadOnlyMetadataCollection toProperties = GetDependentProperties(navProperty); return toProperties[fromProperties.IndexOf(principalProperty)]; } /// /// 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. /// public ReadOnlyMetadataCollection GetPrincipalProperties(NavigationProperty navProperty) { if (navProperty == null) { throw new ArgumentNullException("navProperty"); } return ((AssociationType)navProperty.RelationshipType).ReferentialConstraints[0].FromProperties; } /// /// 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. /// public ReadOnlyMetadataCollection GetDependentProperties(NavigationProperty navProperty) { if (navProperty == null) { throw new ArgumentNullException("navProperty"); } return ((AssociationType)navProperty.RelationshipType).ReferentialConstraints[0].ToProperties; } /// /// True if this entity type requires the HandleCascadeDelete method defined and the method has /// not been defined on any base type /// 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; } /// /// 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 /// private bool ContainsCascadeDeleteAssociation(ItemCollection itemCollection, EntityType entity) { return itemCollection.GetItems().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(); } /// /// 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. /// public bool IsCascadeDeletePrincipal(NavigationProperty navProperty) { if (navProperty == null) { throw new ArgumentNullException("navProperty"); } return IsCascadeDeletePrincipal((AssociationEndMember)navProperty.FromEndMember); } /// /// True if the specified association end is the principal in an identifying relationship. /// or if the association end has cascade delete defined. /// public bool IsCascadeDeletePrincipal(AssociationEndMember associationEnd) { if (associationEnd == null) { throw new ArgumentNullException("associationEnd"); } return associationEnd.DeleteBehavior == OperationAction.Cascade || IsPrincipalEndOfIdentifyingRelationship(associationEnd); } /// /// 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. /// 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; } /// /// 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. /// public bool IsIdentifyingRelationship(AssociationType association) { if (association == null) { throw new ArgumentNullException("association"); } return IsPrincipalEndOfIdentifyingRelationship(association.AssociationEndMembers[0]) || IsPrincipalEndOfIdentifyingRelationship(association.AssociationEndMembers[1]); } /// /// 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. /// 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; } /// /// Returns the subtype of the EntityType in the current itemCollection /// public IEnumerable GetSubtypesOf(EntityType type, ItemCollection itemCollection, bool includeAbstractTypes) { if (type != null) { IEnumerable typesInCollection = itemCollection.GetItems(); 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; } } /// /// Responsible for loading an EdmItemCollection from a .edmx file or .csdl files /// public class MetadataLoader { private readonly DynamicTextTransformation _textTransformation; /// /// Initializes an MetadataLoader Instance with the /// TextTransformation (T4 generated class) that is currently running /// public MetadataLoader(object textTransformation) { if (textTransformation == null) { throw new ArgumentNullException("textTransformation"); } _textTransformation = DynamicTextTransformation.Create(textTransformation); } /// /// 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 /// 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; } /// /// Create an EdmItemCollection loaded with the metadata provided /// public EdmItemCollection CreateEdmItemCollection(string sourcePath, params string[] referenceSchemas) { EdmItemCollection edmItemCollection; if(TryCreateEdmItemCollection(sourcePath, referenceSchemas, out edmItemCollection)) { return edmItemCollection; } return new EdmItemCollection(); } /// /// Attempts to create a EdmItemCollection from the specified metadata file /// public bool TryCreateEdmItemCollection(string sourcePath, out EdmItemCollection edmItemCollection) { return TryCreateEdmItemCollection(sourcePath, null, out edmItemCollection); } /// /// Attempts to create a EdmItemCollection from the specified metadata file /// 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; } /// /// Attempts to create a StoreItemCollection from the specified metadata file /// 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; } /// /// Attempts to create a StorageMappingItemCollection from the specified metadata file, EdmItemCollection, and StoreItemCollection /// 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; } /// /// Gets the Model Namespace from the provided schema file. /// 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; } /// /// Returns true if the specified file path is valid /// 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; } /// /// Base class for ItemCollectionBuilder classes that /// loads the specific types of metadata /// private abstract class ItemCollectionBuilder { private readonly DynamicTextTransformation _textTransformation; private readonly string _fileExtension; private readonly string _edmxSectionName; private readonly string _rootElementName; /// /// FileExtension for individual (non-edmx) metadata file for this /// specific ItemCollection type /// public string FileExtension { get { return _fileExtension; } } /// /// The name of the XmlElement in the .edmx element /// to find this ItemCollection's metadata /// public string EdmxSectionName { get { return _edmxSectionName; } } /// /// The name of the root element of this ItemCollection's metadata /// public string RootElementName { get { return _rootElementName; } } /// /// Method to build the appropriate ItemCollection /// protected abstract ItemCollection CreateItemCollection(IEnumerable readers, out IList errors); /// /// Ctor to setup the ItemCollectionBuilder members /// protected ItemCollectionBuilder(DynamicTextTransformation textTransformation, string fileExtension, string edmxSectionName, string rootElementName) { _textTransformation = textTransformation; _fileExtension = fileExtension; _edmxSectionName = edmxSectionName; _rootElementName = rootElementName; } /// /// Selects a namespace from the supplied constants. /// protected abstract string GetNamespace(SchemaConstants constants); /// /// Try to create an ItemCollection loaded with the metadata provided /// 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 readers = new List(); try { readers.Add(schemaElement.CreateReader()); IList 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; } /// /// Tries to load the root element from the metadata file provided /// 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; } /// /// Tries to load the root element from the provided edmxDocument /// 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; } /// /// Tries to load the root element from the provided .edmx metadata file /// 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); } /// /// Takes an Enumerable of EdmSchemaErrors, and adds them /// to the errors collection of the template class /// private bool ProcessErrors(IEnumerable 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; } } /// /// Builder class for creating a StorageMappingItemCollection /// 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 readers, out IList errors) { return MetadataItemCollectionFactory.CreateStorageMappingItemCollection(_edmItemCollection, _storeItemCollection, readers, out errors); } /// /// Selects a namespace from the supplied constants. /// protected override string GetNamespace(SchemaConstants constants) { return constants.MslNamespace; } } /// /// Builder class for creating a StoreItemCollection /// 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 readers, out IList errors) { return MetadataItemCollectionFactory.CreateStoreItemCollection(readers, out errors); } /// /// Selects a namespace from the supplied constants. /// protected override string GetNamespace(SchemaConstants constants) { return constants.SsdlNamespace; } } /// /// Builder class for creating a EdmItemCollection /// private class EdmItemCollectionBuilder : ItemCollectionBuilder { private List _referenceSchemas = new List(); public EdmItemCollectionBuilder(DynamicTextTransformation textTransformation) : base(textTransformation, MetadataConstants.CSDL_EXTENSION, MetadataConstants.CSDL_EDMX_SECTION_NAME, MetadataConstants.CSDL_ROOT_ELEMENT_NAME) { } public EdmItemCollectionBuilder(DynamicTextTransformation textTransformation, IEnumerable referenceSchemas) : this(textTransformation) { _referenceSchemas.AddRange(referenceSchemas); } protected override ItemCollection CreateItemCollection(IEnumerable readers, out IList errors) { List ownedReaders = new List(); List allReaders = new List(); 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(); } } } /// /// Selects a namespace from the supplied constants. /// protected override string GetNamespace(SchemaConstants constants) { return constants.CsdlNamespace; } } } /// /// Responsible for encapsulating the retrieval and translation of the CodeGeneration /// annotations in the EntityFramework Metadata to a form that is useful in code generation. /// 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 AccessibilityRankIdLookup = new Dictionary { { "private", 1}, { "internal", 2}, { "protected", 3}, { "public", 4}, }; /// /// Gets the accessibility that should be applied to a type being generated from the provided GlobalItem. /// /// defaults to public if no annotation is found. /// public static string ForType(GlobalItem item) { if (item == null) { return null; } return GetAccessibility(item, TYPE_ACCESS); } /// /// 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. /// 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; } /// /// 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. /// public static string ForReadOnlyProperty(EdmMember member) { if (member == null) { return null; } return GetAccessibility(member, GETTER_ACCESS); } /// /// 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. /// public static string ForReadOnlyProperty(EntitySet set) { if (set == null) { return null; } return GetAccessibility(set, GETTER_ACCESS); } /// /// 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. /// public static string ForWriteOnlyProperty(EdmMember member) { if (member == null) { return null; } return GetAccessibility(member, SETTER_ACCESS); } /// /// 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. /// 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; } /// /// 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. /// 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; } /// /// Gets the accessibility that should be applied to a method being generated from the provided EdmFunction. /// /// defaults to public if no annotation is found. /// 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"; } } } /// /// Responsible for creating source code regions in code when the loop inside /// actually produces something. /// public class CodeRegion { private const int STANDARD_INDENT_LENGTH = 4; private readonly DynamicTextTransformation _textTransformation; private int _beforeRegionLength; private int _emptyRegionLength; private int _regionIndentLevel = -1; /// /// Initializes an CodeRegion instance with the /// TextTransformation (T4 generated class) that is currently running /// public CodeRegion(object textTransformation) { if (textTransformation == null) { throw new ArgumentNullException("textTransformation"); } _textTransformation = DynamicTextTransformation.Create(textTransformation); } /// /// Initializes an CodeRegion instance with the /// TextTransformation (T4 generated class) that is currently running, /// and the indent level to start the first region at. /// public CodeRegion(object textTransformation, int firstIndentLevel) : this(textTransformation) { if (firstIndentLevel < 0) { throw new ArgumentException("firstIndentLevel"); } _regionIndentLevel = firstIndentLevel - 1; } /// /// Starts the begining of a region /// public void Begin(string regionName) { if (regionName == null) { throw new ArgumentNullException("regionName"); } Begin(regionName, 1); } /// /// Start the begining of a region, indented /// the numbers of levels specified /// 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; } /// /// Ends a region, or totaly removes it if nothing /// was generted since the begining of the region. /// public void End() { End(1); } /// /// Ends a region, or totaly removes it if nothing /// was generted since the begining of the region, also outdents /// the number of levels specified. /// 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); } } /// /// Gets the current indent level that the next end region statement will be written /// at /// public int CurrentIndentLevel { get { return _regionIndentLevel; } } /// /// Get a string of spaces equivelent to the number of indents /// desired. /// public static string GetIndent(int indentLevel) { if (indentLevel < 0) { throw new ArgumentException("indentLevel"); } return String.Empty.PadLeft(indentLevel * STANDARD_INDENT_LENGTH); } } /// /// Responsible for collecting together the actual method parameters /// and the parameters that need to be sent to the Execute method. /// 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; } /// /// Creates a set of FunctionImportParameter objects from the parameters passed in. /// public static IEnumerable Create(IEnumerable 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 importParameters = new List(); 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 _knownIdentifiers; public UniqueIdentifierService() { _knownIdentifiers = new HashSet(StringComparer.Ordinal); } /// /// Given an identifier, makes it unique within the scope by adding /// a suffix (1, 2, 3, ...), and returns the adjusted identifier. /// 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; } } } /// /// Responsible for marking the various sections of the generation, /// so they can be split up into separate files /// public class EntityFrameworkTemplateFileManager { /// /// Creates the VsEntityFrameworkTemplateFileManager if VS is detected, otherwise /// creates the file system version. /// 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 files = new List(); 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; /// /// Initializes an EntityFrameworkTemplateFileManager Instance with the /// TextTransformation (T4 generated class) that is currently running /// private EntityFrameworkTemplateFileManager(object textTransformation) { if (textTransformation == null) { throw new ArgumentNullException("textTransformation"); } _textTransformation = DynamicTextTransformation.Create(textTransformation); _generationEnvironment = _textTransformation.GenerationEnvironment; } /// /// 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. /// 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; } /// /// Produce the template output files. /// public virtual IEnumerable Process(bool split = true) { var generatedFileNames = new List(); 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 checkOutAction; private Action> projectSyncAction; /// /// Creates an instance of the VsEntityFrameworkTemplateFileManager class with the IDynamicHost instance /// 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 Process(bool split) { if (templateProjectItem.ProjectItems == null) { return new List(); } 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 keepFileNames) { var keepFileNameSet = new HashSet(keepFileNames); var projectFiles = new Dictionary(); 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 } /// /// 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 /// 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; /// /// 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. /// 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"); } /// /// Gets the value of the wrapped TextTranformation instance's GenerationEnvironment property /// public StringBuilder GenerationEnvironment { get { return (StringBuilder)_generationEnvironment.GetValue(_instance, null); } } /// /// Gets the value of the wrapped TextTranformation instance's Errors property /// public System.CodeDom.Compiler.CompilerErrorCollection Errors { get { return (System.CodeDom.Compiler.CompilerErrorCollection)_errors.GetValue(_instance, null); } } /// /// Calls the wrapped TextTranformation instance's Write method. /// public void Write(string text) { _write.Invoke(_instance, new object[] { text }); } /// /// Calls the wrapped TextTranformation instance's WriteLine method. /// public void WriteLine(string text) { _writeLine.Invoke(_instance, new object[] { text }); } /// /// 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 /// public IDynamicHost Host { get { if (_dynamicHost == null) { if(_host == null) { _dynamicHost = new NullHost(); } else { _dynamicHost = new DynamicHost(_host.GetValue(_instance, null)); } } return _dynamicHost; } } } /// /// Reponsible for abstracting the use of Host between times /// when it is available and not /// public interface IDynamicHost { /// /// An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue /// string ResolveParameterValue(string id, string name, string otherName); /// /// An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath /// string ResolvePath(string path); /// /// An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile /// string TemplateFile { get; } /// /// Returns the Host instance cast as an IServiceProvider /// IServiceProvider AsIServiceProvider(); } /// /// 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. /// public class DynamicHost : IDynamicHost { private readonly object _instance; private readonly MethodInfo _resolveParameterValue; private readonly MethodInfo _resolvePath; private readonly PropertyInfo _templateFile; /// /// Creates an instance of the DynamicHost class around the passed in /// Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost shapped instance passed in. /// 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"); } /// /// A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue /// public string ResolveParameterValue(string id, string name, string otherName) { return (string)_resolveParameterValue.Invoke(_instance, new object[] { id, name, otherName }); } /// /// A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath /// public string ResolvePath(string path) { return (string)_resolvePath.Invoke(_instance, new object[] { path }); } /// /// A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile /// public string TemplateFile { get { return (string)_templateFile.GetValue(_instance, null); } } /// /// Returns the Host instance cast as an IServiceProvider /// public IServiceProvider AsIServiceProvider() { return _instance as IServiceProvider; } } /// /// 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. /// public class NullHost : IDynamicHost { /// /// An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue /// that simply retuns null. /// public string ResolveParameterValue(string id, string name, string otherName) { return null; } /// /// An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath /// that simply retuns the path passed in. /// public string ResolvePath(string path) { return path; } /// /// An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile /// that returns null. /// public string TemplateFile { get { return null; } } /// /// Returns null. /// public IServiceProvider AsIServiceProvider() { return null; } } /// /// Responsible for encapsulating the constants defined in Metadata /// 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 /// /// Base class for this transformation /// [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 indentLengthsField; private string currentIndentField = ""; private bool endsWithNewline; private global::System.Collections.Generic.IDictionary sessionField; #endregion #region Properties /// /// The string builder that generation-time code is using to assemble generated output /// protected System.Text.StringBuilder GenerationEnvironment { get { if ((this.generationEnvironmentField == null)) { this.generationEnvironmentField = new global::System.Text.StringBuilder(); } return this.generationEnvironmentField; } set { this.generationEnvironmentField = value; } } /// /// The error collection for the generation process /// public System.CodeDom.Compiler.CompilerErrorCollection Errors { get { if ((this.errorsField == null)) { this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection(); } return this.errorsField; } } /// /// A list of the lengths of each indent that was added with PushIndent /// private System.Collections.Generic.List indentLengths { get { if ((this.indentLengthsField == null)) { this.indentLengthsField = new global::System.Collections.Generic.List(); } return this.indentLengthsField; } } /// /// Gets the current indent we use when adding lines to the output /// public string CurrentIndent { get { return this.currentIndentField; } } /// /// Current transformation session /// public virtual global::System.Collections.Generic.IDictionary Session { get { return this.sessionField; } set { this.sessionField = value; } } #endregion #region Transform-time helpers /// /// Write text directly into the generated output /// 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); } } /// /// Write text directly into the generated output /// public void WriteLine(string textToAppend) { this.Write(textToAppend); this.GenerationEnvironment.AppendLine(); this.endsWithNewline = true; } /// /// Write formatted text directly into the generated output /// public void Write(string format, params object[] args) { this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args)); } /// /// Write formatted text directly into the generated output /// public void WriteLine(string format, params object[] args) { this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args)); } /// /// Raise an error /// public void Error(string message) { System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError(); error.ErrorText = message; this.Errors.Add(error); } /// /// Raise a warning /// 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); } /// /// Increase the indent /// public void PushIndent(string indent) { if ((indent == null)) { throw new global::System.ArgumentNullException("indent"); } this.currentIndentField = (this.currentIndentField + indent); this.indentLengths.Add(indent.Length); } /// /// Remove the last indent that was added with PushIndent /// 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; } /// /// Remove any indentation /// public void ClearIndent() { this.indentLengths.Clear(); this.currentIndentField = ""; } #endregion #region ToString Helpers /// /// Utility class to produce culture-oriented representation of an object as a string. /// public class ToStringInstanceHelper { private System.IFormatProvider formatProviderField = global::System.Globalization.CultureInfo.InvariantCulture; /// /// Gets or sets format provider to be used by ToStringWithCulture method. /// public System.IFormatProvider FormatProvider { get { return this.formatProviderField ; } set { if ((value != null)) { this.formatProviderField = value; } } } /// /// This is called from the compile/run appdomain to convert objects within an expression block to a string /// 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(); /// /// Helper to produce culture-oriented representation of an object as a string /// public ToStringInstanceHelper ToStringHelper { get { return this.toStringHelperField; } } #endregion } #endregion } // ------------------------------------------------------------------------------ // // 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. // // ------------------------------------------------------------------------------ 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; /// /// Class to produce the template output /// [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "11.0.0.0")] public partial class CSharpCodeGenTemplateV50 : CSharpCodeGenTemplateV50Base { /// /// Create the template output /// 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// \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(@" // //------------------------------------------------------------------------------ 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()) { 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()) { this.Write("\r\n/// \r\n/// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(container))); this.Write("\r\n/// "); 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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_ContextDefaultCtorComment"), container.Name, container.Name))); this.Write("\r\n /// \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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_ContextCommonCtorComment"), container.Name))); this.Write("\r\n /// \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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_ContextCommonCtorComment"), container.Name))); this.Write("\r\n /// \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()) { VerifyEntityTypeAndSetAccessibilityCompatability(set); this.Write("\r\n /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(set))); this.Write("\r\n /// "); 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 addToMethods = CreateContextAddToMethods.Value ? container.BaseEntitySets.OfType() : Enumerable.Empty(); foreach (EntitySet set in addToMethods) { string parameterName = code.Escape(FixParameterName(set.ElementType.Name, code)); this.Write("\r\n /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_GenCommentAddToMethodCs"), set.Name))); this.Write("\r\n /// \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 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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(edmFunction))); this.Write("\r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel))); this.Write(this.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(p => new Tuple(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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(edmFunction))); this.Write("\r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel))); this.Write(this.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(p => new Tuple(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(" /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(edmFunction))); this.Write("\r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel))); this.Write("\r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(p => new Tuple(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().OrderBy(e => e.Name)) { this.Write("\r\n/// \r\n/// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(entity))); this.Write("\r\n/// "); 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().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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(navProperty))); this.Write("\r\n /// "); 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(" /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(navProperty))); this.Write("\r\n /// "); 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().OrderBy(c => c.Name)) { this.Write("\r\n/// \r\n/// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(complex))); this.Write("\r\n/// "); 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().OrderBy(c => c.Name)) { this.Write("\r\n/// \r\n/// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(enumType))); this.Write("\r\n/// "); 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(" /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(member))); this.Write("\r\n /// "); 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() .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 parameters = FactoryMethodParameter.CreateParameters(structuralType.Members.OfType().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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_FactoryMethodComment"), structuralType.Name))); this.Write("\r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(ParameterComments(parameters.Select(p => new Tuple(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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(simpleProperty))); this.Write("\r\n /// "); 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 /// \r\n /// "); this.Write(this.ToStringHelper.ToStringWithCulture(SummaryComment(complexProperty))); this.Write("\r\n /// "); 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 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 ReferenceCsdlPaths{ get; set; } public Nullable CreateContextAddToMethods{ get; set; } public Dictionary EdmToObjectNamespaceMap { get { return _edmToObjectNamespaceMap; } set { _edmToObjectNamespaceMap = value; } } public Dictionary _edmToObjectNamespaceMap = new Dictionary(); public Double SourceEdmVersion { get { if (ItemCollection != null) { return ItemCollection.EdmVersion; } return 0.0; } } private bool VerifyTypeUniqueness(IEnumerable types) { HashSet hash = new HashSet(); 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 GetSourceSchemaTypes() where T : GlobalItem { if (Path.GetExtension(SourceCsdlPath) != ".edmx") { return ItemCollection.GetItems().Where(e => e.MetadataProperties.Any(mp => mp.Name == "SchemaSource" && (string)mp.Value == SourceCsdlPath)); } else { return ItemCollection.GetItems(); } } 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 CreateParameters(IEnumerable properties, UniqueIdentifierService unique, Func multiSchemaEscape, CodeGenerationTools code) { List parameters = new List(); 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 + "" + Environment.NewLine; comment += lineStart + PrefixLinesOfMultilineComment(lineStart, XmlEntityize(item.Documentation.LongDescription)) + Environment.NewLine; comment += lineStart + ""; return comment; } return string.Empty; } string PrefixLinesOfMultilineComment(string prefix, string comment) { return comment.Replace(Environment.NewLine, Environment.NewLine + prefix); } string ParameterComments(IEnumerable> parameters, int indentLevel) { System.Text.StringBuilder builder = new System.Text.StringBuilder(); foreach (Tuple parameter in parameters) { builder.AppendLine(); builder.Append(CodeRegion.GetIndent(indentLevel)); builder.Append(XMLCOMMENT_START); builder.Append(String.Format(CultureInfo.InvariantCulture, " {1}", parameter.Item1, parameter.Item2)); } return builder.ToString(); } string XmlEntityize(string text) { if (string.IsNullOrEmpty(text)) { return string.Empty; } text = text.Replace("&","&"); text = text.Replace("<","<").Replace(">",">"); string id = Guid.NewGuid().ToString(); text = text.Replace(Environment.NewLine, id); text = text.Replace("\r", " ").Replace("\n"," "); text = text.Replace(id, Environment.NewLine); return text.Replace("\'","'").Replace("\"","""); } const string XMLCOMMENT_START = "///"; IEnumerable 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 _knownIdentifiers; public UniqueIdentifierService() { _knownIdentifiers = new HashSet(StringComparer.Ordinal); } /// /// /// /// 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 TemplateMetadata = new Dictionary(); /// /// Responsible for helping to create source code that is /// correctly formated and functional /// public class CodeGenerationTools { private readonly DynamicTextTransformation _textTransformation; private readonly CSharpCodeProvider _code; private readonly MetadataTools _ef; /// /// Initializes a new CodeGenerationTools object with the TextTransformation (T4 generated class) /// that is currently running /// 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; } /// /// 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. /// public bool FullyQualifySystemTypes { get; set; } /// /// When true, the field names are Camel Cased, /// otherwise they will preserve the case they /// start with. /// /// Default is true. /// public bool CamelCaseFields { get; set; } /// /// Returns the NamespaceName suggested by VS if running inside VS. Otherwise, returns /// null. /// public string VsNamespaceSuggestion() { string suggestion = _textTransformation.Host.ResolveParameterValue("directiveId", "namespaceDirectiveProcessor", "namespaceHint"); if (String.IsNullOrEmpty(suggestion)) { return null; } return suggestion; } /// /// Returns a string that is safe for use as an identifier in C#. /// Keywords are escaped. /// public string Escape(string name) { if (name == null) { return null; } return _code.CreateEscapedIdentifier(name); } /// /// Returns the name of the TypeUsage's EdmType that is safe for /// use as an identifier. /// 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"); } /// /// Returns the name of the EdmMember that is safe for /// use as an identifier. /// public string Escape(EdmMember member) { if (member == null) { return null; } return Escape(member.Name); } /// /// Returns the name of the EdmType that is safe for /// use as an identifier. /// public string Escape(EdmType type) { if (type == null) { return null; } return Escape(type.Name); } /// /// Returns the name of the EdmFunction that is safe for /// use as an identifier. /// public string Escape(EdmFunction function) { if (function == null) { return null; } return Escape(function.Name); } /// /// Returns the name of the EnumMember that is safe for /// use as an identifier. /// public string Escape(EnumMember member) { if (member == null) { return null; } return Escape(member.Name); } /// /// Returns the name of the EntityContainer that is safe for /// use as an identifier. /// public string Escape(EntityContainer container) { if (container == null) { return null; } return Escape(container.Name); } /// /// Returns the name of the EntitySet that is safe for /// use as an identifier. /// public string Escape(EntitySet set) { if (set == null) { return null; } return Escape(set.Name); } /// /// Returns the name of the StructuralType that is safe for /// use as an identifier. /// public string Escape(StructuralType type) { if (type == null) { return null; } return Escape(type.Name); } /// /// Returns the NamespaceName with each segment safe to /// use as an identifier. /// 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; } /// /// Returns the name of the EdmMember formatted for /// use as a field identifier. /// /// This method changes behavior based on the CamelCaseFields /// setting. /// public string FieldName(EdmMember member) { if (member == null) { return null; } return FieldName(member.Name); } /// /// Returns the name of the EntitySet formatted for /// use as a field identifier. /// /// This method changes behavior based on the CamelCaseFields /// setting. /// 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; } } /// /// Returns the name of the Type object formatted for /// use in source code. /// /// This method changes behavior based on the FullyQualifySystemTypes /// setting. /// public string Escape(Type clrType) { return Escape(clrType, FullyQualifySystemTypes); } /// /// Returns the name of the Type object formatted for /// use in source code. /// 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; } /// /// Returns the abstract option if the entity is Abstract, otherwise returns String.Empty /// public string AbstractOption(EntityType entity) { if (entity.Abstract) { return "abstract"; } return String.Empty; } /// /// Returns the passed in identifier with the first letter changed to lowercase /// 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); } /// /// 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. /// public string SpaceAfter(string value) { return StringAfter(value, " "); } /// /// 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. /// public string SpaceBefore(string value) { return StringBefore(" ", value); } /// /// If the value parameter is null or empty an empty string is returned, /// otherwise it retuns value with append concatenated on the end. /// public string StringAfter(string value, string append) { if (String.IsNullOrEmpty(value)) { return String.Empty; } return value + append; } /// /// If the value parameter is null or empty an empty string is returned, /// otherwise it retuns value with prepend concatenated on the front. /// public string StringBefore(string prepend, string value) { if (String.IsNullOrEmpty(value)) { return String.Empty; } return prepend + value; } /// /// Returns false and shows an error if the supplied type names aren't case-insensitively unique, /// otherwise returns true. /// public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable types, string sourceFile) { return VerifyCaseInsensitiveUniqueness(types, t => string.Format(CultureInfo.CurrentCulture, GetResourceString("Template_CaseInsensitiveTypeConflict"), t), sourceFile); } /// /// Returns false and shows an error if the supplied strings aren't case-insensitively unique, /// otherwise returns true. /// private bool VerifyCaseInsensitiveUniqueness(IEnumerable items, Func formatMessage, string sourceFile) { HashSet hash = new HashSet(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; } /// /// Returns the names of the items in the supplied collection that correspond to O-Space types. /// public IEnumerable GetAllGlobalItems(EdmItemCollection itemCollection) { return itemCollection.GetItems().Where(i => i is EntityType || i is ComplexType || i is EnumType || i is EntityContainer).Select(g => GetGlobalItemName(g)); } /// /// Returns the name of the supplied GlobalItem. /// public string GetGlobalItemName(GlobalItem item) { if (item is EdmType) { return ((EdmType)item).Name; } else { return ((EntityContainer)item).Name; } } /// /// 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. /// public string CreateFullName(string namespaceName, string name) { if (String.IsNullOrEmpty(namespaceName)) { return name; } return namespaceName + "." + name; } /// /// Retuns a literal representing the supplied value. /// 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(); } /// /// Returns a resource string from the System.Data.Entity.Design assembly. /// 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"; /// /// 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. /// /// The type of item to return. /// The item collection to look in. /// The items to generate. public IEnumerable GetItemsToGenerate(ItemCollection itemCollection) where T: GlobalItem { return itemCollection.GetItems().Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName)); } /// /// 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). /// /// The c-space type usage to get a name for. /// The type name to use. public string GetTypeName(TypeUsage typeUsage) { return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null); } /// /// 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). /// /// The c-space type to get a name for. /// The type name to use. public string GetTypeName(EdmType edmType) { return GetTypeName(edmType, isNullable: null, modelNamespace: null); } /// /// 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). /// /// The c-space type usage to get a name for. /// If not null and the type's namespace does not match this namespace, then a /// fully qualified name will be returned. /// The type name to use. public string GetTypeName(TypeUsage typeUsage, string modelNamespace) { return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace); } /// /// 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). /// /// The c-space type to get a name for. /// If not null and the type's namespace does not match this namespace, then a /// fully qualified name will be returned. /// The type name to use. public string GetTypeName(EdmType edmType, string modelNamespace) { return GetTypeName(edmType, isNullable: null, modelNamespace: modelNamespace); } /// /// 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). /// /// The c-space type to get a name for. /// Set this to true for nullable usage of this type. /// If not null and the type's namespace does not match this namespace, then a /// fully qualified name will be returned. /// The type name to use. 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"); } } /// /// Responsible for making the Entity Framework Metadata more /// accessible for code generation. /// public class MetadataTools { private readonly DynamicTextTransformation _textTransformation; /// /// Initializes an MetadataTools Instance with the /// TextTransformation (T4 generated class) that is currently running /// public MetadataTools(object textTransformation) { if (textTransformation == null) { throw new ArgumentNullException("textTransformation"); } _textTransformation = DynamicTextTransformation.Create(textTransformation); } /// /// This method returns the underlying CLR type of the o-space type corresponding to the supplied /// Note that for an enum type this means that the type backing the enum will be returned, not the enum type itself. /// public Type ClrType(TypeUsage typeUsage) { return UnderlyingClrType(typeUsage.EdmType); } /// /// 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. /// 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); } /// /// True if the EdmProperty is a key of its DeclaringType, False otherwise. /// public bool IsKey(EdmProperty property) { if (property != null && property.DeclaringType.BuiltInTypeKind == BuiltInTypeKind.EntityType) { return ((EntityType)property.DeclaringType).KeyMembers.Contains(property); } return false; } /// /// True if the EdmProperty TypeUsage is Nullable, False otherwise. /// public bool IsNullable(EdmProperty property) { return property != null && IsNullable(property.TypeUsage); } /// /// True if the TypeUsage is Nullable, False otherwise. /// public bool IsNullable(TypeUsage typeUsage) { Facet nullableFacet = null; if (typeUsage != null && typeUsage.Facets.TryGetValue("Nullable", true, out nullableFacet)) { return (bool)nullableFacet.Value; } return false; } /// /// If the passed in TypeUsage represents a collection this method returns final element /// type of the collection, otherwise it returns the value passed in. /// public TypeUsage GetElementType(TypeUsage typeUsage) { if (typeUsage == null) { return null; } if (typeUsage.EdmType is CollectionType) { return GetElementType(((CollectionType)typeUsage.EdmType).TypeUsage); } else { return typeUsage; } } /// /// Returns the NavigationProperty that is the other end of the same association set if it is /// available, otherwise it returns null. /// 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)); } /// /// 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. /// public EdmProperty GetCorrespondingPrincipalProperty(NavigationProperty navProperty, EdmProperty dependentProperty) { if (navProperty == null) { throw new ArgumentNullException("navProperty"); } if (dependentProperty == null) { throw new ArgumentNullException("dependentProperty"); } ReadOnlyMetadataCollection fromProperties = GetPrincipalProperties(navProperty); ReadOnlyMetadataCollection toProperties = GetDependentProperties(navProperty); return fromProperties[toProperties.IndexOf(dependentProperty)]; } /// /// 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. /// public EdmProperty GetCorrespondingDependentProperty(NavigationProperty navProperty, EdmProperty principalProperty) { if (navProperty == null) { throw new ArgumentNullException("navProperty"); } if (principalProperty == null) { throw new ArgumentNullException("principalProperty"); } ReadOnlyMetadataCollection fromProperties = GetPrincipalProperties(navProperty); ReadOnlyMetadataCollection toProperties = GetDependentProperties(navProperty); return toProperties[fromProperties.IndexOf(principalProperty)]; } /// /// 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. /// public ReadOnlyMetadataCollection GetPrincipalProperties(NavigationProperty navProperty) { if (navProperty == null) { throw new ArgumentNullException("navProperty"); } return ((AssociationType)navProperty.RelationshipType).ReferentialConstraints[0].FromProperties; } /// /// 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. /// public ReadOnlyMetadataCollection GetDependentProperties(NavigationProperty navProperty) { if (navProperty == null) { throw new ArgumentNullException("navProperty"); } return ((AssociationType)navProperty.RelationshipType).ReferentialConstraints[0].ToProperties; } /// /// True if this entity type requires the HandleCascadeDelete method defined and the method has /// not been defined on any base type /// 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; } /// /// 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 /// private bool ContainsCascadeDeleteAssociation(ItemCollection itemCollection, EntityType entity) { return itemCollection.GetItems().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(); } /// /// 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. /// public bool IsCascadeDeletePrincipal(NavigationProperty navProperty) { if (navProperty == null) { throw new ArgumentNullException("navProperty"); } return IsCascadeDeletePrincipal((AssociationEndMember)navProperty.FromEndMember); } /// /// True if the specified association end is the principal in an identifying relationship. /// or if the association end has cascade delete defined. /// public bool IsCascadeDeletePrincipal(AssociationEndMember associationEnd) { if (associationEnd == null) { throw new ArgumentNullException("associationEnd"); } return associationEnd.DeleteBehavior == OperationAction.Cascade || IsPrincipalEndOfIdentifyingRelationship(associationEnd); } /// /// 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. /// 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; } /// /// 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. /// public bool IsIdentifyingRelationship(AssociationType association) { if (association == null) { throw new ArgumentNullException("association"); } return IsPrincipalEndOfIdentifyingRelationship(association.AssociationEndMembers[0]) || IsPrincipalEndOfIdentifyingRelationship(association.AssociationEndMembers[1]); } /// /// 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. /// 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; } /// /// Returns the subtype of the EntityType in the current itemCollection /// public IEnumerable GetSubtypesOf(EntityType type, ItemCollection itemCollection, bool includeAbstractTypes) { if (type != null) { IEnumerable typesInCollection = itemCollection.GetItems(); 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; } } /// /// Responsible for loading an EdmItemCollection from a .edmx file or .csdl files /// public class MetadataLoader { private readonly DynamicTextTransformation _textTransformation; /// /// Initializes an MetadataLoader Instance with the /// TextTransformation (T4 generated class) that is currently running /// public MetadataLoader(object textTransformation) { if (textTransformation == null) { throw new ArgumentNullException("textTransformation"); } _textTransformation = DynamicTextTransformation.Create(textTransformation); } /// /// 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 /// 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; } /// /// Create an EdmItemCollection loaded with the metadata provided /// public EdmItemCollection CreateEdmItemCollection(string sourcePath, params string[] referenceSchemas) { EdmItemCollection edmItemCollection; if(TryCreateEdmItemCollection(sourcePath, referenceSchemas, out edmItemCollection)) { return edmItemCollection; } return new EdmItemCollection(); } /// /// Attempts to create a EdmItemCollection from the specified metadata file /// public bool TryCreateEdmItemCollection(string sourcePath, out EdmItemCollection edmItemCollection) { return TryCreateEdmItemCollection(sourcePath, null, out edmItemCollection); } /// /// Attempts to create a EdmItemCollection from the specified metadata file /// 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; } /// /// Attempts to create a StoreItemCollection from the specified metadata file /// 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; } /// /// Attempts to create a StorageMappingItemCollection from the specified metadata file, EdmItemCollection, and StoreItemCollection /// 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; } /// /// Gets the Model Namespace from the provided schema file. /// 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; } /// /// Returns true if the specified file path is valid /// 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; } /// /// Base class for ItemCollectionBuilder classes that /// loads the specific types of metadata /// private abstract class ItemCollectionBuilder { private readonly DynamicTextTransformation _textTransformation; private readonly string _fileExtension; private readonly string _edmxSectionName; private readonly string _rootElementName; /// /// FileExtension for individual (non-edmx) metadata file for this /// specific ItemCollection type /// public string FileExtension { get { return _fileExtension; } } /// /// The name of the XmlElement in the .edmx element /// to find this ItemCollection's metadata /// public string EdmxSectionName { get { return _edmxSectionName; } } /// /// The name of the root element of this ItemCollection's metadata /// public string RootElementName { get { return _rootElementName; } } /// /// Method to build the appropriate ItemCollection /// protected abstract ItemCollection CreateItemCollection(IEnumerable readers, out IList errors); /// /// Ctor to setup the ItemCollectionBuilder members /// protected ItemCollectionBuilder(DynamicTextTransformation textTransformation, string fileExtension, string edmxSectionName, string rootElementName) { _textTransformation = textTransformation; _fileExtension = fileExtension; _edmxSectionName = edmxSectionName; _rootElementName = rootElementName; } /// /// Selects a namespace from the supplied constants. /// protected abstract string GetNamespace(SchemaConstants constants); /// /// Try to create an ItemCollection loaded with the metadata provided /// 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 readers = new List(); try { readers.Add(schemaElement.CreateReader()); IList 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; } /// /// Tries to load the root element from the metadata file provided /// 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; } /// /// Tries to load the root element from the provided edmxDocument /// 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; } /// /// Tries to load the root element from the provided .edmx metadata file /// 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); } /// /// Takes an Enumerable of EdmSchemaErrors, and adds them /// to the errors collection of the template class /// private bool ProcessErrors(IEnumerable 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; } } /// /// Builder class for creating a StorageMappingItemCollection /// 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 readers, out IList errors) { return MetadataItemCollectionFactory.CreateStorageMappingItemCollection(_edmItemCollection, _storeItemCollection, readers, out errors); } /// /// Selects a namespace from the supplied constants. /// protected override string GetNamespace(SchemaConstants constants) { return constants.MslNamespace; } } /// /// Builder class for creating a StoreItemCollection /// 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 readers, out IList errors) { return MetadataItemCollectionFactory.CreateStoreItemCollection(readers, out errors); } /// /// Selects a namespace from the supplied constants. /// protected override string GetNamespace(SchemaConstants constants) { return constants.SsdlNamespace; } } /// /// Builder class for creating a EdmItemCollection /// private class EdmItemCollectionBuilder : ItemCollectionBuilder { private List _referenceSchemas = new List(); public EdmItemCollectionBuilder(DynamicTextTransformation textTransformation) : base(textTransformation, MetadataConstants.CSDL_EXTENSION, MetadataConstants.CSDL_EDMX_SECTION_NAME, MetadataConstants.CSDL_ROOT_ELEMENT_NAME) { } public EdmItemCollectionBuilder(DynamicTextTransformation textTransformation, IEnumerable referenceSchemas) : this(textTransformation) { _referenceSchemas.AddRange(referenceSchemas); } protected override ItemCollection CreateItemCollection(IEnumerable readers, out IList errors) { List ownedReaders = new List(); List allReaders = new List(); 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(); } } } /// /// Selects a namespace from the supplied constants. /// protected override string GetNamespace(SchemaConstants constants) { return constants.CsdlNamespace; } } } /// /// Responsible for encapsulating the retrieval and translation of the CodeGeneration /// annotations in the EntityFramework Metadata to a form that is useful in code generation. /// 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 AccessibilityRankIdLookup = new Dictionary { { "private", 1}, { "internal", 2}, { "protected", 3}, { "public", 4}, }; /// /// Gets the accessibility that should be applied to a type being generated from the provided GlobalItem. /// /// defaults to public if no annotation is found. /// public static string ForType(GlobalItem item) { if (item == null) { return null; } return GetAccessibility(item, TYPE_ACCESS); } /// /// 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. /// 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; } /// /// 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. /// public static string ForReadOnlyProperty(EdmMember member) { if (member == null) { return null; } return GetAccessibility(member, GETTER_ACCESS); } /// /// 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. /// public static string ForReadOnlyProperty(EntitySet set) { if (set == null) { return null; } return GetAccessibility(set, GETTER_ACCESS); } /// /// 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. /// public static string ForWriteOnlyProperty(EdmMember member) { if (member == null) { return null; } return GetAccessibility(member, SETTER_ACCESS); } /// /// 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. /// 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; } /// /// 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. /// 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; } /// /// Gets the accessibility that should be applied to a method being generated from the provided EdmFunction. /// /// defaults to public if no annotation is found. /// 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"; } } } /// /// Responsible for creating source code regions in code when the loop inside /// actually produces something. /// public class CodeRegion { private const int STANDARD_INDENT_LENGTH = 4; private readonly DynamicTextTransformation _textTransformation; private int _beforeRegionLength; private int _emptyRegionLength; private int _regionIndentLevel = -1; /// /// Initializes an CodeRegion instance with the /// TextTransformation (T4 generated class) that is currently running /// public CodeRegion(object textTransformation) { if (textTransformation == null) { throw new ArgumentNullException("textTransformation"); } _textTransformation = DynamicTextTransformation.Create(textTransformation); } /// /// Initializes an CodeRegion instance with the /// TextTransformation (T4 generated class) that is currently running, /// and the indent level to start the first region at. /// public CodeRegion(object textTransformation, int firstIndentLevel) : this(textTransformation) { if (firstIndentLevel < 0) { throw new ArgumentException("firstIndentLevel"); } _regionIndentLevel = firstIndentLevel - 1; } /// /// Starts the begining of a region /// public void Begin(string regionName) { if (regionName == null) { throw new ArgumentNullException("regionName"); } Begin(regionName, 1); } /// /// Start the begining of a region, indented /// the numbers of levels specified /// 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; } /// /// Ends a region, or totaly removes it if nothing /// was generted since the begining of the region. /// public void End() { End(1); } /// /// Ends a region, or totaly removes it if nothing /// was generted since the begining of the region, also outdents /// the number of levels specified. /// 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); } } /// /// Gets the current indent level that the next end region statement will be written /// at /// public int CurrentIndentLevel { get { return _regionIndentLevel; } } /// /// Get a string of spaces equivelent to the number of indents /// desired. /// public static string GetIndent(int indentLevel) { if (indentLevel < 0) { throw new ArgumentException("indentLevel"); } return String.Empty.PadLeft(indentLevel * STANDARD_INDENT_LENGTH); } } /// /// Responsible for collecting together the actual method parameters /// and the parameters that need to be sent to the Execute method. /// 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; } /// /// Creates a set of FunctionImportParameter objects from the parameters passed in. /// public static IEnumerable Create(IEnumerable 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 importParameters = new List(); 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 _knownIdentifiers; public UniqueIdentifierService() { _knownIdentifiers = new HashSet(StringComparer.Ordinal); } /// /// Given an identifier, makes it unique within the scope by adding /// a suffix (1, 2, 3, ...), and returns the adjusted identifier. /// 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; } } } /// /// Responsible for marking the various sections of the generation, /// so they can be split up into separate files /// public class EntityFrameworkTemplateFileManager { /// /// Creates the VsEntityFrameworkTemplateFileManager if VS is detected, otherwise /// creates the file system version. /// 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 files = new List(); 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; /// /// Initializes an EntityFrameworkTemplateFileManager Instance with the /// TextTransformation (T4 generated class) that is currently running /// private EntityFrameworkTemplateFileManager(object textTransformation) { if (textTransformation == null) { throw new ArgumentNullException("textTransformation"); } _textTransformation = DynamicTextTransformation.Create(textTransformation); _generationEnvironment = _textTransformation.GenerationEnvironment; } /// /// 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. /// 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; } /// /// Produce the template output files. /// public virtual IEnumerable Process(bool split = true) { var generatedFileNames = new List(); 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 checkOutAction; private Action> projectSyncAction; /// /// Creates an instance of the VsEntityFrameworkTemplateFileManager class with the IDynamicHost instance /// 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 Process(bool split) { if (templateProjectItem.ProjectItems == null) { return new List(); } 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 keepFileNames) { var keepFileNameSet = new HashSet(keepFileNames); var projectFiles = new Dictionary(); 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 } /// /// 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 /// 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; /// /// 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. /// 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"); } /// /// Gets the value of the wrapped TextTranformation instance's GenerationEnvironment property /// public StringBuilder GenerationEnvironment { get { return (StringBuilder)_generationEnvironment.GetValue(_instance, null); } } /// /// Gets the value of the wrapped TextTranformation instance's Errors property /// public System.CodeDom.Compiler.CompilerErrorCollection Errors { get { return (System.CodeDom.Compiler.CompilerErrorCollection)_errors.GetValue(_instance, null); } } /// /// Calls the wrapped TextTranformation instance's Write method. /// public void Write(string text) { _write.Invoke(_instance, new object[] { text }); } /// /// Calls the wrapped TextTranformation instance's WriteLine method. /// public void WriteLine(string text) { _writeLine.Invoke(_instance, new object[] { text }); } /// /// 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 /// public IDynamicHost Host { get { if (_dynamicHost == null) { if(_host == null) { _dynamicHost = new NullHost(); } else { _dynamicHost = new DynamicHost(_host.GetValue(_instance, null)); } } return _dynamicHost; } } } /// /// Reponsible for abstracting the use of Host between times /// when it is available and not /// public interface IDynamicHost { /// /// An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue /// string ResolveParameterValue(string id, string name, string otherName); /// /// An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath /// string ResolvePath(string path); /// /// An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile /// string TemplateFile { get; } /// /// Returns the Host instance cast as an IServiceProvider /// IServiceProvider AsIServiceProvider(); } /// /// 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. /// public class DynamicHost : IDynamicHost { private readonly object _instance; private readonly MethodInfo _resolveParameterValue; private readonly MethodInfo _resolvePath; private readonly PropertyInfo _templateFile; /// /// Creates an instance of the DynamicHost class around the passed in /// Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost shapped instance passed in. /// 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"); } /// /// A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue /// public string ResolveParameterValue(string id, string name, string otherName) { return (string)_resolveParameterValue.Invoke(_instance, new object[] { id, name, otherName }); } /// /// A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath /// public string ResolvePath(string path) { return (string)_resolvePath.Invoke(_instance, new object[] { path }); } /// /// A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile /// public string TemplateFile { get { return (string)_templateFile.GetValue(_instance, null); } } /// /// Returns the Host instance cast as an IServiceProvider /// public IServiceProvider AsIServiceProvider() { return _instance as IServiceProvider; } } /// /// 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. /// public class NullHost : IDynamicHost { /// /// An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue /// that simply retuns null. /// public string ResolveParameterValue(string id, string name, string otherName) { return null; } /// /// An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath /// that simply retuns the path passed in. /// public string ResolvePath(string path) { return path; } /// /// An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile /// that returns null. /// public string TemplateFile { get { return null; } } /// /// Returns null. /// public IServiceProvider AsIServiceProvider() { return null; } } /// /// Responsible for encapsulating the constants defined in Metadata /// 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 /// /// Base class for this transformation /// [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 indentLengthsField; private string currentIndentField = ""; private bool endsWithNewline; private global::System.Collections.Generic.IDictionary sessionField; #endregion #region Properties /// /// The string builder that generation-time code is using to assemble generated output /// protected System.Text.StringBuilder GenerationEnvironment { get { if ((this.generationEnvironmentField == null)) { this.generationEnvironmentField = new global::System.Text.StringBuilder(); } return this.generationEnvironmentField; } set { this.generationEnvironmentField = value; } } /// /// The error collection for the generation process /// public System.CodeDom.Compiler.CompilerErrorCollection Errors { get { if ((this.errorsField == null)) { this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection(); } return this.errorsField; } } /// /// A list of the lengths of each indent that was added with PushIndent /// private System.Collections.Generic.List indentLengths { get { if ((this.indentLengthsField == null)) { this.indentLengthsField = new global::System.Collections.Generic.List(); } return this.indentLengthsField; } } /// /// Gets the current indent we use when adding lines to the output /// public string CurrentIndent { get { return this.currentIndentField; } } /// /// Current transformation session /// public virtual global::System.Collections.Generic.IDictionary Session { get { return this.sessionField; } set { this.sessionField = value; } } #endregion #region Transform-time helpers /// /// Write text directly into the generated output /// 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); } } /// /// Write text directly into the generated output /// public void WriteLine(string textToAppend) { this.Write(textToAppend); this.GenerationEnvironment.AppendLine(); this.endsWithNewline = true; } /// /// Write formatted text directly into the generated output /// public void Write(string format, params object[] args) { this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args)); } /// /// Write formatted text directly into the generated output /// public void WriteLine(string format, params object[] args) { this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args)); } /// /// Raise an error /// public void Error(string message) { System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError(); error.ErrorText = message; this.Errors.Add(error); } /// /// Raise a warning /// 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); } /// /// Increase the indent /// public void PushIndent(string indent) { if ((indent == null)) { throw new global::System.ArgumentNullException("indent"); } this.currentIndentField = (this.currentIndentField + indent); this.indentLengths.Add(indent.Length); } /// /// Remove the last indent that was added with PushIndent /// 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; } /// /// Remove any indentation /// public void ClearIndent() { this.indentLengths.Clear(); this.currentIndentField = ""; } #endregion #region ToString Helpers /// /// Utility class to produce culture-oriented representation of an object as a string. /// public class ToStringInstanceHelper { private System.IFormatProvider formatProviderField = global::System.Globalization.CultureInfo.InvariantCulture; /// /// Gets or sets format provider to be used by ToStringWithCulture method. /// public System.IFormatProvider FormatProvider { get { return this.formatProviderField ; } set { if ((value != null)) { this.formatProviderField = value; } } } /// /// This is called from the compile/run appdomain to convert objects within an expression block to a string /// 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(); /// /// Helper to produce culture-oriented representation of an object as a string /// 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 '------------------------------------------------------------------------------ ' ' 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. ' '------------------------------------------------------------------------------ Namespace TemplateCodeGenerators ''' '''Class to produce the template output ''' _ Partial Public Class VBCodeGenTemplate Inherits VBCodeGenTemplateBase ''' '''Create the template output ''' 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)&"' "&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)&"' "&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)&""&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(""&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)&"''' "&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)&"''' ") 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)&" ''' "&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)&" ''' "&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)&" ''' "&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)&" ''' "&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)&" ''' "&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)&" ''' "&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)&" ''' "&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)&" ''' ") 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)&" ''' "&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)&" ''' "&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)&" ''' "&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)&" ''' ") 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(" ''' "&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)&" ''' ") Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel))) Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&" ''' ") 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)&"''' "&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)&"''' ") Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(entity, region.CurrentIndentLevel))) Me.Write(""&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)&""&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(""&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)&" ''' "&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)&" ''' ") Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(navProperty, region.CurrentIndentLevel))) Me.Write(""&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)&" "&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&" "&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(" ''' "&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)&" ''' ") Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(navProperty, region.CurrentIndentLevel))) Me.Write(""&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)&" ") 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)&"''' "&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)&"''' ") Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(complex, region.CurrentIndentLevel))) Me.Write(""&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)&""&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)&" ''' "&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)&" ''' ") 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)&" ''' "&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)&" ''' ") Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(primitiveProperty, 1))) Me.Write(""&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)&" ") 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)&" ''' "&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)&" ''' ") Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(complexProperty, 1))) Me.Write(""&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)&" "&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)&" ") 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 & "") + Environment.NewLine comment += lineStart + PrefixLinesOfMultilineComment(lineStart, XmlEntityize(item.Documentation.LongDescription)) + Environment.NewLine comment += lineStart & "" 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, " {1}", 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("&", "&") text = text.Replace("<", "<").Replace(">", ">") Dim id As String = Guid.NewGuid().ToString() text = text.Replace(Environment.NewLine, id) text = text.Replace(vbCr, " ").Replace(vbLf, " ") text = text.Replace(id, Environment.NewLine) Return text.Replace("'", "'").Replace("""", """) 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) ''' ''' ''' ''' 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)() ''' ''' Responsible for helping to create source code that is ''' correctly formated and functional ''' Public Class CodeGenerationTools Private ReadOnly _textTransformation As DynamicTextTransformation Private ReadOnly _code As VBCodeProvider Private ReadOnly _ef As MetadataTools ''' ''' Initializes a new CodeGenerationTools object with the TextTransformation (T4 generated class) ''' that is currently running. ''' 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 ''' ''' 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. ''' 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 ''' ''' When true, the field names are Camel Cased, ''' otherwise they will preserve the case they ''' start with. ''' ''' Default is true. ''' 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 ''' ''' Returns the NamespaceName suggested by VS if running inside VS. Otherwise, returns ''' null. ''' 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 ''' ''' Returns a string that is safe for use as an identifier in C#. ''' Keywords are escaped. ''' Public Function Escape(ByVal name As String) As String If name Is Nothing Then Return Nothing End If Return _code.CreateEscapedIdentifier(name) End Function ''' ''' Returns the name of the TypeUsage's EdmType that is safe for ''' use as an identifier. ''' 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 ''' ''' Returns the name of the EdmMember that is safe for ''' use as an identifier. ''' Public Function Escape(ByVal member As EdmMember) As String If member Is Nothing Then Return Nothing End If Return Escape(member.Name) End Function ''' ''' Returns the name of the EdmType that is safe for ''' use as an identifier. ''' Public Function Escape(ByVal type As EdmType) As String If type Is Nothing Then Return Nothing End If Return Escape(type.Name) End Function ''' ''' Returns the name of the EdmFunction that is safe for ''' use as an identifier. ''' Public Function Escape(ByVal edmFunction As EdmFunction) As String If edmFunction Is Nothing Then Return Nothing End If Return Escape(edmFunction.Name) End Function ''' ''' Returns the name of the EnumMember that is safe for ''' use as an identifier. ''' Public Function Escape(ByVal member As EnumMember) As String If member Is Nothing Then Return Nothing End If Return Escape(member.Name) End Function ''' ''' Returns the name of the EntityContainer that is safe for ''' use as an identifier. ''' Public Function Escape(ByVal container As EntityContainer) As String If container Is Nothing Then Return Nothing End If Return Escape(container.Name) End Function ''' ''' Returns the name of the EntitySet that is safe for ''' use as an identifier. ''' Public Function Escape(ByVal edmSet As EntitySet) As String If edmSet Is Nothing Then Return Nothing End If Return Escape(edmSet.Name) End Function ''' ''' Returns the name of the StructuralType that is safe for ''' use as an identifier. ''' Public Function Escape(ByVal type As StructuralType) As String If type Is Nothing Then Return Nothing End If Return Escape(type.Name) End Function ''' ''' Returns the NamespaceName with each segment safe to ''' use as an identifier. ''' 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 ''' ''' Returns the name of the EdmMember formatted for ''' use as a field identifier. ''' ''' This method changes behavior based on the CamelCaseFields ''' setting. ''' Public Function FieldName(ByVal member As EdmMember) As String If member Is Nothing Then Return Nothing End If Return FieldName(member.Name) End Function ''' ''' Returns the name of the EntitySet formatted for ''' use as a field identifier. ''' ''' This method changes behavior based on the CamelCaseFields ''' setting. ''' 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 ''' ''' Returns the name of the Type object formatted for ''' use in source code. ''' ''' This method changes behavior based on the FullyQualifySystemTypes ''' setting. ''' Public Function Escape(ByVal clrType As Type) As String Return Escape(clrType, FullyQualifySystemTypes) End Function ''' ''' Returns the name of the Type object formatted for ''' use in source code. ''' 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 ''' ''' Returns the abstract option if the entity is Abstract, otherwise returns String.Empty ''' Public Function MustInheritOption(entity As EntityType) As String If entity.Abstract Then Return "MustInherit" End If Return String.Empty End Function ''' ''' Returns the passed in identifier with the first letter changed to lowercase ''' 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 ''' ''' 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. ''' Public Function SpaceAfter(ByVal value As String) As String Return StringAfter(value, " ") End Function ''' ''' 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. ''' Public Function SpaceBefore(ByVal value As String) As String Return StringBefore(" ", value) End Function ''' ''' If the value parameter is null or empty an empty string is returned, ''' otherwise it retuns value with append concatenated on the end. ''' 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 ''' ''' If the value parameter is null or empty an empty string is returned, ''' otherwise it retuns value with prepend concatenated on the front. ''' 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 ''' ''' Returns false and shows an error if the supplied type names aren't case-insensitively unique, ''' otherwise returns true. ''' 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 ''' ''' Returns false and shows an error if the supplied entity set names aren't case-insensitively unique, ''' otherwise returns true. ''' 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 ''' ''' Returns false and shows an error if the supplied type members names aren't case-insensitively unique, ''' otherwise returns true. ''' 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 ''' ''' Returns false and shows an error if the supplied strings aren't case-insensitively unique, ''' otherwise returns true. ''' 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 ''' ''' Returns the names of the items in the supplied collection that correspond to O-Space types. ''' 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 ''' ''' Returns the name of the supplied GlobalItem. ''' 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 ''' ''' Returns the names of the members of the supplied EdmType. ''' 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 ''' ''' 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. ''' 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 ''' ''' Retuns a literal representing the supplied value. ''' 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 ''' ''' Returns a resource string from the System.Data.Entity.Design assembly. ''' 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" ''' ''' 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. ''' ''' The type of item to return. ''' The item collection to look in. ''' The items to generate. 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 ''' ''' 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). ''' ''' The o-space type usage to get a name for. ''' The type name to use. Public Function GetTypeName(typeUsage As TypeUsage) As String Return If(typeUsage Is Nothing, Nothing, GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace := Nothing)) End Function ''' ''' 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). ''' ''' The o-space type to get a name for. ''' The type name to use. Public Function GetTypeName(edmType As EdmType) As String Return GetTypeName(edmType, isNullable := Nothing, modelNamespace := Nothing) End Function ''' ''' 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). ''' ''' The o-space type usage to get a name for. ''' If not null and the type's namespace does not match this namespace, then a ''' fully qualified name will be returned. ''' The type name to use. 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 ''' ''' 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). ''' ''' The o-space type to get a name for. ''' If not null and the type's namespace does not match this namespace, then a ''' fully qualified name will be returned. ''' The type name to use. Public Function GetTypeName(edmType As EdmType, modelNamespace As String) As String Return GetTypeName(edmType, isNullable := Nothing, modelNamespace := modelNamespace) End Function ''' ''' 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). ''' ''' The o-space type to get a name for. ''' Set this to true for nullable usage of this type. ''' If not null and the type's namespace does not match this namespace, then a ''' fully qualified name will be returned. ''' The type name to use. 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 ''' ''' Responsible for making the Entity Framework Metadata more ''' accessible for code generation. ''' Public Class MetadataTools Private ReadOnly _textTransformation As DynamicTextTransformation ''' ''' Initializes an MetadataTools Instance with the ''' TextTransformation (T4 generated class) that is currently running ''' Public Sub New(ByVal textTransformation As Object) If textTransformation Is Nothing Then Throw New ArgumentNullException("textTransformation") End If _textTransformation = DynamicTextTransformation.Create(textTransformation) End Sub ''' ''' This method returns the underlying CLR type of the O-space type corresponding to the supplied ''' Note that for an enum type this means that the type backing the enum will be returned, not the enum type itself. ''' Public Function ClrType(typeUsage As TypeUsage) As Type Return UnderlyingClrType(typeUsage.EdmType) End Function ''' ''' 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. ''' 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 ''' ''' True if the EdmProperty is a key of its DeclaringType, False otherwise. ''' 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 ''' ''' True if the EdmProperty TypeUsage is Nullable, False otherwise. ''' Public Function IsNullable(ByVal edmProp As EdmProperty) As Boolean Return edmProp IsNot Nothing AndAlso IsNullable(edmProp.TypeUsage) End Function ''' ''' True if the TypeUsage is Nullable, False otherwise. ''' 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 ''' ''' If the passed in TypeUsage represents a collection this method returns final element ''' type of the collection, otherwise it returns the value passed in. ''' 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 ''' ''' Returns the NavigationProperty that is the other end of the same association set if it is ''' available, otherwise it returns null. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' True if this entity type requires the HandleCascadeDelete method defined and the method has ''' not been defined on any base type ''' 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 ''' ''' 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 ''' 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 ''' ''' 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. ''' 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 ''' ''' True if the specified association end is the principal in an identifying relationship. ''' or if the association end has cascade delete defined. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' Returns the subtype of the EntityType in the current itemCollection ''' 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 ''' ''' Responsible for loading an EdmItemCollection from a .edmx file or .csdl files ''' Public Class MetadataLoader Private ReadOnly _textTransformation As DynamicTextTransformation ''' ''' Initializes an MetadataLoader Instance with the ''' TextTransformation (T4 generated class) that is currently running ''' Public Sub New(ByVal textTransformation As Object) If textTransformation Is Nothing Then Throw New ArgumentNullException("textTransformation") End If _textTransformation = DynamicTextTransformation.Create(textTransformation) End Sub ''' ''' 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 ''' 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 ''' ''' Create an EdmItemCollection loaded with the metadata provided ''' 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 ''' ''' Attempts to create a EdmItemCollection from the specified metadata file ''' Public Function TryCreateEdmItemCollection(ByVal sourcePath As String, ByRef edmItemCollection As EdmItemCollection) As Boolean Return TryCreateEdmItemCollection(sourcePath, Nothing, edmItemCollection) End Function ''' ''' Attempts to create a EdmItemCollection from the specified metadata file ''' 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 ''' ''' Attempts to create a StoreItemCollection from the specified metadata file ''' 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 ''' ''' Attempts to create a StorageMappingItemCollection from the specified metadata file, EdmItemCollection, and StoreItemCollection ''' 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 ''' ''' Gets the Model Namespace from the provided schema file. ''' 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 ''' ''' Returns true if the specified file path is valid ''' 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 ''' ''' base class for ItemCollectionBuilder classes that ''' load the specific types of metadata ''' Private MustInherit Class ItemCollectionBuilder Private ReadOnly _textTransformation As DynamicTextTransformation Private ReadOnly _fileExtension As String Private ReadOnly _edmxSectionName As String Private ReadOnly _rootElementName As String ''' ''' FileExtension for individual (non-edmx) metadata file for this ''' specific ItemCollection type ''' Public ReadOnly Property FileExtension() As String Get Return _fileExtension End Get End Property ''' ''' The name of the XmlElement in the .edmx element ''' to find this ItemCollection's metadata ''' Public ReadOnly Property EdmxSectionName() As String Get Return _edmxSectionName End Get End Property ''' ''' The name of the root element of this ItemCollection's metadata ''' Public ReadOnly Property RootElementName() As String Get Return _rootElementName End Get End Property ''' ''' Method to build the appropriate ItemCollection ''' Protected MustOverride Function CreateItemCollection(ByVal readers As IEnumerable(Of XmlReader), ByRef errors As IList(Of EdmSchemaError)) As ItemCollection ''' ''' Ctor to setup the ItemCollectionBuilder members ''' 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 ''' ''' Selects a namespace from the supplied constants. ''' Protected MustOverride Function GetNamespace(ByVal constants As SchemaConstants) As String ''' ''' Try to create an ItemCollection loaded with the metadata provided ''' 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 ''' ''' Tries to load the root element from the metadata file provided ''' 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 ''' ''' Tries to load the root element from the provided edmxDocument ''' 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 ''' ''' Tries to load the root element from the provided .edmx metadata file ''' 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 ''' ''' Takes an Enumerable of EdmSchemaErrors, and adds them ''' to the errors collection of the template class ''' 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 ''' ''' Builder class for creating a StorageMappingItemCollection ''' 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 ''' ''' Selects a namespace from the supplied constants. ''' Protected Overrides Function GetNamespace(ByVal constants As SchemaConstants) As String Return constants.MslNamespace End Function End Class ''' ''' Builder class for creating a StoreItemCollection ''' 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 ''' ''' Selects a namespace from the supplied constants. ''' Protected Overrides Function GetNamespace(ByVal constants As SchemaConstants) As String Return constants.SsdlNamespace End Function End Class ''' ''' Builder class for creating a EdmItemCollection ''' 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 ''' ''' Selects a namespace from the supplied constants. ''' Protected Overrides Function GetNamespace(ByVal constants As SchemaConstants) As String Return constants.CsdlNamespace End Function End Class End Class ''' ''' Responsible for encapsulating the retrieval and translation of the CodeGeneration ''' annotations in the EntityFramework Metadata to a form that is useful in code generation. ''' 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} _ } ''' ''' Gets the accessibility that should be applied to a type being generated from the provided GlobalItem. ''' ''' defaults to public if no annotation is found. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' Gets the accessibility that should be applied to a method being generated from the provided EdmFunction. ''' ''' defaults to public if no annotation is found. ''' 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 ''' ''' Responsible for creating source code regions in code when the loop inside ''' actually produces something. ''' 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 ''' ''' Initializes an CodeRegion instance with the ''' TextTransformation (T4 generated class) that is currently running ''' Public Sub New(ByVal textTransformation As Object) If textTransformation Is Nothing Then Throw New ArgumentNullException("textTransformation") End If _textTransformation = DynamicTextTransformation.Create(textTransformation) End Sub ''' ''' Initializes an CodeRegion instance with the ''' TextTransformation (T4 generated class) that is currently running, ''' and the indent level to start the first region at. ''' 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 ''' ''' Starts the begining of a region ''' Public Sub Begin(ByVal regionName As String) If regionName Is Nothing Then Throw New ArgumentNullException("regionName") End If Begin(regionName, 1) End Sub ''' ''' Start the begining of a region, indented ''' the numbers of levels specified ''' 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 ''' ''' Ends a region, or totaly removes it if nothing ''' was generted since the begining of the region. ''' Public Sub [End]() [End](1) End Sub ''' ''' Ends a region, or totaly removes it if nothing ''' was generted since the begining of the region, also outdents ''' the number of levels specified. ''' 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 ''' ''' Gets the current indent level that the next end region statement will be written ''' at ''' Public ReadOnly Property CurrentIndentLevel() As Integer Get Return _regionIndentLevel End Get End Property ''' ''' Get a string of spaces equivelent to the number of indents ''' desired. ''' 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 ''' ''' Responsible for collecting together the actual method parameters ''' and the parameters that need to be sent to the Execute method. ''' 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 ''' ''' Creates a set of FunctionImportParameter objects from the parameters passed in. ''' 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 ''' ''' Given an identifier, makes it unique within the scope by adding ''' a suffix (1, 2, 3, ...), and returns the adjusted identifier. ''' 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 ''' ''' Responsible for marking the various sections of the generation, ''' so they can be split up into separate files ''' Public Class EntityFrameworkTemplateFileManager ''' ''' Creates the VsEntityFrameworkTemplateFileManager if VS is detected, otherwise ''' creates the file system version. ''' 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 ''' ''' Initializes an EntityFrameworkTemplateFileManager Instance with the ''' TextTransformation (T4 generated class) that is currently running ''' 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 ''' ''' 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. ''' 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 ''' ''' Produce the template output files. ''' 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)) ''' ''' Creates an instance of the VsEntityFrameworkTemplateFileManager class with the IDynamicHost instance ''' 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 ''' ''' 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 ''' 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 ''' ''' 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. ''' 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 ''' ''' Gets the value of the wrapped TextTranformation instance's GenerationEnvironment property ''' Public ReadOnly Property GenerationEnvironment() As StringBuilder Get Return DirectCast(_generationEnvironment.GetValue(_instance, Nothing), StringBuilder) End Get End Property ''' ''' Gets the value of the wrapped TextTranformation instance's Errors property ''' Public ReadOnly Property Errors() As System.CodeDom.Compiler.CompilerErrorCollection Get Return DirectCast(_errors.GetValue(_instance, Nothing), System.CodeDom.Compiler.CompilerErrorCollection) End Get End Property ''' ''' Calls the wrapped TextTranformation instance's Write method. ''' Public Sub Write(ByVal text As String) _write.Invoke(_instance, New Object() {text}) End Sub ''' ''' Calls the wrapped TextTranformation instance's WriteLine method. ''' Public Sub WriteLine(ByVal text As String) _writeLine.Invoke(_instance, New Object() {text}) End Sub ''' ''' 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 ''' 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 ''' ''' Reponsible for abstracting the use of Host between times ''' when it is available and not ''' Public Interface IDynamicHost ''' ''' An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue ''' Function ResolveParameterValue(ByVal id As String, ByVal name As String, ByVal otherName As String) As String ''' ''' An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath ''' Function ResolvePath(ByVal path As String) As String ''' ''' An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile ''' ReadOnly Property TemplateFile() As String ''' ''' Returns the Host instance cast as an IServiceProvider ''' Function AsIServiceProvider() As IServiceProvider End Interface ''' ''' 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. ''' 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 ''' ''' Creates an instance of the DynamicHost class around the passed in ''' Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost shapped instance passed in. ''' 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 ''' ''' A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue ''' 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 ''' ''' A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath ''' Public Function ResolvePath(ByVal path As String) As String Implements IDynamicHost.ResolvePath Return DirectCast(_resolvePath.Invoke(_instance, New Object() {path}), String) End Function ''' ''' A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile ''' Public ReadOnly Property TemplateFile() As String Implements IDynamicHost.TemplateFile Get Return DirectCast(_templateFile.GetValue(_instance, Nothing), String) End Get End Property ''' ''' Returns the Host instance cast as an IServiceProvider ''' Public Function AsIServiceProvider() As IServiceProvider Implements IDynamicHost.AsIServiceProvider Return TryCast(_instance, IServiceProvider) End Function End Class ''' ''' 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. ''' Public Class NullHost Implements IDynamicHost ''' ''' An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue ''' that simply retuns null. ''' Public Function ResolveParameterValue(ByVal id As String, ByVal name As String, ByVal otherName As String) As String Implements IDynamicHost.ResolveParameterValue Return Nothing End Function ''' ''' An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath ''' that simply retuns the path passed in. ''' Public Function ResolvePath(ByVal path As String) As String Implements IDynamicHost.ResolvePath Return path End Function ''' ''' An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile ''' that returns null. ''' Public ReadOnly Property TemplateFile() As String Implements IDynamicHost.TemplateFile Get Return Nothing End Get End Property ''' ''' Returns null. ''' Public Function AsIServiceProvider() As IServiceProvider Implements IDynamicHost.AsIServiceProvider Return Nothing End Function End Class ''' ''' Responsible for encapsulating the constants defined in Metadata ''' 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" ''' '''Base class for this transformation ''' _ 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" ''' '''The string builder that generation-time code is using to assemble generated output ''' 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 ''' '''The error collection for the generation process ''' 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 ''' '''A list of the lengths of each indent that was added with PushIndent ''' 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 ''' '''Gets the current indent we use when adding lines to the output ''' Public ReadOnly Property CurrentIndent() As String Get Return Me.currentIndentField End Get End Property ''' '''Current transformation session ''' 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" ''' '''Write text directly into the generated output ''' 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 ''' '''Write text directly into the generated output ''' Public Overloads Sub WriteLine(ByVal textToAppend As String) Me.Write(textToAppend) Me.GenerationEnvironment.AppendLine Me.endsWithNewline = true End Sub ''' '''Write formatted text directly into the generated output ''' Public Overloads Sub Write(ByVal format As String, ByVal args() As Object) Me.Write(String.Format(Global.System.Globalization.CultureInfo.CurrentCulture, format, args)) End Sub ''' '''Write formatted text directly into the generated output ''' Public Overloads Sub WriteLine(ByVal format As String, ByVal args() As Object) Me.WriteLine(String.Format(Global.System.Globalization.CultureInfo.CurrentCulture, format, args)) End Sub ''' '''Raise an error ''' 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 ''' '''Raise a warning ''' 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 ''' '''Increase the indent ''' 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 ''' '''Remove the last indent that was added with PushIndent ''' 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 ''' '''Remove any indentation ''' Public Sub ClearIndent() Me.indentLengths.Clear Me.currentIndentField = "" End Sub #End Region #Region "ToString Helpers" ''' '''Utility class to produce culture-oriented representation of an object as a string. ''' Public Class ToStringInstanceHelper Private formatProviderField As System.IFormatProvider = Global.System.Globalization.CultureInfo.InvariantCulture ''' '''Gets or sets format provider to be used by ToStringWithCulture method. ''' 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 ''' '''This is called from the compile/run appdomain to convert objects within an expression block to a string ''' 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() ''' '''Helper to produce culture-oriented representation of an object as a string ''' 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 '------------------------------------------------------------------------------ ' ' 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. ' '------------------------------------------------------------------------------ Namespace TemplateCodeGenerators ''' '''Class to produce the template output ''' _ Partial Public Class VBCodeGenTemplateV50 Inherits VBCodeGenTemplateV50Base ''' '''Create the template output ''' 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)&"' "&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)&"' "&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)) '''''''' '''''''' Write Relationship Attributes. '''''''' region.Begin(CodeGenerationTools.GetResourceString("Template_RegionRelationships")) For Each association As AssociationType in GetSourceSchemaTypes(Of AssociationType)() 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)&"''' "&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)&"''' ") 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)&" ''' "&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)&" ''' "&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)&" ''' "&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)&" ''' "&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)&" ''' "&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)&" ''' "&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)&" ''' "&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)&" ''' ") 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)&" ''' "&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)&" ''' "&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)&" ''' "&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)&" ''' ") 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)&" "&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)&" ''' "&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)&" ''' ") 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(" ''' "&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)&" ''' ") Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(edmFunction, region.CurrentIndentLevel))) Me.Write(""&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&" ''' ") 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)&"''' "&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)&"''' ") Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(entity, region.CurrentIndentLevel))) Me.Write(""&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)&""&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(""&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)&" ''' "&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)&" ''' ") Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(navProperty, region.CurrentIndentLevel))) Me.Write(""&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)&" "&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&" "&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(" ''' "&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)&" ''' ") Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(navProperty, region.CurrentIndentLevel))) Me.Write(""&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)&" ") 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)&"''' "&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)&"''' ") Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(complex, region.CurrentIndentLevel))) Me.Write(""&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)&""&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)&"''' "&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)&"''' ") Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(enumType, region.CurrentIndentLevel))) Me.Write(""&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)) If enumType.IsFlags Then Me.Write(""&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(" ''' "&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)&" ''' ") Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(member, region.CurrentIndentLevel + 1))) 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(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)&" ''' "&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)&" ''' ") 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)&" ''' "&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)&" ''' ") Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(simpleProperty, 1))) Me.Write(""&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)&" ") 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)&" ''' "&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)&" ''' ") Me.Write(Me.ToStringHelper.ToStringWithCulture(LongDescriptionCommentElement(complexProperty, 1))) Me.Write(""&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)&" "&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)&" ") 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 & "") + Environment.NewLine comment += lineStart + PrefixLinesOfMultilineComment(lineStart, XmlEntityize(item.Documentation.LongDescription)) + Environment.NewLine comment += lineStart & "" 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, " {1}", 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("&", "&") text = text.Replace("<", "<").Replace(">", ">") Dim id As String = Guid.NewGuid().ToString() text = text.Replace(Environment.NewLine, id) text = text.Replace(vbCr, " ").Replace(vbLf, " ") text = text.Replace(id, Environment.NewLine) Return text.Replace("'", "'").Replace("""", """) 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) ''' ''' ''' ''' 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)() ''' ''' Responsible for helping to create source code that is ''' correctly formated and functional ''' Public Class CodeGenerationTools Private ReadOnly _textTransformation As DynamicTextTransformation Private ReadOnly _code As VBCodeProvider Private ReadOnly _ef As MetadataTools ''' ''' Initializes a new CodeGenerationTools object with the TextTransformation (T4 generated class) ''' that is currently running. ''' 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 ''' ''' 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. ''' 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 ''' ''' When true, the field names are Camel Cased, ''' otherwise they will preserve the case they ''' start with. ''' ''' Default is true. ''' 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 ''' ''' Returns the NamespaceName suggested by VS if running inside VS. Otherwise, returns ''' null. ''' 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 ''' ''' Returns a string that is safe for use as an identifier in C#. ''' Keywords are escaped. ''' Public Function Escape(ByVal name As String) As String If name Is Nothing Then Return Nothing End If Return _code.CreateEscapedIdentifier(name) End Function ''' ''' Returns the name of the TypeUsage's EdmType that is safe for ''' use as an identifier. ''' 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 ''' ''' Returns the name of the EdmMember that is safe for ''' use as an identifier. ''' Public Function Escape(ByVal member As EdmMember) As String If member Is Nothing Then Return Nothing End If Return Escape(member.Name) End Function ''' ''' Returns the name of the EdmType that is safe for ''' use as an identifier. ''' Public Function Escape(ByVal type As EdmType) As String If type Is Nothing Then Return Nothing End If Return Escape(type.Name) End Function ''' ''' Returns the name of the EdmFunction that is safe for ''' use as an identifier. ''' Public Function Escape(ByVal edmFunction As EdmFunction) As String If edmFunction Is Nothing Then Return Nothing End If Return Escape(edmFunction.Name) End Function ''' ''' Returns the name of the EnumMember that is safe for ''' use as an identifier. ''' Public Function Escape(ByVal member As EnumMember) As String If member Is Nothing Then Return Nothing End If Return Escape(member.Name) End Function ''' ''' Returns the name of the EntityContainer that is safe for ''' use as an identifier. ''' Public Function Escape(ByVal container As EntityContainer) As String If container Is Nothing Then Return Nothing End If Return Escape(container.Name) End Function ''' ''' Returns the name of the EntitySet that is safe for ''' use as an identifier. ''' Public Function Escape(ByVal edmSet As EntitySet) As String If edmSet Is Nothing Then Return Nothing End If Return Escape(edmSet.Name) End Function ''' ''' Returns the name of the StructuralType that is safe for ''' use as an identifier. ''' Public Function Escape(ByVal type As StructuralType) As String If type Is Nothing Then Return Nothing End If Return Escape(type.Name) End Function ''' ''' Returns the NamespaceName with each segment safe to ''' use as an identifier. ''' 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 ''' ''' Returns the name of the EdmMember formatted for ''' use as a field identifier. ''' ''' This method changes behavior based on the CamelCaseFields ''' setting. ''' Public Function FieldName(ByVal member As EdmMember) As String If member Is Nothing Then Return Nothing End If Return FieldName(member.Name) End Function ''' ''' Returns the name of the EntitySet formatted for ''' use as a field identifier. ''' ''' This method changes behavior based on the CamelCaseFields ''' setting. ''' 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 ''' ''' Returns the name of the Type object formatted for ''' use in source code. ''' ''' This method changes behavior based on the FullyQualifySystemTypes ''' setting. ''' Public Function Escape(ByVal clrType As Type) As String Return Escape(clrType, FullyQualifySystemTypes) End Function ''' ''' Returns the name of the Type object formatted for ''' use in source code. ''' 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 ''' ''' Returns the abstract option if the entity is Abstract, otherwise returns String.Empty ''' Public Function MustInheritOption(entity As EntityType) As String If entity.Abstract Then Return "MustInherit" End If Return String.Empty End Function ''' ''' Returns the passed in identifier with the first letter changed to lowercase ''' 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 ''' ''' 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. ''' Public Function SpaceAfter(ByVal value As String) As String Return StringAfter(value, " ") End Function ''' ''' 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. ''' Public Function SpaceBefore(ByVal value As String) As String Return StringBefore(" ", value) End Function ''' ''' If the value parameter is null or empty an empty string is returned, ''' otherwise it retuns value with append concatenated on the end. ''' 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 ''' ''' If the value parameter is null or empty an empty string is returned, ''' otherwise it retuns value with prepend concatenated on the front. ''' 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 ''' ''' Returns false and shows an error if the supplied type names aren't case-insensitively unique, ''' otherwise returns true. ''' 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 ''' ''' Returns false and shows an error if the supplied entity set names aren't case-insensitively unique, ''' otherwise returns true. ''' 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 ''' ''' Returns false and shows an error if the supplied type members names aren't case-insensitively unique, ''' otherwise returns true. ''' 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 ''' ''' Returns false and shows an error if the supplied strings aren't case-insensitively unique, ''' otherwise returns true. ''' 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 ''' ''' Returns the names of the items in the supplied collection that correspond to O-Space types. ''' 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 ''' ''' Returns the name of the supplied GlobalItem. ''' 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 ''' ''' Returns the names of the members of the supplied EdmType. ''' 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 ''' ''' 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. ''' 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 ''' ''' Retuns a literal representing the supplied value. ''' 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 ''' ''' Returns a resource string from the System.Data.Entity.Design assembly. ''' 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" ''' ''' 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. ''' ''' The type of item to return. ''' The item collection to look in. ''' The items to generate. 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 ''' ''' 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). ''' ''' The o-space type usage to get a name for. ''' The type name to use. Public Function GetTypeName(typeUsage As TypeUsage) As String Return If(typeUsage Is Nothing, Nothing, GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace := Nothing)) End Function ''' ''' 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). ''' ''' The o-space type to get a name for. ''' The type name to use. Public Function GetTypeName(edmType As EdmType) As String Return GetTypeName(edmType, isNullable := Nothing, modelNamespace := Nothing) End Function ''' ''' 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). ''' ''' The o-space type usage to get a name for. ''' If not null and the type's namespace does not match this namespace, then a ''' fully qualified name will be returned. ''' The type name to use. 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 ''' ''' 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). ''' ''' The o-space type to get a name for. ''' If not null and the type's namespace does not match this namespace, then a ''' fully qualified name will be returned. ''' The type name to use. Public Function GetTypeName(edmType As EdmType, modelNamespace As String) As String Return GetTypeName(edmType, isNullable := Nothing, modelNamespace := modelNamespace) End Function ''' ''' 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). ''' ''' The o-space type to get a name for. ''' Set this to true for nullable usage of this type. ''' If not null and the type's namespace does not match this namespace, then a ''' fully qualified name will be returned. ''' The type name to use. 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 ''' ''' Responsible for making the Entity Framework Metadata more ''' accessible for code generation. ''' Public Class MetadataTools Private ReadOnly _textTransformation As DynamicTextTransformation ''' ''' Initializes an MetadataTools Instance with the ''' TextTransformation (T4 generated class) that is currently running ''' Public Sub New(ByVal textTransformation As Object) If textTransformation Is Nothing Then Throw New ArgumentNullException("textTransformation") End If _textTransformation = DynamicTextTransformation.Create(textTransformation) End Sub ''' ''' This method returns the underlying CLR type of the O-space type corresponding to the supplied ''' Note that for an enum type this means that the type backing the enum will be returned, not the enum type itself. ''' Public Function ClrType(typeUsage As TypeUsage) As Type Return UnderlyingClrType(typeUsage.EdmType) End Function ''' ''' 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. ''' 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 ''' ''' True if the EdmProperty is a key of its DeclaringType, False otherwise. ''' 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 ''' ''' True if the EdmProperty TypeUsage is Nullable, False otherwise. ''' Public Function IsNullable(ByVal edmProp As EdmProperty) As Boolean Return edmProp IsNot Nothing AndAlso IsNullable(edmProp.TypeUsage) End Function ''' ''' True if the TypeUsage is Nullable, False otherwise. ''' 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 ''' ''' If the passed in TypeUsage represents a collection this method returns final element ''' type of the collection, otherwise it returns the value passed in. ''' 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 ''' ''' Returns the NavigationProperty that is the other end of the same association set if it is ''' available, otherwise it returns null. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' True if this entity type requires the HandleCascadeDelete method defined and the method has ''' not been defined on any base type ''' 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 ''' ''' 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 ''' 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 ''' ''' 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. ''' 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 ''' ''' True if the specified association end is the principal in an identifying relationship. ''' or if the association end has cascade delete defined. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' Returns the subtype of the EntityType in the current itemCollection ''' 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 ''' ''' Responsible for loading an EdmItemCollection from a .edmx file or .csdl files ''' Public Class MetadataLoader Private ReadOnly _textTransformation As DynamicTextTransformation ''' ''' Initializes an MetadataLoader Instance with the ''' TextTransformation (T4 generated class) that is currently running ''' Public Sub New(ByVal textTransformation As Object) If textTransformation Is Nothing Then Throw New ArgumentNullException("textTransformation") End If _textTransformation = DynamicTextTransformation.Create(textTransformation) End Sub ''' ''' 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 ''' 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 ''' ''' Create an EdmItemCollection loaded with the metadata provided ''' 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 ''' ''' Attempts to create a EdmItemCollection from the specified metadata file ''' Public Function TryCreateEdmItemCollection(ByVal sourcePath As String, ByRef edmItemCollection As EdmItemCollection) As Boolean Return TryCreateEdmItemCollection(sourcePath, Nothing, edmItemCollection) End Function ''' ''' Attempts to create a EdmItemCollection from the specified metadata file ''' 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 ''' ''' Attempts to create a StoreItemCollection from the specified metadata file ''' 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 ''' ''' Attempts to create a StorageMappingItemCollection from the specified metadata file, EdmItemCollection, and StoreItemCollection ''' 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 ''' ''' Gets the Model Namespace from the provided schema file. ''' 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 ''' ''' Returns true if the specified file path is valid ''' 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 ''' ''' base class for ItemCollectionBuilder classes that ''' load the specific types of metadata ''' Private MustInherit Class ItemCollectionBuilder Private ReadOnly _textTransformation As DynamicTextTransformation Private ReadOnly _fileExtension As String Private ReadOnly _edmxSectionName As String Private ReadOnly _rootElementName As String ''' ''' FileExtension for individual (non-edmx) metadata file for this ''' specific ItemCollection type ''' Public ReadOnly Property FileExtension() As String Get Return _fileExtension End Get End Property ''' ''' The name of the XmlElement in the .edmx element ''' to find this ItemCollection's metadata ''' Public ReadOnly Property EdmxSectionName() As String Get Return _edmxSectionName End Get End Property ''' ''' The name of the root element of this ItemCollection's metadata ''' Public ReadOnly Property RootElementName() As String Get Return _rootElementName End Get End Property ''' ''' Method to build the appropriate ItemCollection ''' Protected MustOverride Function CreateItemCollection(ByVal readers As IEnumerable(Of XmlReader), ByRef errors As IList(Of EdmSchemaError)) As ItemCollection ''' ''' Ctor to setup the ItemCollectionBuilder members ''' 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 ''' ''' Selects a namespace from the supplied constants. ''' Protected MustOverride Function GetNamespace(ByVal constants As SchemaConstants) As String ''' ''' Try to create an ItemCollection loaded with the metadata provided ''' 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 ''' ''' Tries to load the root element from the metadata file provided ''' 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 ''' ''' Tries to load the root element from the provided edmxDocument ''' 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 ''' ''' Tries to load the root element from the provided .edmx metadata file ''' 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 ''' ''' Takes an Enumerable of EdmSchemaErrors, and adds them ''' to the errors collection of the template class ''' 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 ''' ''' Builder class for creating a StorageMappingItemCollection ''' 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 ''' ''' Selects a namespace from the supplied constants. ''' Protected Overrides Function GetNamespace(ByVal constants As SchemaConstants) As String Return constants.MslNamespace End Function End Class ''' ''' Builder class for creating a StoreItemCollection ''' 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 ''' ''' Selects a namespace from the supplied constants. ''' Protected Overrides Function GetNamespace(ByVal constants As SchemaConstants) As String Return constants.SsdlNamespace End Function End Class ''' ''' Builder class for creating a EdmItemCollection ''' 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 ''' ''' Selects a namespace from the supplied constants. ''' Protected Overrides Function GetNamespace(ByVal constants As SchemaConstants) As String Return constants.CsdlNamespace End Function End Class End Class ''' ''' Responsible for encapsulating the retrieval and translation of the CodeGeneration ''' annotations in the EntityFramework Metadata to a form that is useful in code generation. ''' 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} _ } ''' ''' Gets the accessibility that should be applied to a type being generated from the provided GlobalItem. ''' ''' defaults to public if no annotation is found. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' 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. ''' 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 ''' ''' Gets the accessibility that should be applied to a method being generated from the provided EdmFunction. ''' ''' defaults to public if no annotation is found. ''' 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 ''' ''' Responsible for creating source code regions in code when the loop inside ''' actually produces something. ''' 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 ''' ''' Initializes an CodeRegion instance with the ''' TextTransformation (T4 generated class) that is currently running ''' Public Sub New(ByVal textTransformation As Object) If textTransformation Is Nothing Then Throw New ArgumentNullException("textTransformation") End If _textTransformation = DynamicTextTransformation.Create(textTransformation) End Sub ''' ''' Initializes an CodeRegion instance with the ''' TextTransformation (T4 generated class) that is currently running, ''' and the indent level to start the first region at. ''' 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 ''' ''' Starts the begining of a region ''' Public Sub Begin(ByVal regionName As String) If regionName Is Nothing Then Throw New ArgumentNullException("regionName") End If Begin(regionName, 1) End Sub ''' ''' Start the begining of a region, indented ''' the numbers of levels specified ''' 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 ''' ''' Ends a region, or totaly removes it if nothing ''' was generted since the begining of the region. ''' Public Sub [End]() [End](1) End Sub ''' ''' Ends a region, or totaly removes it if nothing ''' was generted since the begining of the region, also outdents ''' the number of levels specified. ''' 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 ''' ''' Gets the current indent level that the next end region statement will be written ''' at ''' Public ReadOnly Property CurrentIndentLevel() As Integer Get Return _regionIndentLevel End Get End Property ''' ''' Get a string of spaces equivelent to the number of indents ''' desired. ''' 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 ''' ''' Responsible for collecting together the actual method parameters ''' and the parameters that need to be sent to the Execute method. ''' 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 ''' ''' Creates a set of FunctionImportParameter objects from the parameters passed in. ''' 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 ''' ''' Given an identifier, makes it unique within the scope by adding ''' a suffix (1, 2, 3, ...), and returns the adjusted identifier. ''' 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 ''' ''' Responsible for marking the various sections of the generation, ''' so they can be split up into separate files ''' Public Class EntityFrameworkTemplateFileManager ''' ''' Creates the VsEntityFrameworkTemplateFileManager if VS is detected, otherwise ''' creates the file system version. ''' 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 ''' ''' Initializes an EntityFrameworkTemplateFileManager Instance with the ''' TextTransformation (T4 generated class) that is currently running ''' 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 ''' ''' 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. ''' 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 ''' ''' Produce the template output files. ''' 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)) ''' ''' Creates an instance of the VsEntityFrameworkTemplateFileManager class with the IDynamicHost instance ''' 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 ''' ''' 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 ''' 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 ''' ''' 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. ''' 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 ''' ''' Gets the value of the wrapped TextTranformation instance's GenerationEnvironment property ''' Public ReadOnly Property GenerationEnvironment() As StringBuilder Get Return DirectCast(_generationEnvironment.GetValue(_instance, Nothing), StringBuilder) End Get End Property ''' ''' Gets the value of the wrapped TextTranformation instance's Errors property ''' Public ReadOnly Property Errors() As System.CodeDom.Compiler.CompilerErrorCollection Get Return DirectCast(_errors.GetValue(_instance, Nothing), System.CodeDom.Compiler.CompilerErrorCollection) End Get End Property ''' ''' Calls the wrapped TextTranformation instance's Write method. ''' Public Sub Write(ByVal text As String) _write.Invoke(_instance, New Object() {text}) End Sub ''' ''' Calls the wrapped TextTranformation instance's WriteLine method. ''' Public Sub WriteLine(ByVal text As String) _writeLine.Invoke(_instance, New Object() {text}) End Sub ''' ''' 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 ''' 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 ''' ''' Reponsible for abstracting the use of Host between times ''' when it is available and not ''' Public Interface IDynamicHost ''' ''' An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue ''' Function ResolveParameterValue(ByVal id As String, ByVal name As String, ByVal otherName As String) As String ''' ''' An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath ''' Function ResolvePath(ByVal path As String) As String ''' ''' An abstracted call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile ''' ReadOnly Property TemplateFile() As String ''' ''' Returns the Host instance cast as an IServiceProvider ''' Function AsIServiceProvider() As IServiceProvider End Interface ''' ''' 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. ''' 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 ''' ''' Creates an instance of the DynamicHost class around the passed in ''' Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost shapped instance passed in. ''' 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 ''' ''' A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue ''' 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 ''' ''' A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath ''' Public Function ResolvePath(ByVal path As String) As String Implements IDynamicHost.ResolvePath Return DirectCast(_resolvePath.Invoke(_instance, New Object() {path}), String) End Function ''' ''' A call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile ''' Public ReadOnly Property TemplateFile() As String Implements IDynamicHost.TemplateFile Get Return DirectCast(_templateFile.GetValue(_instance, Nothing), String) End Get End Property ''' ''' Returns the Host instance cast as an IServiceProvider ''' Public Function AsIServiceProvider() As IServiceProvider Implements IDynamicHost.AsIServiceProvider Return TryCast(_instance, IServiceProvider) End Function End Class ''' ''' 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. ''' Public Class NullHost Implements IDynamicHost ''' ''' An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolveParameterValue ''' that simply retuns null. ''' Public Function ResolveParameterValue(ByVal id As String, ByVal name As String, ByVal otherName As String) As String Implements IDynamicHost.ResolveParameterValue Return Nothing End Function ''' ''' An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost ResolvePath ''' that simply retuns the path passed in. ''' Public Function ResolvePath(ByVal path As String) As String Implements IDynamicHost.ResolvePath Return path End Function ''' ''' An abstraction of the call to Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost TemplateFile ''' that returns null. ''' Public ReadOnly Property TemplateFile() As String Implements IDynamicHost.TemplateFile Get Return Nothing End Get End Property ''' ''' Returns null. ''' Public Function AsIServiceProvider() As IServiceProvider Implements IDynamicHost.AsIServiceProvider Return Nothing End Function End Class ''' ''' Responsible for encapsulating the constants defined in Metadata ''' 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" ''' '''Base class for this transformation ''' _ 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" ''' '''The string builder that generation-time code is using to assemble generated output ''' 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 ''' '''The error collection for the generation process ''' 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 ''' '''A list of the lengths of each indent that was added with PushIndent ''' 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 ''' '''Gets the current indent we use when adding lines to the output ''' Public ReadOnly Property CurrentIndent() As String Get Return Me.currentIndentField End Get End Property ''' '''Current transformation session ''' 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" ''' '''Write text directly into the generated output ''' 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 ''' '''Write text directly into the generated output ''' Public Overloads Sub WriteLine(ByVal textToAppend As String) Me.Write(textToAppend) Me.GenerationEnvironment.AppendLine Me.endsWithNewline = true End Sub ''' '''Write formatted text directly into the generated output ''' Public Overloads Sub Write(ByVal format As String, ByVal args() As Object) Me.Write(String.Format(Global.System.Globalization.CultureInfo.CurrentCulture, format, args)) End Sub ''' '''Write formatted text directly into the generated output ''' Public Overloads Sub WriteLine(ByVal format As String, ByVal args() As Object) Me.WriteLine(String.Format(Global.System.Globalization.CultureInfo.CurrentCulture, format, args)) End Sub ''' '''Raise an error ''' 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 ''' '''Raise a warning ''' 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 ''' '''Increase the indent ''' 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 ''' '''Remove the last indent that was added with PushIndent ''' 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 ''' '''Remove any indentation ''' Public Sub ClearIndent() Me.indentLengths.Clear Me.currentIndentField = "" End Sub #End Region #Region "ToString Helpers" ''' '''Utility class to produce culture-oriented representation of an object as a string. ''' Public Class ToStringInstanceHelper Private formatProviderField As System.IFormatProvider = Global.System.Globalization.CultureInfo.InvariantCulture ''' '''Gets or sets format provider to be used by ToStringWithCulture method. ''' 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 ''' '''This is called from the compile/run appdomain to convert objects within an expression block to a string ''' 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() ''' '''Helper to produce culture-oriented representation of an object as a string ''' Public ReadOnly Property ToStringHelper() As ToStringInstanceHelper Get Return Me.toStringHelperField End Get End Property #End Region End Class #End Region End Namespace 0EG1Srݧ#Sǎ1AP`jh5S8nF IN܉s>{պE4 HuD|'y J$ 5.;A o+ kH !ÞSystem.Data.Entity.Design.pdb _CorDllMainmscoree.dll% `="' 8Ph Fg$IBC PROFILE_DATA(б~`B&U c[ eF7   #&+,0n2~ (3 1^ " (( u  &*&6\&`@f    %H   0 < + {GXi %(JNtB#<mf $8 09FOQ_lqJ )-68FHQ +7@BP- $=?Uluw.%'=FHVdlK, ^`    C [ nZ T#?gi@1 .>?@gi .;L((F7xH.!79G >,T#<DNepP" $"3"N" ; L#K.57QSf 1 * O-9M%#Mbs g )2;O $$C  & /9$ )" ,  & ,  & ,  &XO Z$2TUHIi q#:W$ )="' & 5 %'*01oHHNWHYHgH|T.T'~" 2;JL X `hqsv|}N4           $$&HCHKGYH[HbIkmqxy;HH 1HiHHH4H4H44HHHHvH[|  rrr:'>GKIrWKY'TH H H'H/7|@4BHP4R5H=HHHH&&.?TGR_TbqQ}LT%T,T<bTTTTTTTTTTTTTTFTT T,T-;;;               7     T T T T Tt _*_8_JNW`j +-Zw.*HPaelm:<hqs-IE+#{AGnqwx ' # 2Ec 9 . !'(*-34 D  *3 5 C   )(  @c||,|5|P|_9aC  :$&|A|R|e|nCv9999999999999999999999999 9  9 9  9 9  7 7  7 7 7 7 7 @"+-Zw                bQO4, (8*_ 4H]) %8'5'' ##! .?OQXt~ B$ B$ J$w "5JRadjkntuACUqs ;COY{ [ NE  ( <C T   $1@ J <9H H >< ><>HHHT< >< >< >< >< >< ><: 5?APY[_fgtv  z!-:GQ?n~   | O p . 24CLN\hjyJv&aj wh3h .f".XJgw  k)+@IKYj Vh7 ^  "'57>'F'H`e'j`s'u'y'''  3   8'' ! !46v',>Qct7* /+(   !  ,   * ) WG.@vNP_hjxM#^fF$u .0pHp`hjmstz%/ 8FI MZx p Ap p p ( &N!LTVyq :(*88:jsu X$(7H2735 P k tv: "O 3D 3 `$ 3$A$^$ K % aX%8CVS *8@BEKLR3DQ!i   #+@CK`U %'=QS F  .6Dy #0<IQ^jw   nl I                              j ' ML R+58E L ($&02<>J % ?* **&".+-*;=& 2 <$ $$"H+$-$;$ Q('O  =() }'?<y^&F$!{q0S& A)SуCӃԃ SC "  "  cu "e " ʚ                     ŀ 䀀    "?͜"             Yx       ƝĀΝ         qB69 3S" !.C"i- C     !!!!C""""#####"##"#"""#""""""$"x$ % $ $ $ & & & $ % & $ "0"""#"#"#"""""""""""""""""""''$0""#""""###""""""#"""""""""#"""""""(""#(###"""""""$愀0#""܌$ $ń0""""""""""""""""""""""""""""$0)*++,-.--)), *--))))--)))*) )) *)),+,),))+/++,+))/01111111023441111451111011111111 11  1 1 1 ن0114111111111101111111111111 1 0 10111 1  1ↀ011 1 1 1т011          01111  01111110141 11101 1 1 1 1 1 1 111111441111551411 1 1 1101111111111111 퉀0  1   0   1       1111111111111111111 11111111 1 ޅ041兀011111څ011105141501  1 45 4   -66*6c...֋ G(Ga,٠L.0=X݋ؽ--.PMMU߀3Ρ~ƍǏ XXM  Hxdgjbehcfilx 15kyqy{{{z"zyzz{lkooopAmppomύzynAkvÂՂɃۃӄՅÆφɇчˉՉϊߊŋ׋ˌь׌݌ˍٍǎюߎɏۏŐϐِÑבǒӒѓݓǔהŕӕÖ͖ז͗ݗϘߘǙәÚϚۚśϛߛÜϜݜӝ͞ݞ͟àӠۡɢݢӣѤͥݥ٦ç٧Ǩ٨ǩשϪ۪ëѫŬѬɭݭŮ׮ůׯŰѰͱݱŲӲɳ۳Ǵ״ѵߵɶٶշɸոǹݹúӺ˻ۻϼͽ߽ž׾ɿٿnZZZ\Z[W{|Áwwxv"System.Collections.GenericSystem.Data.Common System.Threading System System.LinqSystem.Data.Metadata.EdmSystem.Data.Common.Utils System.XmlSystem.Data.MappingICollection`1 $List`1%DbProviderFactory2 InterlockedjIEnumerable`1kIEnumerator`1l$ EnumeratormIList`1nEqualityComparer`1o IEquatable`1pObjectEqualityComparer`1qIEqualityComparer`1r Enumerables Dictionary`2t EntityTypeuIDictionary`2vKeyValuePair`2wIReadOnlyDictionary`2xIReadOnlyCollection`1yRowTypez HashSet`1{ Action`5|EdmSchemaError~IReadOnlyList`1 Func`2 sEntry zSlotsValueCollection EnumeratorEntityContainer EntitySet Set`1EmptyEnumerable`1ISet`1SZArrayHelper#SZGenericArrayEnumerator`1z Enumerator XmlWriterStoreItemCollection XmlReaderEdmItemCollection$SynchronizedList$StorageMappingItemCollection GAH I @ J H K L MAAN A O 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 {sP Initialize |pQ GetHashCode }sHResize ~sRResize zQInternalGetHashCode zHIncreaseCapacity zR SetCapacity zP Initialize sSAdd sT get_Values U.ctorD V=System.Collections.Generic.IEnumerable.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 o5PAD$4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo`000004b0TCommentsSystem.Data.Entity.Design.dllLCompanyNameMicrosoft CorporationdFileDescriptionSystem.Data.Entity.Design.dll6 FileVersion4.8.3761.0\InternalNameSystem.Data.Entity.Design.dll/LegalCopyright Microsoft Corporation. All rights reserved.dOriginalFilenameSystem.Data.Entity.Design.dllTProductNameMicrosoft .NET Framework: ProductVersion4.8.3761.08Assembly Version4.0.0.0PADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDING 50>0> *H >0> 1 0 +0L +7>0<0 +70 0!0 +\e}{j͠00 3I:X0  *H 0w1 0 UUS10U Washington10URedmond10U Microsoft Corporation1!0UMicrosoft Time-Stamp PCA0 180823202027Z 191123202027Z01 0 UUS1 0 UWA10URedmond10U Microsoft Corporation1-0+U $Microsoft Ireland Operations Limited1&0$U Thales TSS ESN:A841-4BB4-CA931%0#UMicrosoft Time-Stamp service0"0  *H 0 V=o6k7׏MJS/$+ө -i9-=Vlpdߖt5%\VGJr}X Qko|a L\hhZ䈚v|K!HΠVN7:B@FD҇.GƬ]5zr5")QO[J 0v[Aj+& RܷRUg(aHkHr\̕J 3ĥd@8 00U)>cW^Ig2& d0U#0#4RFp @v+50TUM0K0IGEChttp://crl.microsoft.com/pki/crl/products/MicrosoftTimeStampPCA.crl0X+L0J0H+0%r:xcf._ۗUL>iI-c~åӿ9!0f6oޫh(i&Sxo106+0@YHFQ J-tUDz$} 3#_)m2Zj'ϰ z}"ZKӄcWkIx:T?%^ǡ "[/(Uzӏv*_0[0U% 0 +0UDw>Uq>s0PUI0GE0C1)0'U  Microsoft Operations Puerto Rico10U 229803+4379500U#0ҴX7.3L 0VUO0M0KIGEhttp://crl.microsoft.com/pki/crl/products/MicCodSigPCA_08-31-2010.crl0Z+N0L0J+0>http://www.microsoft.com/pki/certs/MicCodSigPCA_08-31-2010.crt0  *H 3š{^줦(]W%#% ipMi/ٛYhd4ckv{BtE3]FICqxӞەA14p,Cw/=aJcY}R`E?P~BXA8I0O)/;GY7!f/-mk u!2ZE?VQ̮}0H& (D-ԇIW M4# Í2 5(Ј?0p00 a3&10  *H 0_10 &,dcom10 &,d microsoft1-0+U$Microsoft Root Certificate Authority0 100831221932Z 200831222932Z0y1 0 UUS10U Washington10URedmond10U Microsoft Corporation1#0!UMicrosoft Code Signing PCA0"0  *H 0 rY\0d` BvSl>ok:t/2BN#r5W ʮ IhMKyKqG%ߝuϪsDׁ6\Eܯ=(hrsV5rv_wE8s[gRi/ t)v/T0Yҍb_F1P'@0r)("7N=2=͡8\NV(*2KOc-bE=F[&SzJF7<8w\V< _^0Z0U00UҴX7.3L 0 U0 +70# +71N&`;1o<-0 +7  SubCA0U#0`@V'%* SY0PUI0G0ECA?http://crl.microsoft.com/pki/crl/products/microsoftrootcert.crl0T+H0F0D+08http://www.microsoft.com/pki/certs/MicrosoftRootCert.crt0  *H Y9>&Fo@2j/nI_uL;-C -1#|P!]=/LVpyIr>A i˥ - PV-JҼp VชKWB4Qui +w:<К-Q ʏhp$2O'FɻWD|v}rvadLFζ:wwg!Z^G< =ͲPxф<"]Z@Njstz_Fg(w1K^Te? F,:h4e9&cݽ%(4y*_0;j#~0z0U%0 +7L+0UG?e8]w@0PUI0GE0C1)0'U  Microsoft Operations Puerto Rico10U 230012+4379650U#0HndPӂ77"mu0TUM0K0IGEChttp://www.microsoft.com/pkiops/crl/MicCodSigPCA2011_2011-07-08.crl0a+U0S0Q+0Ehttp://www.microsoft.com/pkiops/certs/MicCodSigPCA2011_2011-07-08.crt0 U00  *H  S ? &D џcK?\3le3[Խa1&'H5d"k-;,)75 $9nx )`'v4$ݹu;"P &I}EC4ρ\,ԓgs=2`0,.E(T\͖ہض0CHF]^v*XHLaA骸jB>x#x[mY}9y` =6E6n=;ԧ%vEZC1؄u}Q7'5qWqɘҞZdv}j51ruȈjEfΒu'[oIoX]i*SK{lOW`q Q4G=u"U?j9kZ?#x085Y$@:g_;I mP>!JA[nnT5fgr|R"r?0z0b a0  *H  01 0 UUS10U Washington10URedmond10U Microsoft Corporation1200U)Microsoft Root Certificate Authority 20110 110708205909Z 260708210909Z0~1 0 UUS10U Washington10URedmond10U Microsoft Corporation1(0&UMicrosoft Code Signing PCA 20110"0  *H 0 r.nM4X!B*kZP8I 7k 8™91BӉ yd~`$lIh^ߛS ,ï٩+z זY`fv2R&/PϳD].uhm:\F8dnd5xc-@ \yI) w=+ZMV(zr:I^C{{>]O/Y;-3Xŷ>2ӳ=8~ҝ,NV!5%9ndS#_R!t%_('(8%9J6|#faj(I_%]!K>RĵW?$z[/#p]QFwἬ_UK9#ID|Erzr$߿FWۃMI0[ݰf{KI)(}gbx_/W\w((m(,@7OD LԥC/tnx X,]`>O3ڰޞNFlֈ 00 +70UHndPӂ77"mu0 +7  SubCA0 U0U00U#0r-:1CN1#40ZUS0Q0OMKIhttp://crl.microsoft.com/pki/crl/products/MicRooCerAut2011_2011_03_22.crl0^+R0P0N+0Bhttp://www.microsoft.com/pki/certs/MicRooCerAut2011_2011_03_22.crt0U 00 +7.00?+3http://www.microsoft.com/pkiops/docs/primarycps.htm0@+042 Legal_policy_statement. 0  *H  g򆥘Ty.tg" cB}y e_.,>rm? ;Gic"5]e}FPU |K.)=Եw9dD=xz#}t&F*Š hh.*?*kXIc inZF+;н5n%'(M= 2-[I9 ƭQEX82q'',: iYhnot@*(>?Mf Mo}Ev@*e]Rbc6'ͥ]cA[>wuaaA(e/\֡FY KH)ű?Ew5Ңzz"HG#kKux7yKֳ#hu i;0Lumc=ѝVNOW"x2!zA ?̤]WqVNHEBɛv[ HkymmjRs zP1n0j00~1 0 UUS10U Washington10URedmond10U Microsoft Corporation1(0&UMicrosoft Code Signing PCA 20113^%0  `He0 *H  10 *H  1  +70 +7 10  +70/ *H  1" K^![*A\H4xBPMە͖0B +7 1402Microsofthttp://www.microsoft.com0  *H {[:]kB[<II;C3W6 Yf|N.E#-^q 0T6!F辺OH1GU e}I/F7 g`F47mlZC6r7+( =~^_oܠa{Ĩ2ޱԴنM~AB(Yw9޶nco8UR1q Vľ'u?xk'0 +710 *H 010  `He0Q *H  @<08 +Y 010  `He ZCѭA^my>ɚ oj\5n20190328090217.703Z0Ф01 0 UUS10U Washington10URedmond10U Microsoft Corporation1%0#U Microsoft America Operations1&0$U Thales TSS ESN:3BBD-E338-E9A11%0#UMicrosoft Time-Stamp Service<00٠3\s0  *H  0|1 0 UUS10U Washington10URedmond10U Microsoft Corporation1&0$UMicrosoft Time-Stamp PCA 20100 181024211425Z 200110211425Z01 0 UUS10U Washington10URedmond10U Microsoft Corporation1%0#U Microsoft America Operations1&0$U Thales TSS ESN:3BBD-E338-E9A11%0#UMicrosoft Time-Stamp Service0"0  *H 0 cNP\!T˨V2ih2RHoH\;Mi#Փ6,b%Nk_Am_tXt1 QEA VDŧb%QTHk^_iΔ'm`f+Ι+RŰew'LO[Q[)gxboT<׽K~D[1<0sApnhOFi.PM0bІzj`)c~X00U' !.܂R0U#0c:\1C{|F3hZmU0VUO0M0KIGEhttp://crl.microsoft.com/pki/crl/products/MicTimStaPCA_2010-07-01.crl0Z+N0L0J+0>http://www.microsoft.com/pki/certs/MicTimStaPCA_2010-07-01.crt0 U00U% 0 +0  *H  p.:kv]3f+[S'1A |a0Y0D`TC M8Bݓs0W&E GͿ$`2X`FXG2tag_TϓLĦ]an(aF'$gr!KdPb]w=WuBM@Q>gfD~Knʱz* 1N5xhttp://www.microsoft.com/pki/certs/MicRooCerAut_2010-06-23.crt0U 00 +7.00=+1http://www.microsoft.com/PKI/docs/CPS/default.htm0@+042 Legal_Policy_Statement. 0  *H  Q ?q=!o1Wm0fjxǨ%kTW+QDS`v@@A\\^5$VKtBȯ7}Z?yJR8/ye٩kzoK0D$"<Y)p2J'U/3b_W@ΙfjbJ &9Jqc{!mÜ<}jxm8ؔƥ B"8 %d~cY%z.9Wvqa˚Gͧ};q ]t"aڰPo1:eGxHr~akow˧ 9؂r*T9[ Uzs;-3.)/T'!ȬN(ۖBAM*f0ӻt2Kc{/!YD!J^Q nW&P)oΑ-RB=j]j^Q Z03IfI<1 0 00|1 0 UUS10U Washington10URedmond10U Microsoft Corporation1&0$UMicrosoft Time-Stamp PCA 20103\s0  `HeJ0 *H  1  *H  0/ *H  1" 1.#pD(߹[l:\0 *H  /1000 :/-ȂmmJ6zk9xK%200~0|1 0 UUS10U Washington10URedmond10U Microsoft Corporation1&0$UMicrosoft Time-Stamp PCA 20103\s0" ȯSUA]/fVs-12kcY# 0  *H  gT˥g_n2)6{A-?#{Kbr8izԎ'F?Q^7n r)[\=qc^{2c(,o/J ZzdRf4}izL%.t)z hUgt6'|O;IHPEmFCdVƿK9nг} G(W2z =`$v!Z=