MZ@ !L!This program cannot be run in DOS mode. $PELBR"  PB% @` `$O@LMX> h$  H.textP  `.rsrcLM@N@@.reloc V@B!%H, ~ h#rp(rp(+&{o& *6{o' *2{o( *6{o) *:{o* *6{o+ *:{o, *2{o- *2{o. *Js/ }(0 *{*0){  (1 t |(+ 3*0){  (3 t |(+ 3*0){  (1 t |(+ 3*0){  (3 t |(+ 3*Js }(0 *s }(0 r-p(}*{*Jr)p(}*{*r5-p(+&rU-p(+& (*0r5-p(+&rc-p(+&rU-p(+&s5 s6 s7 o8  o9 +co: -r-p ((zs6 o8 )(,o; s< o= + X o - ,o (%s(!&*(m)Hp *B>( *0\r-p(r-p(+&r.p(s5 s> r5.p(?    (#o=  o@ ,(rA.psA zs7 o8 o  +j o -r-p((zr5.p(? o8 %(, (#o= +X o -  , o (%s  (!  , o   ("o=  &* *A.>%w . '<(,TB0sB sC oD oE (F (G oH , ((%oI  oJ oK sL oM (~(N , ((zs  o*!6 Jo; sO *Jo; sO *Jo; sO *09oP +(Q oR ,sz(S -o *#*Z{, {o *Z{, {o*sT } sT } sU }(V *sT } sT } sU }(V } } } *{ *{ *{ *"} *{ *{ *{*sW }sX }sU }(V *sW }sX }sU }(V }}*{*{*"}*{*{*{*(Z * *0([ (\ s] (-rs.ps^ z -r.ps^ z-r1/ps^ z([ ~Q~_ o` r5.p(a (r/p(a (r/p(a ((< (<(< ,o * 0ob ( ,o *  (Z * *0  oc od oe r/p(f , s +s  ([ (\ (g (h si (j ok (@ o ol - om  on so op , o ,o ,^ol 1Uo ++o oq or os s^ o - ,o z([ (*(L> AU 8 st (u ,~*st (u ,~*~*(Z * *:([ (*(Z * *:([ (*r/p}(0 }}}}*0 snsx (I*0T oy sG oKod~oXo+o{  + o| oe o -  , o o +o}  + o~ o (f ,oL o -  , o o >(h si s o o o ( oy sGo  + ( oL ( -  o o (Jo o *(?[ t*  (0N o on +r/p~_ o` r/po -+r/p~_ o` r/po -*V( ( ,(z*0z (Xo 0 .$.:+R. .!$.6+At0(W*t)(P*t"(M*t((O*t*(Q*o (z0 {o -r'p+r/po {r[po o  o ,so o o o  ,o to ( -( ,4o (j ,r/p r/p( {r/p o  {:{r0po (`o {r0po (`o {r)0po (`o {rI0po (`o {rc0po (`o +,o ,$o ,{rI0p(`o o ,{r0po o o ,{r0po o o ,{r0po o o o +( (N( -"o o 9:o o o o 3jo o o to o t*{r/po {r0po (L{o {o  {o *0|{r_%po {r[po o {r0po o (jo {-!{r1po Y(`o {o *0{r 1po {r[po o o ,{r%1po (jo o +o +( (Z( -$o {o *Vr0{r71po {r[po o o o +( (T( -&o o o +( (R( -(o {o *2Nh0R{rO1po o o +( (Z( -*o {o *80J{r_1po r1po o (Sr1po o (S{o *0v{o {r1po o  +;{r1po {r[po o o {o X o 2{o *0 {r1po {r1po o o o to (j {r0po {r1po (Vo o ,r1po (U{o *{o {r 2p.on o {o *0. E+r2p*r2p*r2p*~_ *0z{r)2po {r[po o o ,{r%1po (jo o ,{r?2prQ2po o o 9o o o 3m{r[2po  +@{r1po {r[po o o o {o X o o 2{o o +o +( (Z( -*o o o +( o 3(Y( -/o {o * ;%`0k{o ,Zs ()o &oP +(Q on o &(S -o {on o *)"K0{rc2po {r[po o {r2po o o {r2po o o {r2po o o {o *0{r'po {r[po o {r0po (bo o ([{,Ho r2po ,6{r`3p(\r3po r2po o (`o {o *04(a (_ o o 8(  (^, o +Co +"o o o (f , + o - ,o  (]:{,^o 3TtQo  . o -8o r3p(f ,&( ,{o (\r4po +#{o (\o (`o ( :2o *A4F/u %Vr4p(f ,r4p**-*o ,*o -*o -o o o ,**0v{,Io r24p(f -5o rZ4p(f -#o r`3p(f -o rz4p(f **o r`3p(f -o rz4p(f **0*( r4p$( o t3*o ( ( ,on (h o *on *r{, o (c*o *0!(a o 3o *(j*o . *o ,o {( -*0{{-+(| {r0po {r4po {r4pr4po {,,{~(N ,{r4pr3pr"5po {-2( -{r.5po ( -{r@5po   +0 5q5 {rl5p( ( o X i2*0@{rx5po {r[po o {,Ho r5po ,6{r/6p(\r3po r5po o (`o o o +@( o .  3t9(h+t7(f+ o (z( -7o o ~-ks ~( +o +o (Mo - ,o {o *M ( 0{rU6po {r[po o {r71po (jo o o +( (g( -<o {o *Nj0M{r1po {r1po o {rs6po o o {o *0{rs6po {r[po o {r)2po  (jo (io r6po  ,6o ,.{r6po {o  o  {o +ro r0po  ,$o ,{o  o on o o r6po  ,$o ,{o  o on o {o *0uo ~-ls ~( +o +0 o o  (,{o on o o - , o *. o TTJ.#(o> o -o> o T*0R)o o o? o o@ o> o 3  +  , o o@ *o o@ *0%*s }o sA (+*F(,(**0?+o o +( o, - ( -*o ** !-02,sC ((oD {)o  o1 o0 *0<o o +( o oE ( -*o * !-0Qo o o to {)o  3(o o o to {)o  **{*o< o o o? Q{*o< o o o? Q*F(0 (*(0 rAp(+&r8Ap(+&(*0{-(0 rjAp(+&rAp(+&r8Ap(+&o+(+ i. rjAp(zo+~7-s 7~7( +(*{.*{2*2{3o*6s}3*{6*"}6*J~}4(*frAp(}4(*0:.rAp((s o (H ( ,o *& / jr7p(+&((*0:.rAp((s o (H ( ,o *& / jr7p(+&((*0/rAp(+&(-o rAp(z,"rAp(( ( ,(z,Cr8Ap(( ( ,(zo (f ,o (z},-+(+}-}0}1s}3(*0^0{.,}.}/}2s sI }Y(,1{4~(u ,(* o{ZsJ ({1sK {,o o 8( o . .=+Y(- t7o (- t7oL +; o+* t9{^soM + o (z( :r7o oN +(O ((P -Wo sQ (oR +BoS  {^ ooT & o(  oU  ooV o - ,o oW +'oX   (- (  oU o - ,o {_{'{^oY oZ {_{'o +(    (oU (! -Go {4~(N ,?r5p ([ (\ s] s^ o_ o` }5({Z(:-{_{ oa ob +(c od {Yoe (f -_o {_{#og oh +(i od {Yoe (j -ao {_{'o +1(  oo od {Yoo oe (! -Go od {Yoe }.{_}/{Y}2*(,( so+{Z**A.DcO 4" [)*<a*>#**0f1{5,?rBpr3p(k {2{0{45 55(H*{2{0{45(H*0&2{/{,{.{4sp oo*0 .3{-,{-i,{4~(u ,*{-~8-s 8~8( + o  8 o s  }(' 9o {\(  s}o  sl (+(+o ~9-sn 9~9(+~:-sn :~:(+(+(+,oq (+ o8 (od {Yoe or od (s  {1  }t  {0}u  '  r/psv  }w  }x  }y  sz }{  sz }|  s}   od  o~ {_{( (+o  o :<  , o *AV! 0*4o ( o o o sv *05s s r*Bp(a {[( oo o +(  (o ( -*o {0s o +( o ( -fo *9(a026s s {^oY o  +& ( o- o + ooM  ( - io oY o  8 ( ooN  +s (O o o@ o o o@ o o ,8o ,.{^o {^o o o  (P - Wo  ( :Q io *(3Ql"0J7o o +( {^o o , ( -<o ** ,80Q8o o +)( {^o o , ooL ( -<o * 6B09{,o o +r( o 3at7(w o o +-( {]o -{]t7o o ( -*o ( -7o *=:w03:{1, {0,* {,o o +( o o + ( -7o ( ,r:Bp {0-FrRBpo 1o r`Bp(a (}0+r`Bp(a (}0{1-x.o 1 o rlBp(a (}1+rlBp(a (}1{1rRBpo 1o rlBp(a (}1*%#H>{.-(z*0K;o  ( {3o o{\( s {_{"o *0<{_{ o ,*s s s {3o o{[( oo1 o  +b ( o o o -(-{]o -% (  o ,  o o  ( - *o {0s  {_{  o  *^o0C=o ( o o s o ({_{!o *0[>o r`3po ,Hs^ r2p ([ (\ o r`3po o s] o_ o` }5*0?oo {[( {0s oo {\( s s+soo> (  o {_{"o o    s   o {_{& o Xoo+ ?{( o *0@{_{#o o -%o ( {_{#o o o {\( s o o +.(  ({_{& o o ( -<o {_{%o *g;0@A{_{$o> o {_{"o o o &s *0Bs o {[(  {4~( ,(-(+ {0s  (o o +8( t:({_{$o o ( -&o (, o  ( *gE0Co o - l*o o?  (,+o ~<-sA <~<(+ +)o ~=-sA =~=(+ o o -#o o 3,o o s *l *0Do o -*o o? o o/ o t0 (- (-*o o0 - -{_{$o t:o {_{$o t:o +I {_{!o o/ o( {_{!o o/ o( X2 s *0;Eo o -*o o? o o/ o t0 (*bo o o/ o *07Fo o t: o o t: ((*0xGo o to t0 s ({3o o( o s o t)o o o  o *0Ho oo o +( o o( -$o *!90>o ( ,( o (f ,( o (*0THo o to t0 {_{ o o ( o s o *0 ( o *&C(*0Is .o + (o Xi2rs#p  + o rK"p( X o Y2o Yo (a *&C(*0PJo  +( -_X i2s ( -o ( - ( *ro -o , o **o ,1o -)o ~;-s ;~;(+**o *o **o **o, **o, *(0 - r|Bp(z}D}E}F}G}H*2(*{D*{E*{F*{G*{H*b(0 r-p(}O*"(*{O*Jr)p(}O*0VK s }rDp(+&{rDp( - s ( ,o *-J 0*LrDp(+&( ((+( +*0RMs }rDp(+&{rDp(+&rAp((s (*0(LrDp(+&( ((+( +*0NrAp((rDp(+&(o!+o +{o o o o +F(  o , o ,+to + oq (  7s< o ( -ro o :y ,o (*QS5 0LOo ( (u ,(0(zo oM ( (u ,(0(z*0)P(,Q*o QP(*01Q~S-s S~S("+ (#+( +*(Po - Pol 1**04RQ{O E +s Q+s Q(**o Q*0ESs5 o oM (QP~( ,~P(X s< o= *0{To o &s ~`s o o &o!+o 8o (," oq (  's< o 8 o o  o o oM ( s ~boM ( on ( o (a ~`rK"p( s  ~as   s   o  o &o  o &( (  `o s oM (( ~ds s s ~es s s ~fs s s ~gs s s ~hs o s s  o o & o o & o o & o o & o o & o  o & (o  o &o : ,o o o 1(om *A9R 0JUo o o +( o o , ( -7o **'80KVs/ o +!( ( (( o& (  -uo * .;0)Ws  r!#po  o  o  o *0Xs ~io %(   и(  и(  o s o з( s r Eps o o &o ~js o &o (-s o &o ~ks o & 0o o o & o o o s o  8 (  s s s o o &( (( (o o &o s  ns! s"  o#  o &X  (  :[ uo o ( s ns$ s% o &*0dYs rEp(h (& (a o  Po %( и( и( o s o o ~js o &o (/s o &o ~ks o &o' ~P1do o' ((o +o o o( &o - ,o (r(Epns) +s o* ns s$ o s" o &*" 0KZW( r:Eps+ W( n s s, o- o &*0[s }*0\s }*.r:Eps *0]rPEpn s s) *00^o' ~P1(($+(* (*o. o ~lo (/ *0X_s0  `o o ~js o &o (.s o &o ~ks o &*0i`s1  o2 o3 ~co4 o ~js o &o (,s o &o ~ks o &*:o5 ~R*r PPQ (R*0 ~X(; ,#@o< *~W(; ,#@o< *~V(; ,#?o< *((; ,#?o< *o= (h (> o< *0 a s? *0ObrAp(( P~T-s T~T(%+-oM (P(&*&s@ *NrAp((*.sA *0cr^Ep(&+&rzEp(+&rEp(+&rAp(oM (( , r^Ep(z( P~U-s U~U(%+-o (P(&*(B -(0 s< o ***oR **oR *2{VoC *2{VoD *{X*{W*N{V{W(5*0 Bds/ ~Z~d-sE d~d ~Y(*0 Bds/ ~\~h-sE h~h ~[(*0 Bds/ ~^~l-sE l~l ~](*0 JesN ~a~p-sE p~p ~_~`(*2{VoF *(0 }X|W(}V*0f~~b- sG b~b('+~c- sH c~c((+oJ +# oK QP( 2 (- o - , o ~QP(**Xg O/~ {V*0wg{VsL (  oM oN oO  +oP &oQ oR &oS -(T oU ,o ,o *"?a Rk 0hoV oW oX oY -%( -(Z ( o[ +o[ *s 8 s s o\  +4 (] o_, o-  ( + (  (^ - }o o_ ,Lo_ ,$(Z o` &r$Fpo` &(Z o` &r,Fpo` & oa &r/po` &o_ ,Mo_ ,$(Z o` &r$Fpo` &(Z o` &r0Fpo` &oa &r/po` &Xi?s o_ ,0(Z o` &rwp(f - +T*T*T*T*0k(p -**v~(N ,s*s*0 N^}v{vo4~ysL  ~x( }u{uoM }t*0El{toS ,-{w-o }w{t{woP &+}w*fo!o"o#s{*(0 *VrJwpxrPwpy*{z*(0 *{{*{|*{}*{~*{*{*{*{*{*{*{*{*2(Q or *sN*su*.( *b(s rp(t (P*>(u (Q*0rߖpи( sv }{(N {{ow rpи( sv }|(N {|ow rpи( sv }}(N {}ow rpи( sv }~(N {~ow r'pи( sv }(N {ow r;pи( sv }(N {ow rMpи( sv }(N {ow r]pи( sv }(N {ow rEpз( sv }(N {ow rEpи( sv }(N {ow rFpи( sv }(N {ow rop( sv }(N {ow *0 (N rߖpox }{(N rpox }|(N rpox }}(N rpox }~(N r'pox }(N r;pox }(N rMpox }(N r]pox }(N rEpox }(N rEpox }(N rFpox }(N ropox }*{*0>m{o>(y t # {o>oz {o{ (z*#N{o>(| *0>m{o?(y t # {o?oz {o{ (z*#N{o?(| *0>m{o@(y t # {o@oz {o{ (z*#N{o@(| *0>m{oA(y t # {oAoz {o{ (z*#N{oA(| *0>m{oB(y t # {oBoz {o{ (z*#N{oB(| *0>m{oC(y t # {oCoz {o{ (z*#N{oC(| *0>m{oD(y t # {oDoz {o{ (z*#N{oD(| *0>m{oE(y t # {oEoz {o{ (z*#N{oE(| *0>n{oF(y  # {oFoz {o{ (z*#b{oF(| *0>m{oG(y t # {oGoz {o{ (z*#N{oG(| *0>m{oH(y t # {oHoz {o{ (z*#N{oH(| *0>o{oI(y  # {oIoz {o{ (z*#b{oI(| *J{o>(} *J{o?(} *J{o@(} *J{oA(} *J{oB(} *J{oC(} *J{oD(} *J{oE(} *J{oF(} *J{oG(} *f( ( t}*0gprop(  YE +({ +(y +(x + rp(z=( o o *(*0$qs (z( (}o { *0$qs (z( (~o { *0Co 3o 3 #?*#?*o 3 #@*#@*0$qs (z( (o { *0)r YE +(*(}*(~*~(; ,r=p*~(; ,r*?p*r@p*~(; ,r>=p*~(; ,r>p*rD@p*~(; ,r<p*~(; ,rh>p*r?p*2~(.+*0No -o .o , o 3o -o rp(f , o (*Q*0N % ,Dr<p(f -r >p(f -r?p(f -+~Q*~Q*~Q*Q*0Xs~V~W~X~~ ~~~*0O~_ }(0 rp(r$p(+&rAp(}}s}*{*{*{*"}*0ts ~(*frp(/+&~(*rp(/+&rAp((*0:.rAp((s o (H ( ,o *& / 0 i1r7p(+&(r prp(k ({{{{{{5 55(I*6~(*0qurp(+&r$p(+&rAp((  ((z( o - ((z o  ( s *# ,0v{,}}}}}sk {o{o {o( (  o } {o &} {o {s }(({rK"p~_ o` rp(a sK oqo  +9 o {oe ({o oU  o -  , o ({o +*( {oe (  oU ( -o od {oe ({~(N ,{o~(N ,(({o +(  { oe ( -o ol(-1}{}{}{s }>  (,/ (  s s ox+ {ools *A|F, L7#21c>2q 0w   ~(N ,~ ~ ~ +~ ~ ~ s o o o o o ( s    o   o  s@   ( o ( a( o ( s    o   o  s?  (o o o o ~ ( s  o    sA  (o (9&(, ((z,o ,o ,o *AL=C=C=`0"xo0+ o o o o &*ol ,(-((( (z*>{-(z*05yo +o oR 3 o - ,o ** ' 0ozo s o o +2( t: oo o  os&s  o ( -&o od *?Y0|{os (  (o ( ,( o s rpr0p((( s^ o_ o` od *0| 3rp*rp*0~}{{o Ws +6o8 (},(-(o o3o o7-o , ( ,o *as 0~o o;   s5 o$,ho$(,r/psv 8 -o#o$(+o#o$( us< o= 8o)9{~(u ,*ou,4{o -%or od r/p(s sv +f ,D{o ,3 oH {o &{o ,{o & W( s< o=   s s   8 o o2 o--o,(  ,yo0-= r™po/-o. o#o*( |s< o= o*p( o sv  o +d r™po--o, -o#o* (+o#o* ( us< o=  X  o / o+9o#f({o,'+'{o"} o#( -+o#} o%sz } o&sz } o(sz } o'sz }{ }w  o }x s} od  oy,{o *{o &*0ov,( ( **0~_ s {{oo +<o t og ( ,( -(o o o - ,o ( -(*$Im 0o (-*~-s ~(-,oe( s< ox*s {~(; , (+ (-+oi, (-)~-s ~(, ( {oeo  {s   o   o s5     ( (:" (,  s< o=   9{~-s ~(1+o 8o  o ~-s ~(2+o +Uo o o o ,7o ,,  o o (  s< o=  + o - ,o  , o :I ,o  ,{ o +*{ o &{o &{ o & od   oy*bM k 0voR o>oy o?oy o@oy ({oBoy oCoy oDoy ({or or_ *0[o o o .*o + ( o o o - ( -o **-I0To +.( o1 oao , o, ,  ( -o **;B0To +.( o1 oao , o, -  ( -o **;B05o o o s o {o *05o - o - {o {o 8o1 o oYo -Co o o rK"po oY( ( ws< o= * o1 o oao -Co o o rK"po oa( ( ws< o= *Xo ?s o *0o o? o o/ o t0   o o +)( o o _ o o ` ( -*o -6 ,3o (o (o o ( Q*rs#pQ*56k{{os (*{{os (*{{os (*0Ws s o +_o tR oj(},#o ,o o o   o o^,  oLo o - ,o o , o *l 0! s}o oj -s5  {o -fo s om|(,!W( rs< o=  +W( }s< o=  ({-+ { (3+($+{9i: -sA   (4+o 8s  } o }{ {o o (-ps5 - s (5+(6+oioLoP( s< o= (^o :E ,o i>{,0i{o /{(+(7+} + } +] 3' o oi( s< o= +% o oi( s< o= Xi2{o oJo  {{s   od E +$ op+' op{ o &+{ o & oy* 0ao oj -s5 ( s od  ot o o0 - { o & oy*0s s Qo 8{o  ob-oPov-yob-7 -oPoioL(+oPoioL(+oLoi( us< o= PoLo 8o ~-s ~~-s ~(8+r̙pr̙po o oN( o o @Srחpo 9od: o o :oVo o ( / ( +--oVo o ( 1 ( +,x(ojrחpoVo o o o oLW( vs< o= PoLo 8]o o oVҌ#( o rpo 9of:o o :oXo o ( / ( +--oXo o ( 1 ( +,x(oj rpoXo o o o oL W( vs< o= PoLo 86o o oXҌ#( o 8o .o  . o @,rחp o 9Toe:I o o :8oT o o ( / ( +--oT o o ( 1 ( +,x(oj rחpoT o o  o o oL W( vs< o= PoLo 8 o  o oTҌ#( o 8;o  . o :&r3p o 9oc: o o :oR o o ( / ( +--oR o o   ( 1  ( +,x(oj r3poR o o  o o oL W( vs< o= PoLo 8 o  o oR( o og-,oZ,$~ %( o o +2oh-*o\,"~ %( o o oLo ( s o o :y ,o *A 0t +Jo oN-8o oPov, {(,o oLo X o 2o 1Q+QP*0{o >( -*{o  +w(  {o  os s^ (,rpr0p(( o_ rpr[p(( o_ o` ((  -o *+0s s (oo (,*oo {o s  ( oo ,o jo & (g s o o{s o ,o , o *(Pa + Hp 0( o ( o  o o s o  o o +,( t- o o ( s o ( -$o ( ( s {oo ( o o  o! o" *:9soY*oa*o ~-s ~(2+*o *o *o *o# *{*"}*rޙp(9+&oG rp(f ,s*oH (2sI z(0 *{*"}*:(0 (*^(-*(o*^(-*(o*(,#o . (o*(o**s }(0 r-p(}*{*Jr)p(}*{*0KrAp(r-p(J r-p(+&r.p(J rAp(s(*0LL( ~-s ~("+(:+,*((+( +*r-p(J r.p(J rAp(s(*0KL( ~-s ~("+(:+,*((+( +*0{r5-p(+&rU-p(+&rAp((-s5 (o= *sL r5.poM  ( s( ,o *G'n 0KL( ~-s ~("+(:+,*((+( +*0r5-p(+&rc-p(+&rU-p(+&rAp((-s5 (o= *sL r5.poM  (s o9 +5o: (N r5.p(a (o oO o - ,o  s( ,o *vB T 0LL( ~-s ~("+(:+,*((+( +*0o(P -"s5 (V sQ o= *(R (-s5 (o= ( ,o *11b 0'(S ,3 (Q*(,**0=Q(R ( &,o s5  ($o=  *  80_Ss5 (- (o= *P~(u ,~QP~( ,~P(X s< o= *0s5 ~(; ,(W s< o=  r(- _(w(; ,( A{( oo{o oo oo ,Hs }o(;+ sU (<+oH ooV , ݷooW ,o ݒ ($o= | ($o= f ($o= P ($o= :   ($o= $  (,  (#o= +* *A  9 &8 <: R; h ~$F(U s< *0{s o  o, (X (N (Y -(=++o  o,6 ~-s ~(%+-o([ oW ,,(P ,(\ *q0(] o^ ,o *  0o_  o` -+ oa (b ,oc 3=od 34 +0(h rpo_ oa (  , oe oc od sQ * s< *09~( ,!s rprtp( (>+&~(g *09~( ,!s rpr6p( (>+&~(g *09~( ,!s rprp( (>+&~(g *09~( ,!s r@prp( (>+&~(g *0 (h o s] oi ,o ,o sj rpok ol om on B( o oo ( o oo ?( o oo #( o oo @( o oo A( o oo B( o oo op  oq or oV ,=or (;+~_ ~-ss ~(?+(zou ov *  * *oR **oR **oR **oR **oR *~_ (f -(Z on ( *on **.rp(*.rIp(*0rp (*0rp (*0rp (*0r'p (*0r{p (*0rp (*0r p (*0r3p (*0rqp (*0#rp (*0rp (*0r9p (*0#rp (*0rp (*0rp (*0rUp (*0rp (*0rp (*0-rp (*0rp (*.rSp(*0rp (*0rp (*0r-p (*0rp (*0rp (*0rp (*.rIp(*0rsp (*0rp (*0rp (*0r7p (*0#rp (*0rp (*0r p (*0rA p (*0ro p (*0r p (*.r p(*0r7 p (*0rw p (*0r p (*0r p (*0r9 p (*0r p (*0r p (*0r p (*0rW p (*0r p (*0r p (*.r p(*0rQ p (*0r p (*0r p (*.r p(*0r+p (*0rOp (*0rp (*0rp (*0rp (*0rp (*0rcp (*0#rp (*0rp (*.rCp(*.rp(*0rp (*.r?p(*.rYp(*.rp(*0rp (*0rp (*0r%p (*0rcp (*0rp (*0rp (*0rGp (*0rp (*0rp (*0r+p (*0ryp (*0rp (*.rp(*0r=p (*.rp(*.rp(*.rp(*0rUp (*0rp (*0rp (*.rp(*.rUp(*.rp(*.rp(*.rp(*.rAp(*.rqp(*.rp(*.rp(*.r+p(*.rqp(*.rp(*.rp(*.r%p(*.r]p(*.rp(*.rp(*.r%p(*.r[p(*0rp (*.rp(*0rp (*0rp (*0rqp (*s *s *s *s: *:(0 (e*6(hs *6(hs *0s s *^~- s ~*{*"}*2{o*2{o*b~- s ~**>(_}*{*0, P (n (x, (o (x, *2rp(u*2rp(u*2r3p(u*2rp(u*2rMp(u*0"  . 0.  `3****0/ o rMp(o  ,o on (y *0/ ` o (o  ,o on (v *0F % ,;rcp(f -rup(f -rp(f -+ * P* 0* `*04  . 0. P.+rcp*rup*rp*rp*>(s(s*zrcp(f - rp(f ,**&(j*N(doo*J(d(o*0B,7o 1.o o o  (d( oo|* 0],Yo +( o3 s o &( -o  (d( o* '1>A0;,7o 1.o o o  (d( o* 2(ku*%o _o2 %o ((t`o2 *&({*0(o o (o o (doo (grp( (o (o o o ((o o ((oo &s *(do o to os *0%/on (frpo(b *2(u)*{*:(0 }*0r p((r9p(  rp(o o &rp( o o &ood(*0zoo +Ro~ o-  o +o rps ( o o &o - ,o *_m **0ou (*0L(  r?po r[po (o o &*0rep( o o o o o ( o o &(,9o 1/o o o  o ( o*`t0]{-Brp r p( o o o on (}o {o &*0oXo o (-oXo o (9re p(( ol, r p  (oXo, -#r p(o o &8r p(( o o &r !p( (G( os ry!ps (o o &oXo o (:r!p( r p(o o &r!p( r p(o o &(,Ao 18o o o % odoXo ( o(*%0r"p((r9p(  rp(o o &rp( o o &ood(*F~rK"p( *0(os (*08  ++ un -s o s o & X i2*0@ +5un - s o Yon s o &X i2*0SI( o ( J( o ( o o &o o &*05K( o  ( o o &*0 rO"p( o o &*.r"p*0G}s}(0 }}}}{s}*0    (  E +s +s o _}{os0(1(,ݚ(o , ((-or"ps +c(X s o r"p( Mon r#p( (Y oO s s r"ps s  r!#po  o  o  (o ,?om jo &s] (o((~_ ( oZ (H   (6   ($   (   (7,o ,o ,o o ,o , o *A it9 i8 i: i; i 7 0O{,*{oq o@+&0&o on oq ( oq (* 00{,*o o ( s o +a( oq o ,>oq oq o ,*oq ( o o oq (+ oq o &( -$o *'n0{,*( s o o +V( (,Ft9 oq o ,$ oq (s o (+ oq o &( -7o * c0*s }{o +s (A+*0?s }o s (B+(C+ ,o 1(D+**0%( ,o To T*% TT*0f% TT( uU ,6o o ,(o o o To o o T*,o To T*2{o*{*j{- s }{*R{s< o= *j{o; s o= *Z{s o= *08{({o; {o sO o= *02{({{o sQ o= *04{({{o sQ o= *0?{oP +(Q oR , (S -o ** !-0s }*0& o (o ( (o*0' o (o ( (o*^( ,*rK"p( *0} o 31o o -(o o*(o o*o ((f , o +o (o ( (o*2{o *6((*0 {oo,**j{- s}{*{*{*2(,**6{o&*6{o'*0(  ,o (-o ( 8o .3&t-o ( +mt(o ( +Zo r%#po ( ,o r[po  ( , oy ,on ( +(  ((*Zu{,t{*o *( -o %( ,*((*0#  + s o &X i2*04( r7#p o ( s o &*0( ,  rs#p *ru#prs#po`   o 2X(,X  +  o Y1(,Y  + o' Y ,YXo ,(( i3  o *  8 (:~o o - rs#p8-o ry#po o 8o ry#po o (f -|o -po ,+^o' o' (  +5 o  o . - rs#p+ o +  X  2( -X i?o'   +5  o'  2    o9   o  X  i2 *-*o ( -r#po ((*6r#p(*0Y(h r#p ( s o &((h r#p ( s o &*0<( , rs#p*ru#prs#po`   o *Jr#ps *0olo (s2 (do(o s1 o o2 (o ,%o `o2 ((o o8(~o4((o o6((o (o _-oo(o o7(s o & *(o -*(d(o o*B}({*j(doo(|*0O(o +o +"( (d{sQ oD( -*o */@0o o0 s o +( ( ,o ( -*o o /*s (doo(f(o o(do~-s% ~s(o o `o r$p(o (a o (o (do(K,3(do (o (( (o oo (o (!o (ns$ s o o &s  o 8(  (d (sQ  oW  ovo   s o s o o & ov("o ( oXo o (,Cs o  ovs o (f(Vr%$po s) +o   ovs s o &( :o o  s" o &o o &*A4'B 2(u}*{*0Mo, ,*(m,*(n `. (o `3(o .(o P3**,o -}o3 o &*, o3 o &*(*&(*j(doo(*0( - (fo *2(o *2(u(*Rr_$p}({*0+ol(o s1 o (fo (s2 (doo4,"o4o -o3 o4o &+o3 (foo &(o o6((o ((o o8(~(((o o  +H ( (,8 t9(o o &(o o & ( - 7o (o o +3( (,!t9( o  o &( -7o (o o ++(   (, ( o  o &( -ro (o o7(s   o & *(U:Z@80( o ,**06 o ,*o o o ( ,to o *z(}(d(o(*0(o o +r( (,bt9 o  (r(q(-B(do  o o  (r(wo (q(w(' o( -7o * 3 `.  0***0s0  `o o r$p(o (a s o &o (o s o &(o (o ($o (o (o( &o o &s0  `o (for$ps o o &o o s o &o (o s o &(o (#o (o (o( &o o &s0 `o (fr$por$ps  o o & o o s o & o (o s o &(o (# o ( o (o( &o o &*0rs {o b( s o  `o o o &(do(o rK"p{(  so *0^s (doo Po o (o (do  o (fr$poo *0 /s (doo(q`o o o o o r$p r$p r%po r%p( (do  o(foo o (o s)(doo,,o,o o -o (o ( (zo0,Eo 1;o o o '(d(o ( oo.  ,E o 1;o  o o ' (d(o (  oo (cs (`  (cs s    s n   s  s! s  s o &o (cs s" o &o (*'Th'0s (dooo  (r`o r%po (a o s (do  oo o  o (o o o &b( s o o s r+%pn o s o s s) o( &o (*0s (dooo o (p`o (do~-s% ~s ( ( ,to o (do (f oo o (s o s o o o  + ( ( ( - "o o o  +B ( o -(o +o&s o  ( - "o s r?%p    s  o  o s! s" o &*  O[0Ko&( o r_%p(a o o (fd( os o &s s  (fd( ono s (fos s$ s  (fd( on  o s   s$ s o ,rs%ps +(hs o       s o & *0N( o -(fo+ (fo o o s o o &*0-o , d( *o o tQ o *^s {ns) *2(u6*(*&(*0V((oE+o +"( (d(sG oD( -/o */G0( (o o >o @o o r%ps o &(o o +"( o o s o &( -$o o r%ps o &*Z/j(doo(*0( - (fo *2(o1 *2(u0*0(0 (( 3iY(*iY(iY  YE    *(*(*03 -~( +3 ~( , o*{*"}*{*"}*{*"}*{*"}*Rr%pr%p(*r%pr&p((Z r?&p( *0(o 2o' o o *Fr_&prq&p(*Fr&pr&p(*Fr&pr&p(*Fr&pr&p(*Fr&pr&p(*Fr&prup(*Fr&pr&p(*Fr&pr&p(*Fr&pr'p(*Fr&prp(*Fr&pr'p(*Fr&prp(*Fr&pr'p(*Fr&prp(*Fr&pr&p(*Fr&prup(*Fr&pr'p(*Fr&prp(*0Ar#'p(2*r1'p( /*r%p( 2 r='po *0-(2*( /*rM'p(a o *0<o /*o' X , Y( ,o' . ( ,**0^ 2 sssss sss s  s s 2 ssss sss s  s  s*( *0R E+**0(-( +P(  (.oo ,(.oo +s (.oo o ( -o (, E +(*(*(*]k0 +o o % -*0d  -+8;o rQ'p(f , X 8rU'p(f ,%Y X<X< 8( :rY'po :(!,,@  ( 9 (" 89X3@ (#  E+j  ($ +]  (%  (&+EX3>r&p(f ,,o +r&p(f ,, o o o % :*01(-s   89o' 9o ';('E 2=aiz8X @ ( 9 (" +vY -o +k, (& (%+O+G+?,; ($ +.,(,o +,(,o o o % :*6(.o *0fr_'po /Q*r_'po' X ~o / o9 Q+ Yo QPro'po , Po9 Q*0N(.o o + o o3(,o  o - , o **,@ 0Qo [3*(o )o =o 3,2(1$o o  o Xo9 Q*~o 2*  o Xo9 Q *0f(.o o +8 o o(f ,#o. o 3(,o  o - , o **DX 0l(.o o +> o o(f ,)o.o.o. o 3  o - , o **J^ 0l(.o o +> o o(f ,)o.o.o. o 3  o - , o **J^ 0Q ~o  2*(( o  0rs'p(+9x o  8jo  E 999 9"84r'p(f , o  &8rs'p(+, o  8r'p(+, 8r'p(+-r'p(+, o  8r'p(+9 o  8r'p(f , o  &8r&p(),  o  +lr&p(),_ o  +Tr'p(f - r (p(f ,: o  &+/r%(p(f ," o  &+r5(p(f ,  o  &*  o o +rE(prM'po` rE(po /*:(**0Ho /*o' X , Y( , o' .o % (.( ,**0(* /*o' X o' / ( -*X o' 2*~o /o' Yo o QPr%po ,"Pr%po ,PPo' Yo Q*{*"}*j{- s }{*0\  : =;  (%д( *(_}-~_ +} *0?(do s { ( ( ( ( (  (o ((2o o &(do35(grK(p  (   Mon  o +(grK(po (2o o &( s (doo  +? o (3,*(5ozo 1 o o  o -  , o *L2 2(do*0no  3#u6o o on (4*o .o . o 3#u}o o on (4**o' - o& +"(do+ ( o**0Ko ~ +.  { o ,{ (do< X i2**0 0( ~ -7s; ~ s (( ~ -8s; ~ s 6( ~ -9s; ~ s )( ~ -:s; ~ s *6t0s*6t(s*6t6s*6t)s*V(0 } }  *B(j}*b(C(d(Fo*0(F(n 3Y(F(o 03G(d(Fo rcprp(& (Fo o (Fo o*(F(n 03X(F(o 3F(d(Fo rprcp(& (Fo o (Fo o*:oloA*0S{, (Fo (do(,*(Fo o u} ,o o ,**2(ku2**(@*"(I*0T(Mo (J o o &(Mo o . (Mo (J o o &*0(N (Ms) (dos ,(go(doo+*(do(do0o(go(go(Mo ((Mo o 9%o r(p(a o (Mo o (do(K,M(d(Mo (Mo o o (% (Mo o o oo,,o,o -o,o +o o (P %o! (M(m`o o! _(doo (L(M(n(_(doo (L(M(o(_o ;do/,Eo 1;o" o o '(d(Mo ( os# o,. s$ 9 s%   r(po&  o' (d(Ooo & (fo(cs$ r(ps o( o o  o" (a n s o s s! s) s o &8 r#)ps   o"  s o &8 s#  s%   r/)po&  o' (d(Ooo & (fo(cs$ r(ps o( o o o"  (a ns o s  s! s) s o &o.,Eo 1;o o o '(d(Mo ( oo s" o &*'3G'0Oo o +$( o 3o o , ( -$o ** 1=r(Mo o rK"p( *2(Fu1*0F(d(Oo ,(frg)po +o 3(fr)po *0o o to *0s% o . r)po& + r)po& o' (d(Ooo &(fo(cs$ r(ps o( o o n s o s s! **(@*01(X(m (t(c(x o o *0(W (X(js) (doo,(yo,(R -*o0(Zo.([o/(]o o &o,(Uo,(T*0*s (doo(v(fo b( s o  `o o r)ps o &o o &s (doo(v(go b( s o  `o o o &(do(wrK"p(v(f(  so (do(wrK"p(v(g(  so *0(js* (doo Po (X(m,(X(no+ o o &(Xo o (,J(f( o(ks* (doo Po o o &*Zk( os *0(X(d *2(Fu-*2(Xo *R(doo*0o ,bo 1Ys, o o ,o 1o- o. o- % (d(Xo ( oo! _ (do(u(X(n (_(\*4G%0<(Xo o (9(Xo (e:(h(cr*pn (hs/ (vs (Xo, s (is) s o &(is s o &(hs" o &*(Xo o uQ ,Jo0 ( ( ,3(f(Vr*pn (hs) s" o &*(hs" o &*0@o" o! _ (do(u(X(o(_(^*0(c(v(fn s# s) o( &(cr#*pn (vs s) o( &,<o 13o o % (d(Xo ( o(Xo o (, (`8(Xo o (, (b8(Xo o (,X(Xo o to o (,(Xo (e(b+G(Xo (e(`+.(Xo o (,(hs# s o &(crQ*pn (vs s) o( &(c(v(gns) o( &*es%0 P3( P. ,so + so  3( . ,so + so  `3( `. ,so + so  03) 0.!, so * so *0s# -y(Xo o tQ s o o0 o1 ,(Xo, s o (h(f(Vr}*po s) s o &*(hs o &*0.Ѐ( (fos (2 s *0s# -b(h(cr}*pn (h(vs s) s o &(is s o &*(hs o &*00(Xo o u} ,o (vo ,**0>o o (,(ftQ(z8(,(ft((d(~+o( ,gto o (,%(fo tQo (e({+)(fo t(o (e(d(|( &o, ,(*(*0#o r*po3 , o **Fr*pr*p( *Fr*pr*p( *{-(c(js }{*{-(c(ks }{*2(v(*2(v(*0-(Xo u0 ,o (Xo o **6o4 *0o4 9o o (9o, -o (5 o ,* E, 4#+2s *(p*(q*(r*(s*(o***0@t in  +#s X i2(fos6 *09M (fon r*p(h (7 s s$ *0Fg (8 (fon (9 qs (F+s$ *0kr (fon (: qs (fon (; (< qs s$ s$ *04s (fon (< qs s$ * *(Xo o rK"p(Xo ( *(Y*F(Xo o *0es (vo (Xo (o -%o! `o -o (E,%o! `o o *0(Xo o ( ,<(Xo (e,*-&(Xo (Xo o ((z*-,>, o , ,/o -&(Xo (Xo o ( (z**({*0[o0 -1o}o ,o}*o}*o (} }}*0!o (} }}*z3 (+ 3 (*.(|*0( o *0( o *{*{*0g(0 s= s> },s? s@ }.s= s> }-sA sB }/*6{,oC *0 sD *0sD oE o &*&(*N{.sF oG *0&(H (I , sJ +sK *:((*:((*:((*:((*:r*p(*:r"p(*z{/rK"p( sL oM *0-(N (O sF ( oE o &*6{-oC *0&( sD oE (o &*6r +p(*~%-( (%~%*~&-g( (&~&*~'-r( ('~'*~(-M( ((~(*v~)-r%+p()~)*2~#(*2~$(*2rA+p(*~*-и( (*~**~+-s( (+~+*~u( #v( $*0( sP | ~#oQ +8 (,$o oR -o (( oS Xi2~$oQ  +d (,P o oR ,, o oT (( ( ,% o oU + o 0( oS  X  i2sV oW  + (X oY  (Z - o * 0\u, t(*u, t(*u, t(*ul, tl(*t(*08 o[ (\ , (` o] (\ , (` *08 o^ (\ , (` o_ (\ , (` *ro` -oa - ob **oc -od -, oe ***"(* *0S( ,*o' 3o (h (f oe *o (h (f oe o9 (a *~( rs+pog ,rs+p*(*6((a *F(~:(a *"~9*2ry+p(a *2r+p(a *2r+p(a *2r,p(a *r(-T*tQo T*0Bo' 1%o .3o9  .o * .o *2rM,p(a *0' (-*( ,*o ( *0RQ~;oh +%(i (j o , (k Q (l -o **2@0B^ r,pr,pr,pr,p9r,p:(;*V(0 }<}=*V(0 }<}>*{=-{>s6 }={=*{>**{<*(m {<,{=, {=o *(m *(0 *0L(\ ( ob on + oo on 3 ,o ,o *5 :A 00 (p ri.po ,o9 ro.prK"po` *0Jo;  o{ +3X ~_  oq (Z ( o; (a o{ -*F-(z*b(+&o' -(z*B,3*(z0(sA *0(sA *0(sr *0(sr *0 s *0 sr *0 ss *0 s *0 st *:((*.((*.((*F((*F((*2(sr *2(sr *6(sr *su *"sv *s *b(G+&(-(z**ow *0pr6p(H+&uy,~x *ux -o on (Y(za( oy ua -r6po on (Z(z*0 su *0'ol  +oz oR ,*X 2*"(*0&,! +o ( -*X o' 2*0/,*o' (  +o ( -*X 2*0,s rQ'po` &(rU'po` &on *Nr6p~_ (*0-* s o +0o - +r6p(  o o -uO,o , ( o{ o| +(} -o` &o` & (~ -o *=Q},6(h ( *0a( ,rs#p*r7pr7po` r7pr7po` r!7pr%7po` r/7pr37po` rA7prE7po` *0A:o 2 o' X0QQ*o QXo' YYo Q*0Yo ~@( ,C~A( ,6~B( ,)~C( ,~D( ,~Eo **0X (Z s  o +' o %X , (Z o` &on o` & o - , o on *3G 0+ o9 + o: o o - ,o * *o **o *.o *. o *0( uQ -*~(; , o **.o *0[|( @}( A~( B( CЀ( D:( E*0O(0 -( +( s }Fs }G~I-s% I~I}H*(0 -( +( s }Fs }G}H*:{Fo *0`  {Ho +"X {Ho (h (& (a {Fo -{Fo , {Go *&(*:{Go * *0  s ( o ,o ~P o o ~O{R(f ,~O +"o o ~N{R(f ,~N o s r1:p{Ro r;:p{So rC:p{Uo rM:p{To rU:p o tQr:p o tQr5;p o tQ~_ Qr;p o 9 o 8o to o  8 o tAo r[po ,ro rR<po ,^o o  +. o tAo r#)po , o Q+  o - uO  , o  o :` uO  , o o :uO  , o *4  ;@ 0Ms ( o o s o o & (  o , o *1B 0Hr<p}Rr<p}Sr>=p}Tr=p}UNHr >p}Rrh>p}Sr>p}Tr*?p}UOHr?p}Rr?p}SrD@p}Tr@p}UPrApQ**s *0H#?. #3~V*#?3(*#@3~W*~X*s Vs Ws X*-{Zs< o *{Zs o *0Ks5 }Zs}[s}\s }]s }^s}_(0 *0rBp`rBpar,CpbrZCpcrCpdrCper Dpfr8DpgrfDphrzDpirDpjrDpk.l*N(9o<}w*>(9(6*6o<}w*Z{woq ts+* * *:{w(I+*:{w(I+*:{w(I+*:{w(J+*:{w(J+*:{w(J+*:{w(J+* *:{wt*:{w(p *:{wt*:{w(p *>{w t*>{w (p *rExp*N(9o<}w*>(9(6*6o<}w*Z{woq ts-* *:{w(I+*:{w(I+*:{w(I+*:{w(I+*:{w(J+*:{w(J+*:{w(J+*:{w(J+*:{w(J+*>{w t*>{w (p *>{w t*>{w (p *>{w t*>{w (p *rp*:(=}z*s*:(=}z*s*b(s rp(t (@*>(u (A*{*{*{*{*{*{*{*{*{*{*{*{*{*2(Q or *s/*0wrHFpи( sv }(N {ow rEpи( sv }(N {ow rEpи( sv }(N {ow rM9pи( sv }(N {ow rEpз( sv }(N {ow r p( sv }(N {ow rpи( sv }(N {ow rpз( sv }(N {ow rחpз( sv }(N {ow rpз( sv }(N {ow rpз( sv }(N {ow rp( sv }(N {ow r1p( sv }(N {ow rUp( sv }(N {ow *05(N rHFpox }(N rEpox }(N rEpox }(N rM9pox }(N rEpox }(N r pox }(N rpox }(N rpox }(N rחpox }(N rpox }(N rpox }(N rpox }(N r1pox }(N rUpox }*sD*.R( *f( ( tQ}*{*0>m{o1(y t # {o1oz {o{ (z*#N{o1(| *0>m{o2(y t # {o2oz {o{ (z*#N{o2(| *0>m{o3(y t # {o3oz {o{ (z*#N{o3(| *0>m{o4(y t # {o4oz {o{ (z*#N{o4(| *0>o{o5(y  # {o5oz {o{ (z*#b{o5(| *0>m{o6(y t # {o6oz {o{ (z*#N{o6(| *0>n{o7(y  # {o7oz {o{ (z*#b{o7(| *0>n{o9(y  # {o9oz {o{ (z*#b{o9(| *0>n{o8(y  # {o8oz {o{ (z*#b{o8(| *0>n{o:(y  # {o:oz {o{ (z*#b{o:(| *0>o{o;(y  # {o;oz {o{ (z*#b{o;(| *0>o{o<(y  # {o<oz {o{ (z*#b{o<(| *0>o{o=(y  # {o=oz {o{ (z*#b{o=(| *J{o1(} *J{o2(} *J{o6(} *J{o7(} *J{o8(} *J{o9(} *J{o:(} *J{o;(} *J{o<(} *0k ~_ (`-(F (a-&~_ ( , rK"p(a (H(a ~_ ( , rK"p(a (J(a *{o1(y {o2(y {o3(y s{*0s$ }~-zs% ~s}s& }s' }s( }s) }s* }sn}s+ }s, }s- }s. }s. }s/ }(0 }*0s  }*:{o0 &*6{o1 *0{o {o  *n{o2 {o3 *2{o4 *0a{o5 ,*(n,*{o1 -5 W( ts< (x{o0 &*0{o6 &*:{o7 *:{o8 *0XlR{(wrK"p( oK+ ,1{~o: /Po . Po 3RQ**0S{-D{oL+o; +o< (,o }+o - ,o {*)B :t(y*0RSol ,I-~{o= ,{o> oH *u  -s {o? *FrK"pr,po` *0i,(p -on }+},(p -on }+},(p -on }+}}*RWWo *.(|*{*{*{*{*0UuW-*W {{( ,*{{( ,*{{( ,**0F {,{oE a {,{oE a {,{oE a *0y ~_ (~, (~(a (,&~_ ( , rK"p(a ((a (,&~_ ( , rK"p(a ((a *r{-{- {**{ *"} *{ *"} *v(0 s ( s ( *0D( o o +( o ( ( -o *#5J( o ,**J( o ,**0 o , ( o **0 o , ( o **( o ( o - ( o *( *"( *6oe ( *6oe ( *6oe ( *6oe ( *0k   rp rp rp rp rp r$p r.p }K  r6p rBp rTp rbp rnp r~p rp rp rp  rȚp  rښp  rp  rp  r p rp r,p r<p rRp rdp rvp rp rp rp rp rp rԛp rp rp rp rp r$p r2p  rBp !rNp "r`p #rjp $rtp %rp &rp 'rp (rp )rp *rȜp +rМp ,rp -rp .rp /rp 0r p 1rp 2r$p 3rp 4rp 5rp 6rp 7rʝp 8rԝp 9rp :rp ;rp rp ?r(p @r:p ArNp Br^p Crhp Drrp Erp Frp Grp Hrp IrĞp Jr֞p }s/ rprpo& rprpo& rprpo& rprpo& rprpo& rprpo& rprpo& } s r po r$po r*po r2po r8po r@po rJpo rPpo rVpo r\po rdpo rlpo rvpo rpo rpo rpo rpo rʟpo r؟po rpo rpo rpo r po rpo rpo r(po r0po r:po rFpo rPpo r^po rhpo rrpo r~po rpo rpo rpo rpo rpo rȠpo rڠpo rpo rpo rpo rpo rpo r.po rDpo rNpo rXpo rhpo rvpo rpo rpo rpo rpo rpo r¡po r֡po rpo rpo rpo rpo rpo r*po r4po rFpo } s/ rRprbpo& rtprpo& rprpo& rprpo& rТprܢpo& rprpo& rprpo& r*pr8po& rFprVpo& rjprppo& rzprpo& rprpo& rģprңpo& rprpo& rprpo& rpr"po& r.pr6po& rBprLpo& rVpr`po& rlprzpo& rprpo& rprpo& rpr̤po& rܤprpo& rprpo& rprpo& r"pr0po& r@prNpo& r^prxpo& rprpo& rprpo& rƥprҥpo& rprpo& rprpo& rpr0po& rBprNpo& rZprnpo& rprpo& rprpo& rprĦpo& rΦprަpo& rprpo& rprpo& r(pr4po& rBprNpo& r\prhpo& rxprpo& rprpo& rprpo& rprҧpo& } s/ rprpo& rprpo& rpr,po& r@prLpo& r\prhpo& rxprpo& rprpo& rpr̨po& rprpo& r prpo& r0prBpo& rRprhpo& r|prpo& rprpo& rprکpo& rprpo& rprpo& r&pr8po& rHpr\po& rnprpo& rprpo& rprҪpo& rprpo& rprpo& rpr$po& r.pr@po& rPpr`po& rnprpo& rprpo& } s/ rpr̫po& rܫprpo& rpr*po& r@prXpo& rrprpo& rprpo& rpr¬po& rجprpo& rprpo& rpr"po& r6prFpo& rXprdpo& rrpr~po& rprpo& rprpo& rprƭpo& r֭prpo& rprpo& rprpo& r,pr<po& rNprZpo& rhprvpo& rprpo& rprpo& } s/ r®prЮpo& rprpo& rprpo& rpr.po& rDprPpo& r`prnpo& rprpo& rprpo& rprȯpo& rܯprpo& rprpo& r$pr2po& rDprVpo& rlprxpo& rprpo& rprpo& rİprְpo& rprpo& r prpo& r(pr4po& rDprPpo& r`prlpo& r|prpo& rprpo& rpṟpo& rܱprpo& rprpo& r"pr2po& rDprRpo& rbprppo& rprpo& rprpo& rprȲpo& rڲprpo& rprpo& rpr(po& r8prFpo& rVprhpo& r|prpo& rprpo& rprpo& rгpr޳po& rprpo& rpr&po& r Epr8po& rHprXpo& rlprvpo& rprpo& rprpo& rprԴpo& rprpo& rprpo& r pr4po& rHprTpo& r`prlpo& rxprpo& rprpo& rprƵpo& rܵprpo& rprpo& r$pr4po& rBprRpo& r`prvpo& rprpo& rprpo& rʶprڶpo& rprpo& rprpo& r$pr:po& rNprdpo& rPpr`po& rxprpo& rprpo& rpr̷po& r޷prpo& rprpo& rpr2po& rDprVpo& rfprxpo& rprpo& rprpo& rȸprظpo& rprpo& rprpo& r&pr4po& r@prLpo& rVprdpo& rpprpo& rprpo& rprpo& rҹpr޹po& rprpo& rprpo& rpr0po& rBprRpo& r`prnpo& rzprpo& rprpo& rprpo& rʺprʺpo& rںprںpo& rprpo& rprpo& r pr po& rprpo& r$pr$po& r2pr2po& r@pr@po& rNpr\po& rlprxpo& rprpo& rprpo& rĻpr̻po& rػprpo& rprpo& }s r@po rlpo rpo rpo rpo rpo rpo }s/ r(pr4po& rprpo& rpr,po& rDprVpo& rjpr|po& rprpo& rpr¼po& rԼprpo& rprpo& rFprpo& r"pr.po& r<prHpo& rVprbpo& rprpo& rpprpo& rprpo& rĽprؽpo& rprpo& rpr&po& r:prJpo& r\prlpo& r~prpo& rprpo& rpr̾po& rܾprpo& rprpo& rpr&po& r6prBpo& rPpr\po& rjprvpo& rprpo& rprpo& rprĿpo& rҿprܿpo& rprpo& rprpo& rpr2po& rRprnpo& rprpo& rprpo& rprpo& r.prFpo& r`prxpo& rprpo& rprpo& rprpo& r(pr@po& rZprrpo& rprpo& rprpo& rprpo& rpr0po& rHpr^po& rvprpo& rprpo& rprpo& rprpo& r.prDpo& r\prrpo& rprpo& rprpo& rprpo& rpr*po& rBprXpo& rpprpo& rprpo& rprpo& rprpo& rpr0po& rFprZpo& rpprpo& rprpo& rprpo& rprpo& rpr,po& rBprVpo& rlprpo& rprpo& rprpo& rprpo& rpr(po& r>prRpo& rhpr|po& rprpo& rprpo& rprpo& rpr$po& r:prNpo& rdprxpo& rprpo& rprpo& rprpo& }s/ rprpo& rģprңpo& rprpo& rpr(po& rHprhpo& rprpo& rprpo& rprpo& r8prpo& rTprppo& rprpo& rprpo& rprpo& r,prFpo& r`prxpo& rprpo& rprpo& rprpo& rpr2po& rHpr^po& rtprpo& rprpo& rZprnpo& rprpo& rprpo& rpr,po& r@prTpo& rhpr|po& rprpo& rprpo& }s/   rprpo&  r prpo&  }s/   r,pr:po&  rLprZpo&  rlprvpo&  rprpo&  rprpo&  }(rps (s }{ s}{ s}{ s}{s}{s}{s}{s}{s}{ s}{ o( { o( (M+{ o( (M+{o( (M+{ o( (M+{ o( (M+{o( (M+{o( (M+{o( (M+{o( (M+{(M+{(+s }{ o { o (M+{ o (M+{o (M+{ o (M+{ o (M+{o (M+{o (M+{o (M+{o (M+{(M+s }*0crp(+&{o ,*{o ,*(-{(o o ,*oo ,**0lrp(+&{o ,*{o ,*(-{(o o ,*(-oo ,**rp(+&s% (*0{o , {o *(,*( (,(a *(,(a *{oe o - o,(a *{o ,{o (a *s r po ~-s% ~((,(a *s r(po r4po ~-s% ~((,(a *s r@po ~-s% ~((,(a *s rpo ~-s% ~((,(a *s rLpo ~-s% ~((,(a *s rVpo ~-s% ~((,(a *s   r`po  rhpo  rppo  ~-s% ~((,(a *{o ,{o (a *{o ,{o (a *s   rxpo  ~-s% ~((,(a *s   rpo  rpo  ~-s% ~((,(a *{o ,{o (a *s   rpo  rpo  rpo  ~-s% ~((,(a *s   rpo  rpo  rpo  rpo  rpo  s% ((,(a *s rpo rpo rpo ~-s% ~((,(a *s rpo rpo rpo rpo rpo ~-s% ~((,(a *rp(o ,o' Yo r p( *{o ,{o (a *s rpo rpo r po r&po r,po ~ -s% ~ ((,(a *r2p(o -rp(o , rp( *rp(o , rp( *rp( *rp(+&s% (*0s {o , {o *(,*(}{(,{(a *{(,{(a *{{oe o ,{(a *{{o ,{{o (a *{{o ,{{o (a *{{o ,{{o (a *{{o ,{{o (a *{{o ,{{o (a *{s rtpo ~!-s% !~!((,(a *{s r|po rpo ~"-s% "~"((,(a *{s rpo ~#-s% #~#((,(a *{s rpo ~$-s% $~$((,(a *{s rpo ~%-s% %~%((,(a *{s rpo ~&-s% &~&((,(a *{s rpo rpo rpo ~'-s% '~'((,(a *{{o ,{{o (a *{{o ,{{o (a *{s   rpo  ~(-s% (~(((,(a *{s   rpo  rpo  ~)-s% )~)((,(a *{{o ,{{o (a *{s   rpo  rpo  rpo  rpo  r*po  ~*-s% *~*((,(a *{s   r6po  rBpo  rNpo  ~+-s% +~+((,(a *{s   rZpo  rbpo  rjpo  rrpo  rzpo  ~,-s% ,~,((,(a *{r p(o ,'{{o' Yo rp( *{{o ,{{o (a *{s rpo rpo rpo rpo rpo  s% ((,(a *{s rpo ~--s% -~-((,(a *{s rpo rpo rpo ~.-s% .~.((,(a *{rp(o ,"{{o' Yo (a *{rp(o ,{(a *{rp(o ,"{{o' Yo (a *{(a *0Qo (,>o' -*o' s o ( o &o9 o` &on **0 o Xo QXo9 *J( -( **o ( -o o , rp( ,**0_rp(+&{((-;(o o -rp(o -{oe (N+,**(,o' 1{ oe o ,**0nrp(+&rp(+&{o ,rp(1rpsA z{o ,rp(1rpsA z{o *jo' Yo rp(a *jo' Yo rp(a *jo' Yo rp(a *jo' Yo rp(a *jo' Yo rp(a *jo' Yo rp(a *jo' Yo rp(a *jo' Yo rp(a *2rp(a *2rp(a *r p(o -o' Yo rp(a **jo' Yo rp(a *2rp(a *2rp(a *jo' Yo r6p(a *jo' Yo r<p(a *jo' Yo rFp(a *jo' Yo rPp(a *jo' Yo rZp(a *jo' Yo rbp(a *Bo' Yo *jo' Yo rp(a *Bo' Yo *jo' Yo rjp(a *jo' Yo rnp(a *Bo' Yo *Bo' Yo *Bo' Yo *0's }}s (O+*rQ(, o Q**0(0 }/{/o t r*pow }0rFpи( ox }1rdp( ox }2rpm( ox }3rp ( ox }4*b{3{/oy tm*R{2{/oz *b{1{/oy t*R{1{/oz *R{4{/oz *0n{0{/o t M o{ -+o{ s| o; o} o~ (o (o &~_ *ME0I-#~(N , (s*(s*~(N , (s*(s*"( *{5-}5( (( ( *"( *(*(0 rp( o s }*0 ~-s (P+&~* *.({*0u( -*{(o ,Si1M +6u ,& o' 1  o rp(a X i2( ( **0( -*{(o **R(*0( -*{(o **(0 *>o {*(0 *Jo {(f *07(8 {3{3 } +s {}*(*0 { Ez8}{{o o }}+Q|( }{uX-3{{{o oQ+}} %}|( -( (*{*s: z0"{ YE*(*{*f(0 }(8 }*f}|o *(0 *J{o oF *(0 *N{{(*(0 *2{s6 *(0 *{*07[(8 {3{3 } +s {}*(*0{ Eb8}}8{~QZ~QX{o' /4{{~QZ~Qo }}*}+-{{~QZo9 }}*}%{X}{{o' ~Q[>V*{*s: z*{*f(0 }(8 }*07\(8 {3{3 } +s {}*(*0 { E\8}}{}}+I{{}({(}} 6}{X}{{i2( (*{*s: z0{ YE*(*{*f(0 }(8 }*"}*(0 *J{o oF *(0 *^oL{o (f *07(8 {3{3 } +s  {}*(*0 { . ;8}{{o@ oA }}+m|(B }{oP }}+/|(Q }{}} 8}|(S -( |(C -(  (*{*s: z0H{ YE*{ YE+ ( ( *57$@{*f(0 }(8 }*f}|o *f}|o *(0 *j{{o' Yo *(0 *R{{o *(0 *6{(*BSJB v4.0.30319l#~p#Strings$#US(m#GUID8ms#BlobW+ 3p3O 5 = %QH`cJmJKcϭc\cJ5xc}sb*_BJi~xcJ.m_xc=dcLccxc, d do dcxcIcJ} d ~n nӢZ ̀nOsbjcCxcsbc\uxcxcurxcJ_ xcHxcjDxcuHxcixc*}xcxcpxcxcRIxcxcY}xc/xcxcyxc/xcsxc"xcbxc|xcchHrxcqxcxcrfXcZoJxcXfXS dn d$ dt d?l dk dNj d<2<J13cN_BxcuuIt!yq1#u7Ѻ}!y.xceMzWpaWpGc_'xc%*xcԏ!yd cJ hq7Bc*zBpu c܈ZzpzpsZ l d^m d͗ d4pr dl d dm_m_vyc@m_t d&pxc m d]Cxc{xcf! d~_eJ.Jxcj d|cOQc4YfX3fX8h{)e( d dk d% dp d׋fX`hcSfXJt d s dl dOs dIJ< Zr d dr d dG dj d*wcZl d dQ dq d_Ocvc3cP|}uӇr=Jjt"%""!ywA^u~suhs!yۃ!y"W#c_ԸcjcB{xcNCp-m_Asb!yt/ݐ9`SxcScZxcyxcAc_.e_Xݐjݐwlݐjݐmݐjݐ{mݐu!yf/ݐRvc.qZc\_4_v_8xcxv_cBZqe AOsb&|pYpwp>p×_k d_OtprOtpN_Z cZ c_.__I_cJJAm_m_m_Hum_[`h{?sJ][c՜k dr dl cXk d0  3c@ctk dm d9 dy-m d+u dc|ul d'#c cάc|dc d c__JxcxcfxWvcwcsb/sbsbF/sb1sbQqsb{sb'XѺ0Nc¢czd"d a,MRwdvϊd,[X[dddd[%ß_Ćßj+ßzSßß_ß=ßjß؆ß}ßzß%/sß*~CA03HA0EßA0ß0;?XJß@ßGßAQßQ @z-ßß0d<!xd=??`4y?_4y?/,4yFdJ =R`dVKYd`qhm hwgl+ l-.,A/!s,U/Q,MDdkAkKkGA{ 4{[:[.*[_[/H/PU52SY66pO nTp&\ 2K p2KE{T*vTzTT)TTVj.TV:.T-T5(}EUlUUp UP-UoBUU Up U6](UE_,U{/U@3Ui8U#((.(1(1b(1j(1b(1\(1b(1(1=(1b(#V -V8VMVMV XVF8VMVMVXV8V MVMVJXV8VMVMVXV%~cV#hVuVxmV1{(1EK(_mVZqVqVT1qV}eqVZqVqV-1qVSeqV]qVn;qVqV>MqVQ(Q(Qd(QC(Q(Q(Q[(Q9(Q1(Q(Q9(QL(>vV6_8U6K8U6 8Uǭ8U8UizV~V!(d(?VUqV6({/U]Vi8U ,UVVVVV V VQ( V V*vTzTV VV V.V VVVVVQ8(Ql8(Q8(Q7(Q(Qz (Qp(Q^ (Q?(T?(VlVWVQ^(Q(Q#(QL(cT-V1{)(MVs((WU,UZrUtW) WWWW-V1ҙ!W8,U.&WbY(.&WI/W١(%(d(14W1s4WQk&(:WF0T1xHW1ʞHW1`HW1ڞHWTV%LWV[LWVSLWTVQWVQWVQWVQWV$QWV$QWVQWVQWVQWVQWVSQWTV/WVe^/WV/WV\L/WV-^/WV/WVL/WV /WV]/WV/WV/WVWs(([(% cWm cWcWcW#1B,UQU?(TV!hWV$hWVhWVT!hWVhWQs(Q5(WmW`WmWj2U2UQ=(Q=(Q=(Q=(V/8(3QGV3jGVAU @UݬU UUOZUdU!rW!rW!}W!nWV((V)(V((V)(V`5(Vx5(V(5(VH5(V:(gW(W&,U@W[(Qx(1}HV1HV1CHV1AV1DV1HV!W!W!2d&W.&WS>(ST(S(S (1W1 W1W3h((;_(b(@_(6_8U6K8U6 8UHrUxW=WVW}WΛWdRU36(3m9(3(3_8(3<(3B<(3I(3(3?(35(3(3(3ăWQyTQTQTQTQTQ9TQTQTQTQNTQ&TQyTQTQTQTQTQ9TQTQTQTQTQNTTVSWVWV/WVψWVWVYAWV_0WVhWVWV#WVMWVWVWVWVCWV WVWV&WV.WVWV $WVb$WVzvWV:vWVBFWVbFWV"FWVRWVyWVWVyWVgWV#WVWV=WVJ{WVĨWV׽WVgjWVWVWVWVWV3WV1WV7'Y>u'v-YA}'4A'Df A'D A'PYB'YB'WYB'(B'ZB(A-ZD(Bf D(B D'(ΎZE/(ZE7(WYE?((EG(&ZEL(Q.-ZF8)-3ZGt)(K|)&ZK)Q.-ZL*i>ZM*(N*&ZN+Q.-ZO+(P+&ZP+Q.-ZQ)+EZR\+~bQZV+~bfZ[-Zdb-(ex-=Zf.9g0ȰZhh1~Zi2NZj2jZkH3G l3Zm$4ˮ2 p4eZq4Zs45Zt6WZu`7ձZv7kw8Zx:9y2:Zzl:Z|:Z}&;YZ~V;C[t;8 [;C[;[<([@>/[>yigy*`yX `$z `tz `z1 `{t '{L{t`| u'`|m1-`|"X`~m`dhyz``>Z `; `p`~`o`$`1l'`>W`LD `b `́ `ځ``\`i&`vRV`W[!K( Z  8 D K Bd 3  W < a E >a . ` .`lo``Z`z` bK`}` F].`w(W[}`6`(g`e`Df`g`ńg`̈́e`Մ2f`݄g`g`f`e`f`,& e`!rH-(F Xϡ(p(c1aZZp<1H1cePpedtZZԊ0D1!19eFe$]]D;Y; h|L؍Mfa``*a=VaP}`c`vaaa ̎&a?aH6ax6a=ja7a( (#a]'a'a (a3i`j,aPj5aW[;k sq {_\=aŒLa@t]aēteaTLa)oavo}aڙyaq(hahaڪa|Ga_a8Vua/a ȕaDaa(a2 b2 b!b ĥ'/bKb\aEa.aXzTb Hb`[Hb"Ьb' b,,|b1*b3b5b78b85 c9 c:& c;.oc<6) $c=>I-c>FI3c>^?C|@VA#VBOk*:cC(D&DS*R\F_*X\FX\G8Hŷ!>Iݷg?CcJ OYL/vUYM7vOYMJzZYNTQ.KcNQ.YRQ.]cU8Q.YXQ.jcZ(Q._Y]Q.yc_Q.lYcI.cftfcjdicldicn|I.cpܿMcucu4cx,cz d| d|d|\ d|G d|P_Y_[%Y_f Y_qY_|Y_dW[p{ { Sm /dr| @dd:$d$d@| Em @m (@ dX| m B dJ{d| ,dPcdtS(dY0(dh| ={  ݂d0A m XWm Ad[lVdWW[YndicYK(twdwd1wdHĀd gĉd!Òd"]d# EUd$\_Ud%\Qd'Qd(,d)<=Od+ ,[nd,e0d.yK(/0d/d2td5cZ8d8e9 ;k e;le<-c0=:,bd=Be=T0&e>0e@|0ejek6zem6zeq,0UYv,bdv@evDevDfyDf|D fHD-fD9fj$kFfD,Ofx,VfN:+,OfM6Z6h)^fhdUdfʷYYjfpsf{fŤfD|fff餩flfDfW[ cBf f0dXd#l%dc%fTBf4GM<fF0ddcBf #cff _f8 fzK((XT3g|dldv!gXg#g%,gt5ghDg(EQga/lYgyc M_gXd  0dcBf #%cY4igqgʠ Ԡœ%t$-$6t@xg>}@~gGj]M\T]MMMc^MG^MZLM?LM$+^M6^MHMZMlM~dMMMLMuLM MMMLI{&gW[00g0g:(Dghyg0 4gP ig g  ug  _+  {Cg | _gՅgdg0HgMpF{&ghg ,0UY!90OY! h"8W["h";(% @e%00h%0$h'0h*<W[+8h+ 8h-.}8h/<Q 8h130Ch50Nh70[h;J<`ch>4dAqK(Bl(Bn;dBH=CcmhDshD4dGdH`~hI ^-=p-2oZi-0gi.oi.yi.i)/-iH/iT/Nit/xi/2f / 2f /(0Fi(0Fi@0Fic0Yim0Yi0Yi0>Ci05Gi0Ci0Gi0i1ޠi1i01eii1Fix1Fi1j13f 1?f 1ʬf !2q f D2f b2zf o2f |2Pf 2WYf 2xdf 2W[2j,49j49j49%j59,j9593j[59;jd59Bjh5JM5)=M5;M5;M6ӼHj69M6a=M*6:M76>MD6J#Ojd6J>f69M6(j;A1$;s ;r3j;j;';'i(<'jd<zYk<Y k<&Lk=5$k=/VM>>+k`>D4k >/:k a.G..G`.Gb.Gk.G`/HZ`1Hz`2(H 2,HZ2;H 2JH82YHD2hHK2wHBd2H 32H2HW2H<2Ha2HE2H>a2H.2I`2Ib2Ik2)I}`31Ik3@I}`4HI(4aI 4qI/g`6yIe`6If`6If`6Iuf`6If`6IAg`6Ig`6Ig`6I"f`6I8h`6Ie`6I!h`6I6I,& 6Iϡ(6tLp(6Me`6MrH7M 7Mc1k8MZ8HNZ8\N 9N+9N_7:(Om7:P\> Qih?hQh?QMh@Q[h@Q0AXR0AtROBR^ŎBRCHSCdSDSDSvaES`ES/aETaE%TaE8TaEKT`E^TbbEqT`ET{7ET.kE8UkF VkG)VGkG8VZkHHV_kInVkJVkLV(kLW@lN%W ElO4WElQDWB#lSW(VXF.lV(XF7lXXMZXCl[ YRMl_"Y^Mla.YZc6Y c>Y_7cFYGWlcPYcY^.dZZdZdZͿ)dZdZB4eZ^ eZ(fZfL[g_[#Bht[Si[UKj[Sk[(m[]lm\n\#o#\Up1\Sq@\(r|^r(}C|s}Vt}Uue#VvVw@VglxR&slzˍ|ލ} U~w4&&M9MT1MoMM&M9VMۏzMMMAj M\ Mi Mv M M MǐM0M;MZM)AMDMUMp%M'MM6M zl &lr 䟓l[*[?z]lTKl5>xfoYw(~lȔIT˔hlؔ%Z$k\%ZM%ZllW[(Õlӕ(ە^ lnl3<Ⱥ [Z($K(d ml((f(×lח(ߗjj( jj*l?HȺ1 9(@K(B mJdȉlȺ| Yg(K( mٚW((f(Xl (mclȺX  m`(hK(؜ m(kV(.(6VQ(YFn(vm()((()((uU%7V7V\ %7V7V\ uUuUuUuU+vuUq[[q[R\m\~q[[s.xm.xm.xVV-5~EuUQ-pBuU܀܀Z,7܀i܀܀AF_{iAtaMiEAtaM{di EaMIhunHzDH97##Γ##>p,]IIc}c}/@>xIz//C3(dEP##lcI\|AsiAA:uxAhAI_AogIAI_IAAI_AI_AI_AI_AuU0"E l\"E !eeeee6<q6<uUuUi7A7AP6<AAmm>/Emmmmm˪mHm4˔/mhmm!m DmhnynmhnhnEmnm-dz]Ima| .ma|%.-85656 8? WW|||||Z?srZ?+vuUxq]\xqӄxqӄixqxqixqixqɄӄxqxqxqxqixqXn{:X4ZE#DZlK8rKjiiqAqqAqi ii7V7Vo> Zo> ZjbN3:y ub[K:y#Բ#Բ?uUY/uUz uj u_zruUuUuUuUuUuUuUuUuUuUuUuUPi'iiiii'iiii&~iy6io> Z6uUi7Ao> Zo> ZiitiI*mImIGmmUmAmmm IH:mIE"pmn!!n0mmmmyBGmGmGmؚmͦ@m@ml7*~~uU&&&&JN|^uUj,77!7+vuUq[R\miq[R\mq[R\iq[R\iiq[5mi&~iq[i}iq[i5miq[5mb[.,787V7V7V7V7VºbhbbhTbbbbhTbhbhbhT& bhTbhbhT& bbhTbbbbhT& L  bhTbbhbhbbhbbbbbhbhT& bbhTbbhbhbbbbbbbbbhbhbhTbbbbhbbbbhbhTbhTbhT& bhbhbbhbhbbbhTbhbbhbhbbbbhbbbbhbbh::mmIc}uUceccccccclSlSc_:_q:_:_ _zD##E--_pB_-_-_9-_9Ic}!._qc}-._q-_4B^lS^lS^._._._u[rmcccCBBy}uBy}u0..0..B0.B0.BIIk6?IH6VVc8tc8t8tܲn8tb4p8t8tW8tlC___e_pBB?H_@xx__x%G,n%G,nn__<IG0^@uUuUuUuU^@^@^@kW^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@M^@&%^@^@\ G0&~AG0n)&~A&~An)&~A>^@>>^@^@?>5^@>?>?^@?^@^@&^@&^@&?uUt([0?I0%cc\ #c2B__?2B__"I??y?$@}e2BjE__~E_iA-qm;#uU#eH&0??eeuUuUuUeuUeuUen@yI^BpBSH-B-B#-H#-pB#-H-pB-pBII~IIk^??????6?^EE$Hc}c}c}c}c}D]c}c}?;; ????IC?lSI?y?y&AA[܀[[7VuU:=uU:=uU::=<:=:=6nn0Zw;7w##6<x<00Z:i:=cuUuUuU\keEe Tܸ`?\97VcII}JiIIUU3dففuUفuU1c /:/.SZNcBi0.7Vz uzz uz``_zrPuUuUuUuUuUuUuUuUuUuUuUuUuUGi##IIIII8BIIZ?Geiei\uUuUuUuUuUuU-USuUuUuUuU&&&&&&&p&G&&&&&N|^&~J&~$&J?&,uUuUuUG0iyuU?`??\?|L|LL|L=5A=Q5Zb"b5b&b1b=ii5i i1i=jj5jj1j=mm5mm1m=aiaȺ#a(y!K(2$#,242<#D2L#({(( (!)19AIQYaiqydcd"dĦdUdOTdcdcd8|(dd( (V@0Ul(t(tc|2#y/Alc(aK)aMa8(aKa\r,dKjlP0cVc.j^Al#AȺ(((((  ([3!('+1-7@h$RFIKLAIT1Z10]a9hgQW[( ZAPsI/A#@Ae|ldQ(Y((!'!2#2# 6a(aTaoa_K#ȺW[((14Úd )b#Ji`4Y9/Cy/BOCOOP~NQOR " (#Ⱥ9`49.;BTA($#$Ⱥٝ^,(4#4ȺIh{<(D#DȺQ쑘L(T#TȺY4YY+4Y`4\cd/Haa;EllcCt(|#|Ⱥ OT(5@EA:p| }!Úc5SY;B(#x_2#2>`44#vdT|SȺEzT 3%Q0 GRæ5^Fiŵ#SY`4i(#ȺI2#`4H06(#Ⱥ`4SHYOT_Y`42##C (Ħ #cȺĦ$,#c,Ⱥ4<#<ȺDL#TU#TALȺE)\cIdcli 2RTPKWtct쑘\"|(\(((((d(4(D(lcl|cc(ctÚ\Kl(lccl#Ⱥ(2#UlJP02#6+4P0B7/@K(c\|6+s(!^Ⱥ6+s  ȺϧƸ5DK?(6(91J'$$3%N%-9K@Dc/,(,cAY,4#W|k4Ⱥ<((DsL<cLȺ"cOTT"TcHVWZVc|OT\(OT_TOT\c|ci\cÚRTPI"dcOTccc]dcI D`dY lÚE+ }2 |2 d#dS|cA9 ? aJ 5Q \c\dX %] b h ̅] m lcA} T(( (tQ!K(F |2#!( (#!.Y ۻ ȺQi,r t0#!()(e q )(1)$ Qc ! Y0[ ac$ qF[+ 93 : yc@ )G cM S A(aZ j r Iw 9 Ac 1 c 1$ c !/{  #SȺ(<4c 9(i4:A 9D  9" c   c c `4Qy - `4j I7 3 + B 3 ZL h\AcS IZ 9Df k r m3  | Y(11 1 cA}. (h WZ !(R Z ),K    ^d(K(t W 2#}= ̚F QAL R YcX Fa2` 0"n qsAt qJ@{ q#Ⱥh\ # # " (<Sr c + $ ! U !K(!K(f` h@Q(m7  Ic Ic c :_7c 0b ( c1& , b2 (*B c7(KB "nB ÚO IIA\ IFI:I(b t Yi b s d| ͹  2$#,c4<#<ȺDL#LȺl ( ( (u(qu(zX((n 9`4\\L mr u  cTc f\(\8|(\c\\cdÚ UdUl(lc(;(K%Fd%%l\7Dcdc K=KCt(|2#t8|(tctc2#4cUtt#0ÚȺLOT_cc(08|(\8|(cc֧3cQ-(2 #cQq$cK$c$OT T,#,BT8U! $c$6+Kc4#,c4Ⱥ9 (KK(](cY PdY <I 1!Y ['D<cY =Y ǧP \qi uo "xqݺv~4(L,((T((d(D(\(d(l(t(lclÚ\cdc\6+\OTdOTtctOT!cy|2# " c c 6+sȺ ^.ÚAB7A> * ( h 7{ 3 ɥAIK hB+iZQlM F\{ V@1C M ZMRKW0/^Q1QJXQ})KeQ#@QeQ70l ,w(}! ( Ž =3 m P0\-䟓K, G%aRTa[TywQ(Q?QXXQ7ici (! G \7P0#cȺ\7P01I#c( 2>>1 hgA j 9DA:LTa R LJi Yy _ QK(K( ZM(K(!cm Ju{Úcq.j}u 쑳"c5mFB'5#!cȺaRa^o!AJT 'Vd[   c S\ ex1]# (c\7ȺA쑘SD1Y 7 cS Tc(}@ (}@ t@f > \7AP0= (D(}@ i4 Oc\U͸c'iT(T#"ccȺQ@@,@ (2#  R[ ]# d{#'V'] \() L 7M9 A9 ZL 1  ]ud{P0$d$#$,,#Ԗ A (I (5 3 Q 3  m3 A(AP08|(a Gá>OT_izTq Twy B i Z9 #'9 ș3 ș3 7 ș3<DQLTQ\dQDL lTLl#lStdLt#tS|{:|"|c|c|c(|  cȺA$Y^A$a%az%ILI=I:QLQ=Q:ZL ##SȺy(vSS {UMaa%y%%' ,, _,1c\޸>\#ȺyG^æ{(cL0"cOT (IK^ K 3f!  {1k q C(! /x! ѐ ! Ԗ9 ! `4! SA ~a#X N/! !K! y!+!((^ (Ħ#cSȺͿ)"B4"#Bccc\(\\\#B\UK\SA\d6+\Ú\R[ #`oi[F\SI ox-Tv%Z~v, {,,,,v, {,(v,,{,0,4,8,, ,$,(,,-0-4(-87-<H-@W-Dx-H--- .q..'///D0, ,0 0$0(00v,{,,v,{,,0,00,11 1{,,0,00, 11 11D1Lv,P{,T,X0\,` 1dM1xn1|1111;2b22233K3v333(3,303444v,{,,0,00,11v,{,,0,00,11 114444 4$5(5, 5054585< 5@%5D*5H/5L45P95T>5XC5\H5`M5dR5hW5l\5pa5tf5xk5|p5u5z555555555555555555556H-#686I6d6w66666<6@7D7H7L 8P8T!8X,8\W8`|8hv,l{,p,v,{,,0889Z999:T::: : :; ; ; < l< < < <$ >=( a=, =0 =4 >8 O>< >@ >D >?H w?L ?P ?T @X c@\ @` @d 2Ah Al Ap At Bx _B| B B C UC C C 6D uD D D E ;E E E $F MF F F F G 6G eG G H LH H H 3I I I I I &J kJ J J 8K K K L jL L$ L( 9M, xM0 M4 N8 GN< N@ ND OH OOL OP OT OX 3P\ pP` Pd Ph Ql VQp Qt Qx R| LR R R S HS }S S S S 3T T.s{,.{n.n.n.n.{,.n.o.{,.o.o.o.)o.Do.do.o.o.o.o. o.o.o.#:sC+s#nCncnn{,n{,nn@PsA{,a{,Ps@Ps`PsPsPsPsPsPs`PsPsPsPs{,Ps{,Ps{, Ps!{,A{,a{,{,Ps{, PsPs na {, {, {, #sD {, ;&s ;&s {,# {,A {,C {,a {,c {,d {, {, {, {, {, {, {, {, {, {,! {,# {,A {,C {,` {,a {,c {, {, {, {, {, {, {, {, {, {,{,{,!{,A{,a{,Ps Ps@Ps`Ps{,@n`PsPs{,Ps{,Psa{,{,{,{,{,{,!{,A{,{,{,{,{,{,{,{,!{,@{,`{,{,{,{,{,{,@Ps`{{,`Ps{{,Ps{{,Ps{{,Ps{{,Ps Ps@Psnnnnna{,{,{, {, {,@{,PsPsA!{,a!{,!{,!{,!{,!{,!{,!{,"{, "{,@"{,`"{,"{,"{,"{,"{,#{, #{,@#{,`#{,#{,#{,'Ps'Ps(Ps (Ps@(Ps`(Ps(Ps(Ps(Ps(Ps)Ps )Ps!){,@*Ps+{,.{,0Ps0Ps0{,0Ps1{,1Ps1{,6{, 6{,@6{,`6{,6{,6{,6{,6{,6Ps7{,7Ps7Ps8{, 8{,8Ps 9Ps<{, <{,@<{,`<{,<{,<{,={,!?{,A?{,B{,B{,B{,B{,C{,!C{,AC{,aC{,C{,C{,C{,C{,D{,!D{,AD{,aD{,D{,D{,D{,D{,E{,!E{,AE{,aE{,E{,E{,E{,`Z{,`]{,f{,g{, g{,@g{,$k{,k{,~{,{,@{,{,{,{, {,{,{,{,{, {,@{,`{,{,{,{,{,{, {,@{,`{,{,{,{,{,{, {,@{,`{,{,{,{,{,{,{,{,{,{,@{,`{,{,{,{, {,`{,{,{,{,{, {,`{,{,@{,`{,{,{,{,{, {,䪻{,{,dGSdj#'-Mb Xr,5:>Hr 7AKl &-HX`+1`~'/INRY`gq|, 7 D [ p v A!M!Z!j!t!!!!"+"""""#1#U#n#u####### $$$ $&$/$8$>$M$X$_$h${$$$$$$$$$ %"%(%;%B%L%Q%^%d%v%}%%%%%%%&&Y&j&|&&&&&&'"'*'A'V'_'e'p'''''''''(+(I(W(](c(((((((((( ))$)4)>)I)O)U)_)i)s)))))))))**!*,*4*:*@*F*U*[*b*h**********+ ++(+-+2+y++,,%,-,9,E,N, ) #45ANO R"S#T$V&z'()*+-./0137:;=>?AILMQRUWX\]_bijm 7mc"m'mv+mz0mz-5m4:mrE>mTCmCm[LmE-UmfB>mҎZmcm[Lm"lmbrmYxm=nm/mHrm,mmZ:m:m?:mlmjmv+mX>:mimtmum'mZ:m:m8:mrE:mKmFdm$3mmWm,=:mamF:mBam.:m`mb:mXmgmemHfmgm gmem6fmgmgmfmemfm1mZ:m:m[1:me:mZ:m:m41:mZe:m]'mu;:m:mEMmm/mqmm Jmb,mv+mz0mtmmAmm3mXm);mNomm_m1mmom mm mGmԥm5mWmmÑmmm%mPm,mkmmmmdmKm:mm'mWmm-mmlmc5mcUmcm-m=0+m-mmnm6:m6:m"mmUmncn!mcncmcnӡ:m[:m%:mIn=0+m nmc/nc5nlI>mc;n?:mǂm{WAn=WAn5:m4:mVȂmXƂmQ4:m?:m=:m^2>m2>m7>m@>mά>m >m>m~>m>mT>mHZ>m|d>m[:m䄂mm'mZ:m:m8:mrE:mKmFdm$3mmWm,=:mamF:mBam.:m`mb:m'mZ:m:m8:mrE:mKmFdm$3mmWm,=:mamF:mBam.:m`mb:m3gmemfmfmyfmfmEgmgmgm&fmk?m@oAqBsCuDwEyF{G}HIRSTUVWXZY\[]^_`abdcfeghjiw)*,-.;=>?CDEFGHIJKLMNOPQRSTUWcdefghk   !#%%''))++--,-./21F3M5W7X9Y;c=h?iAjCkElGtIuKvMwOQSUWY[]_acegikmoqsu w y { }  !"#$%&'()*123456789:;<=EFGHIJKLMONQPRSTUVWYX[Z\]^_lw~   b b b b b b b i i i i i i i j j j j j j j m m m m m m m ,<EMT\cks "Bl2LUir ,MVem'AJhrz 2=H]fq| "TgQbrz s  ' . 6  9 '/NU]fo $8@H[e38.7 )ox=Get7IPW?HgH%e,dS,G\,S,S,S,cS,sbS,IS,9S,|vOӌ|S 2143538797>=HGJLMNOTUVW\#`+a+b+dcefghijklmUnZo[p#rQrm#cwwweeWWGG&(.5eGe(BSSSSS77>Eg/!8!G"""#S###$Q$5%5%g5%W;')O*bb*s++e?,$b__10b__10CS$<>9__CachedAnonymousMethodDelegate10<>7__wrap10b__20CS$<>9__CachedAnonymousMethodDelegate20CS$<>9__CachedAnonymousMethodDelegate30b__50<>c__DisplayClass60b__0b__0b__0b__0b__0<.ctor>b__0<.cctor>b__0b__0b__0b__0b__0b__0p0constraint0$$method0x6000489-1CS$<>9__CachedAnonymousMethodDelegate11<>7__wrap11<>c__DisplayClass11b__21CS$<>9__CachedAnonymousMethodDelegate21CS$<>9__CachedAnonymousMethodDelegate31b__51T1EdmxNamespaceUriV1MementoV1FunctionDetailsReaderV1get_UnableToGenerateForeignKeyPropertiesForV1get_EdmVersion1_1b__1b__1<.cctor>b__1Func`1ISchemaElementLookUpTable`1Nullable`1IEnumerable`1IOrderedEnumerable`1Stack`1ICollection`1ReadOnlyMetadataCollection`1EnumerableRowCollection`1ReadOnlyCollection`1IComparer`1IEqualityComparer`1IEnumerator`1HashSet`1IList`1get_Template_GeneratedCodeCommentLine1CS$<>9__CachedAnonymousMethodDelegate1get_Item1Version1p1str1<>c__DisplayClass1constraint1b__12CS$<>9__CachedAnonymousMethodDelegate12b__22CS$<>9__CachedAnonymousMethodDelegate22CS$<>9__CachedAnonymousMethodDelegate32Int32CS$<>9__CachedAnonymousMethodDelegate52T2VBTemplateCodeGenResourceV2CSharpTemplateCodeGenResourceV2_vbCodeGeneratorTypeV2_csharpCodeGeneratorTypeV2EdmxNamespaceUriV2CreateVBCodeGeneratorV2CreateCSharpCodeGeneratorV2b__2b__2b__2<.cctor>b__2b__2Func`2Tuple`2Memoizer`2KeyValuePair`2BidirectionalDictionary`2get_Template_GeneratedCodeCommentLine2CS$<>9__CachedAnonymousMethodDelegate2get_Item2Version2p2str2<>c__DisplayClass2b__13CS$<>9__CachedAnonymousMethodDelegate13b__23CS$<>9__CachedAnonymousMethodDelegate23CS$<>9__CachedAnonymousMethodDelegate33b__43CS$<>9__CachedAnonymousMethodDelegate53VBTemplateCodeGenResourceV3CSharpTemplateCodeGenResourceV3_vbCodeGeneratorTypeV3_csharpCodeGeneratorTypeV3EdmxNamespaceUriV3MementoV3FunctionDetailsReaderV3CreateVBCodeGeneratorV3CreateCSharpCodeGeneratorV3b__3<.cctor>b__3b__3Func`3get_Template_GeneratedCodeCommentLine3CS$<>9__CachedAnonymousMethodDelegate3StoreSchemaMappingVersion3StoreSchemaDefinitionVersion3ConceptualSchemaDefinitionVersion3p3b__14b__14b__24b__44CS$<>9__CachedAnonymousMethodDelegate54Int64b__4b__4b__4b__4CS$<>9__CachedAnonymousMethodDelegate4p4<>c__DisplayClass4b__15CS$<>9__CachedAnonymousMethodDelegate15b__25b__45CS$<>9__CachedAnonymousMethodDelegate55b__5b__5b__5b__5Action`5CS$<>9__CachedAnonymousMethodDelegate5p5<>c__DisplayClass5b__16CS$<>9__CachedAnonymousMethodDelegate16b__26b__46CS$<>9__CachedAnonymousMethodDelegate56__StaticArrayInitTypeSize=6b__6b__6d__6CS$<>9__CachedAnonymousMethodDelegate6<.ctor>b__17b__17CS$<>9__CachedAnonymousMethodDelegate27b__47CS$<>9__CachedAnonymousMethodDelegate575__7b__7b__7b__7CS$<>9__CachedAnonymousMethodDelegate7CS$<>9__CachedAnonymousMethodDelegate18CS$<>9__CachedAnonymousMethodDelegate28b__48CS$<>9__CachedAnonymousMethodDelegate58get_UTF8b__8b__8CS$<>9__CachedAnonymousMethodDelegate8<>7__wrap8b__19d__19CS$<>9__CachedAnonymousMethodDelegate19CS$<>9__CachedAnonymousMethodDelegate29b__49CS$<>9__CachedAnonymousMethodDelegate59d__9CS$<>9__CachedAnonymousMethodDelegate9<>m__Finally9FK_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__5__1ab__1aCS$<>9__CachedAnonymousMethodDelegate1aCS$<>9__CachedAnonymousMethodDelegate2ab__4aCS$<>9__CachedAnonymousMethodDelegate5a5__aCS$<>9__CachedAnonymousMethodDelegateaGenerateCodeFor1_1Schemaget_FKSchemaset_FKSchema_columnFKSchemaget_PKSchemaset_PKSchema_columnPKSchemaget_Schemaset_Schemaget_Template_UnsupportedSchemaCheckValidSchemaIsValidSchema_sourceSchemaWriteStoreSchemaNullAdditionalSchemaInternalWriteModelSchemasourceEdmSchema_columnSchema_schemaSystem.DataDoGenerateStoreMetadataInternalGenerateMetadata5__1bb__1bCS$<>9__CachedAnonymousMethodDelegate1bCS$<>9__CachedAnonymousMethodDelegate2bb__4bCS$<>9__CachedAnonymousMethodDelegate5bTemplate_GenCommentAddToMethodVbb__bSystem.WebCS$<>9__CachedAnonymousMethodDelegatebmscorlibrbTemplateCodeGenerators.VBCodeGenTemplateV5.0.vbTemplateCodeGenerators.VBCodeGenTemplate.vbb__1cb__1c<>7__wrap1cCS$<>9__CachedAnonymousMethodDelegate2cb__4cCS$<>9__CachedAnonymousMethodDelegate5cb__cb__cCS$<>9__CachedAnonymousMethodDelegatecget_IsNiladicVBMarkPropertyGetAsPublicCSMarkPropertyGetAsPublicVBMarkPropertySetAsPublicCSMarkPropertySetAsPublicCodeGenerationValueAccessibilityPublicSystem.Collections.GenericComputeFromStringGenericgenericMicrosoft.VisualBasicCSMarkClassAsStaticorderByFuncb__1db__1d<>m__Finally1dCS$<>9__CachedAnonymousMethodDelegate2db__4dCS$<>9__CachedAnonymousMethodDelegate5dget_CurrentManagedThreadId<>l__initialThreadIdget_RelationshipIdset_RelationshipId_columnRelationshipIdPrivateMemberPrefixIdb__db__dd__dReadLoadEdmFunctionPayloadAddreplacedget_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_CSClassKeyWordIndexOfKeywordkeywordGetSchemaXsd<>c__DisplayClassdb__1eb__1e<>7__wrap1eCS$<>9__CachedAnonymousMethodDelegate2eb__4eCS$<>9__CachedAnonymousMethodDelegate5e5__eb__eReplaceget_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_dateTimeSystem.Runtimeget_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.DisposeTryParse<>c__DisplayClasseFunctionOrderByClauseorderByClauseSaveAssociationForCollapsedAssociationCandidateParseAndValidateCreateMulticastDelegateget_IsIsAggregateget_Template_CurrentlyRunningTemplateLoadMethodSessionState<>1__stateEvaluateToSeparatedStringPrivateVBMarkPropertyGetAsPrivateCSMarkPropertyGetAsPrivateVBMarkPropertySetAsPrivateCSMarkPropertySetAsPrivateget_IsPrivateCodeGenerationValueAccessibilityPrivateRELATIONSHIP_IsCascadeDeleteget_RelationshipIsCascadeDeleteset_RelationshipIsCascadeDelete_columnRelationshipIsCascadeDeletenamespaceToWriteMetadataArtifactLoaderCompositeget_IsCompositeCompilerGeneratedAttributeAssemblyTargetedPatchBandAttribute_GeneratedCodeAttributeEmitGeneratedCodeAttributeDebuggerNonUserCodeAttributeAttributeUsageAttributeNeutralResourcesLanguageAttributeDebuggableAttributeget_IsComposableAttributeAddBrowsableAttributeComVisibleAttributeAssemblyKeyFileAttributeEmitSimpleAttributeAssemblyTitleAttributeget_StoreFunctionNameAttributeEmitSchemaTypeAttributeGetCodeAccessibilityTypeAttributeXmlIgnoreAttributeSoapIgnoreAttributeget_AggregateAttributeDebuggerStepThroughAttributeXmlAttributeget_BuiltInAttributeDebuggerHiddenAttributeAssemblyDelaySignAttributeExtensionAttributeAssemblyFileVersionAttributeAssemblyInformationalVersionAttributeSatelliteContractVersionAttributeget_NiladicFunctionAttributeEDesignResDescriptionAttributeAssemblyDescriptionAttributeBuildProviderAppliesToAttributeAddDataMemberAttributeGetAccessibilityCsdlStringFromMemberAttributeDefaultMemberAttributeGetCodeAccessibilityMemberAttributeAssemblyDefaultAliasAttributeget_ParameterTypeSemanticsAttributeSecurityRulesAttributeFlagsAttributeCompilationRelaxationsAttributeAllowPartiallyTrustedCallersAttributeAssemblyProductAttributeAssemblyCopyrightAttributeCLSCompliantAttributeSecurityTransparentAttributeTargetedPatchingOptOutAttributeget_CommandTextAttributeDebuggerDisplayAttributeParamArrayAttributeAssemblySignatureKeyAttributeAssemblyCompanyAttributeEDesignResCategoryAttributeRuntimeCompatibilityAttributeattributeReadByteWriteByteget_Valueset_ValueAddValueGetSecondValuesecondValueBaseValuemetadataArtifactProcessingValueStonglyTypedAccessToNullValuenullValueGetEnumValueget_MinValueset_DescriptionValueget_HasValueTryGetValueSetValueIsUnboundedFacetValueget_DefaultValueGetCodeExpressionFromDateTimeDefaultValueGetCodeExpressionFromTimeSpanDefaultValueGetDefaultValueGetCodeExpressionFromDateTimeOffsetDefaultValueGetFirstValuefirstValueget_MaxValueGetTypeAccessibilityValueGetAccessibilityValuevalueToAppRelativeIsUninflectiveget_IsLanguageCaseSensitive_isLanguageCaseSensitivecaseSensitiveRemoveInitializeSuppressFinalizeInternalPluralizeCapitalizeInternalSingularizeEntityizeb__1fb__1f<>m__Finally1fCS$<>9__CachedAnonymousMethodDelegate2fb__4fCS$<>9__CachedAnonymousMethodDelegate5fLastIndexOfb__fb__fget_FieldRefget_ComplexPropertyInitializedFieldRef_complexPropertyInitializedFieldRef_fieldRefget_ThisRef_thisRefCreateEdmStructuralObjectRefCS$<>8__localsfget_IsTvf<>m__FinallyftagSystem.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_targetFilePathget_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_property{0E8BEFC4-B104-4956-8464-87DA790EC9A6}GEntityStoreGeneratorSchemaNotLoadedGEntityModelGeneratorSchemaNotLoaded;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_ReturnedNullOnProviderMethodedmNamespaceobjectNamespaceGetterAccessSetterAccessMethodAccessTypeAccessInternalPrivateProtected Public1EdmRelationshipAttribute1RelationshipMultiplicity-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/EdmComplexTypeAttribute.aSystem.Runtime.Serialization.DataMemberAttribute?System.Data.Objects.DataClasses !EdmCodeGenFixup- .tmpCFullName;<param name="{0}">{1}</param> LeadingBlanksLongDescriptionsummary <{0}> </{0}>7^(?<LeadingBlanks>\s{1,})\S Create9VerifyComplexObjectIsNotNull!OnContextCreated name=!connectionString!EntityConnectionconnectionObjectQueryCreateQuery[] AddToAddObjectExecuteFunctionParameterHasValue<KeyProperties>!</KeyProperties>public abstractpartial'Public MustOverridePartial Private End Suboverride sealedOverridesNotOverridablesetinternalSet FriendgetprivateGetprotected public static classstatic  {}// class @ ClassEnd Class!MustOverride SubFunctionSubPropertyEnd PropertyEnd SubEnd FunctionEnd GetEnd Set eSystem.Data.Objects.DataClasses.EdmSchemaAttributeReference5InitializeRelatedReference'RelationshipManager Value7InitializeRelatedCollectionEntityReference!EntityCollection'GetRelatedReference)GetRelatedCollection valueGetValidValue-ReportPropertyChanging+ReportPropertyChangedSetValidValueCollectionKindOnChangingChangedD'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_piInitializedlanguageOptionsourceEdmSchema target)additionalEdmSchemas'additionalEdmSchema/sourceEdmSchemaFilePath9additionalEdmSchemaFilePathstargetPath .csdl'sourceEdmSchemaPath~//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 .mslcsEdm <!---->FunctionImportCollection()ReturnTypeAggregateBuiltInNiladicFunctionIsComposable-ParameterTypeSemantics#StoreFunctionNameCommandText SchemaCollectionType Type ModeComplexTypeBaseTypeAssociationRowType+ReferentialConstraintPrincipalDependent RolePropertyRefEndMultiplicityOnDelete Action*1 0..1EntityTypeAbstract trueKey%NavigationPropertyRelationshipFromRole ToRolehttp://schemas.microsoft.com/ado/2009/02/edm/annotation:StoreGeneratedPattern+StoreGeneratedPatternohttp://schemas.microsoft.com/ado/2009/02/edm/annotationMaxLengthMaxDefaultValue'ClientAutoGeneratedConcurrencyModeCollation=GetAssociatedFacetDescriptionsNamespace Alias Self+UseStrongSpatialTypes falseProvider+ProviderManifestToken xmlnsEntityContainerhttp://schemas.microsoft.com/ado/2009/02/edm/annotation:LazyLoadingEnabled%LazyLoadingEnabledAssociationSetEntitySetDefiningQuery TableCollection({0})factoryGetService, {0}& &amp;< &lt;> &gt;' &apos;" &quot;lookupsstoreContainermodelContainer writer-EntityContainerMapping-StorageEntityContainer%CdmEntityContainer+FunctionImportMappingFunctionName%FunctionImportNameResultMapping%ComplexTypeMappingTypeName+AssociationSetMappingStoreEntitySetConditionColumnName IsNullEndProperty!EntitySetMapping#EntityTypeMappingMappingFragmentScalarPropertyMapping SpaceC-S 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)storeEntityContainer9targetEntityFrameworkVersionoutputFileNameannotation_ResultApplication Target ModelContext types?Edm_EntityMappingGeneratedViewscSystem.Data.Mapping.EntityViewGenerationAttribute-ViewsForBaseEntitySetsOSystem.Data.Mapping.EntityViewContainer-EdmEntityContainerName1StoreEntityContainerName-HashOverMappingClosure-HashOverAllExtentViewsViewCountGetViewAt<Summary></Summary>#mappingCollectionoutputPathoutputWriter indexGetViewToStringviewString AppendedmCollectionstoreCollectionreadersSchemaNameTableNameOrdinal!RelationshipNameRelationshipIdAND( NOT ( WHERECatalogName% 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 ; 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 'RelationshipDetailsPkCatalogPkSchemaPkTablePkColumnFkCatalogFkSchemaFkTableFkColumnIsCascadeDeleteTableDetailsDataTypeMaximumLengthPrecision#DateTimePrecision ScaleIsIdentity#IsServerGeneratedIsPrimaryKey-entityFrameworkVersiondataSpace Edmx+providerInvariantNamefiltersContainer storehttp://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator Tables Views nullNullablecultureen 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 lynxespharynxpharynxesphalanxphalanxes word eeth eeseeetoaescesx deafvessman louse mouse tooth foot zooncissisxis trixeauieuchshssalfelfolfeafarf nife life wifeayeyiyoyuyyiesaoeoiooouooan ouse ooth ooseootoonffemen lice mice teeth geese feetzoa ches shes sses trices eaux ieux alves elves olves eaves arves nives lives wivesayseysiysoysuysaoseosiosoosuossesxesoes[^a-zA-Z\s]esesingular plural{0}({1})_TemplateCodeGenerators.CSharpCodeGenTemplate.csYTemplateCodeGenerators.CSharpCodeGenTemplategTemplateCodeGenerators.CSharpCodeGenTemplateV5.0.cs_TemplateCodeGenerators.CSharpCodeGenTemplateV50WTemplateCodeGenerators.VBCodeGenTemplate.vbQTemplateCodeGenerators.VBCodeGenTemplate_TemplateCodeGenerators.VBCodeGenTemplateV5.0.vbWTemplateCodeGenerators.VBCodeGenTemplateV501/d:PREPROCESSED_TEMPLATETransformTextSourceCsdlPath%ReferenceCsdlPaths Errors/EdmToObjectNamespaceMap3System.Data.Entity.Design... 3%MʹU'Mh  I5!  1 9  - 99%-%-!9!-Y9Y5` i u             5! %51 -%9%  1  51 1% 5% 1% 5!!-%- -5%    yy = ! 5Q5U5]5a  y y =  ye  %y  y ! e 5} } 0AA9A}9} 5 )1} ]  A   } I  99 e 09 9 9 9       A  9 ] M    9 -9 - ]Y ]  ]]]      9   ---9  9    -9  e}A    i i    i5DD5     5  A       AA - - 1  }  D-D9D  -9 E- E 5 5    Y   -- --- - =} e}uu }q 5 } D D D      5 }--  }      -- M  Q Q       =)5-A9 9  ! !     !          U  -    ! Q  a         ) ]] ] M M        Q  M    M ] ]    AE   -%A! -%5!-M-M Qy yy--y9y5P ! %  - M 5MU Y =P ] E AA M M M qu ]e i i i i i m U q y u  u - yM QM Q  M-9  55 % A % 0A}A   5l}5  }5t-M9Mt-----9-  tTH X5!5H H  H H -5-H9H -  # -   uu}- y   -%  5   -  } M  9    \  \\  \ 0 yAE9E I5! I5! -   % } -5 ! - % ]q  m  - ] ] ] ] ]]  =  U] M a  A-}   9 )5 AEI0M Q } 5 5 Y]Y]0     e q m } M5Y  Q M QQ    5 -9    a  ] ]   M ! ]     ]M ]M QMMMMMM ] M ] ] 5]]    ]]   = ]!   % u       ! !   y1   `            i        ] ) q          % )5!151%1=9% -%1 5!1511=!9 -,  1%5%!% !! Quuuy! !%y!9!- 4}14}99}}  }A}9 9 99 999 5!]!!'}-E99} 9 A9  99   @N DiiD=9!999999 1 (5 -DDD5D=!9 A9D9DD<3-=q9     ) 59? D DDDDDDD9D9 9 9 9 - 559  5  9 $ 9   5))!  y! !))  !99 yy!   -!5!>]U-9 9    . )  ] %]9% -A Dpy=I9y y yyYa-M Y]]]P]P]A M M iii q}  u}y5P -PM1Q?TQM=9!?%%%!555=%%% A !9!9\5Xh\5l\Fh5!=5!5eqE5tt9MBt5!!99   p\\ tttt Q9\5H5H\9MK\P5HH9P H\w!5HE \\\\9Huuuuuuuu E\5H-!%5%&59 y5!!# y5!5%!9%5!%y5!! }%5!!( 5!p)=!  !!! ] ]yQm  5]5] UU}MU9}U U5UU5U UU,1yQ 5 Y9 9  5  U !!Ae M 9M5M)M59M?M   9 9 9 9 ---M)M5U55Q5QM 3 }M599M! ]QQQQ ]ME]9 9 5  99 & U Y59Y]]] ]CM%5Q5!5Q5QQ9  M!!5 E!5E5  } --  5   ]MMMMM8  ]]5]]] ]] yy=19= ME!] 51=]!9! %9%E+%   111===1     !\ E E9E iF  5    5    K55555555555555R555555555555555]]] =| ||z\V4?_ :Context ModelApplicationPkCatalogPkSchemaPkTablePkColumnFkCatalogFkSchemaFkTableFkColumnOrdinal RelationshipNameRelationshipIdIsCascadeDeleteContainerXTemplateCodeGenerators.CSharpCodeGenTemplatePTemplateCodeGenerators.VBCodeGenTemplate^TemplateCodeGenerators.CSharpCodeGenTemplateV50VTemplateCodeGenerators.VBCodeGenTemplateV50^TemplateCodeGenerators.CSharpCodeGenTemplate.csfTemplateCodeGenerators.CSharpCodeGenTemplateV5.0.csVTemplateCodeGenerators.VBCodeGenTemplate.vb^TemplateCodeGenerators.VBCodeGenTemplateV5.0.vbInternalProtected PublicPrivate class    Value,InlineObjectCollection DetachFromParent0IEntityWithRelationshipsObjectContextEntitySetObjectResultTSystem.Data.Metadata.Edm.MetadataWorkspace&System.Data.Objects>System.Data.Objects.DataClasses0System.Data.Metadata.Edm0System.Data.EntityClientSetValidValue,ReportPropertyChanging*ReportPropertyChangedGetValidValue8VerifyComplexObjectIsNotNull, EdmxZhttp://schemas.microsoft.com/ado/2007/06/edmxZhttp://schemas.microsoft.com/ado/2008/10/edmxZhttp://schemas.microsoft.com/ado/2009/11/edmxpqrstuvwxyz{|}~CatalogNameSchemaNameTableNameColumnNameIsNullableDataTypeMaximumLengthPrecision"DateTimePrecision ScaleIsIdentity"IsServerGeneratedIsPrimaryKeyhttp://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGeneratornhttp://schemas.microsoft.com/ado/2009/02/edm/annotationType SchemaName Tables Views*StoreGeneratedPattern$LazyLoadingEnabledannotationFEntityStoreGeneratorSchemaNotLoadedFEntityModelGeneratorSchemaNotLoaded: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_ReturnedNullOnProviderMethod  IM5Q5UY5]5a}8y  @              5D55   LT !I y yy-M-M M MaYipyd5} t--  ] U5!  5 ] ]MMMM 5])   !    D@DP5-P       }5  \  \ \  \X`d5|] H% !TI5!!                  !%) !%)-% ! !- 1515! !9= !@= !@= 5!    IM I 5Q 5U YM Y 5] 5a im q qeuyy 8yy 85}y }             -}  }  }}     I } @y  D       5           ! !y - (  ( -D( ( ( ( ( ( (  (D ( ( ( ( (  ( (  ( (  TL T L ! !) !)y ! !yy !))!!  !    !  !  !y  ) !    )   !- -%) %) -% -!AEy-%!-%y!-%!-%y!-%!-%y! yy! h-P -M-P Iy I* -M-M-MUT-PYIT5P Y]P Y]y-M-MMM e l lhI-Py I-P \ h  i Mm p yy}yy yy}%yy !-P !-PyI Iy Qy ! -! T T X T T\5l T T5t Tt5tt 5t T T5t5!- T-MTH X5!X TH X5!" TH\5! TH5\  T T t - -    !-y !y !%)y !%)-%y !-y %y !y !%y !y-y! !-% !@ ]  == M    III   5U 5] 5a      }    }a 5U a 5U  UU  5!  -}}     @ @= @= @= @ @ -Y M} M}  II       MM     }       ] %        )) ) )    5  Y    Y Y Y Y  I      M  %  M M  5U 5Q !5Q !0 M      M MM E E  MM  MM M] M]M M M M MM MM MM MM5]!%))] }- ] ) )qe=1151=9== ==99AEE=Iy !5 ]5 ]5= -! -%} y}   Quuuuyy  8 <  D \X y -! \ \  \ - \ \ \ \ E }! } ! X \\ X     -- - py|] }  9Y  9 9% H 9! ! !( (((((I((M(5Q(5U(Y(5](5a(( (5(((((T(L(y(Q(I((i(py(((((((((((((( 5(((( (D(-!(X (  ( ((-( ]((%(!$TSkipVerificationInFullTrustTWrapNonExceptionThrows"System.Data.Entity.Design.dllMicrosoft CorporationMicrosoft® .NET Framework4/© Microsoft Corporation. All rights reserved.4.0.30319.33440 4.0.0.0 en-US)$f:\dd\tools\devdiv\EcmaPublicKey.snkH@002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a235e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f302d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd911f0571aaf3d54da12b11ddec375b3a5a866e1ee186f807668209f3b11236ace5e21f117803a3143abb126dd035d7d2f876b6938aaf2ee3414d5420d753621400db44a49c486ce134300a2106adb6bdb433590fef8ad5c43cba82290dc49530effd86523d9483c00f458af46890036b0e2c61d077d7fbac467a506eba29e467a87198b053c749aa2a4d2840c784e6d1.0.23-139944453TOPerformance critical to inline this type of method across NGen image boundaries 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 ,C-A@a˴)9yۦwbEg86PկRl9vCtƪG,t7QS"[W+%S7'D0՘57ܳg sVaAGn嶽`vhxdP^z\%M%?*@y]e;#^bﰜV \j=S3En*fVm+59iٰMBR6$RSDS>4;Fe)System.Data.Entity.Design.pdb%/% !%_CorDllMainmscoree.dll% `="' 8Ph@QH4IBC PROFILE_DATA(б 3%MʹU'Mh ME O<4 I   # && +< ,D 0R o2!3"63 +%H4I?APY[_fgtv  KLz!-:GPM?n~   N| O p -P 24CLN\hjyRJSv&aj TwhU3h V.f".WWJgw  Xk)+@IKYjYZ Vh7 ][  "'57>'F'H`e'j`s'u'y'''  3   ]8'' ! !46^v',>Qct7_* `/+( a  b!  c,   * (d WFe.@vfNP_hjxgM"h^fF#iu .0pHp`hjmstjz%/ 8FI MZxl m o!pNKqTVysq tw:(*8x8:jsu yX$(7Hz2{7|35 P k tv}: ~"j'L ($&02<>JML R+58E%?* **&".+-*;=&2<$ $$"H+$-$;$ Q('O =( {GXi %(JNtB#<mf $8 09FOQ_lqJ )-68FHQ +7@BP- $=?Uluw.%'=FHVdlK, ^`    C [ nZ T#?gi@1 .>?@gi .;L((F7xH.!79G >,T#<DNepP" $"3"N"  ;.57QSf L#K 1 * O-9MMbs%# B$ B$ J$! .?OQXt~w "5JRadjkntuACUqs ;COY{  h*;L]   h*;L]   h*;L] H H H[T   $1@ J <9 NE  ( <C  H  >< ><>HHHGKIrWKY'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:<hqsH*5-IE+#{AGnqwx ' # 2Ec 9 . !'(*-34 p Ap p p ( &O 3D 3 `$ 3$A$^$  H   0 < +K          ; >T< >< >< >< >< >< ><: % aX%8CVS *8@BEKLR3DQ!i   #+@CK` U %'=QS  F  .6D y #0<IQ^jw   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                b QO4  , (8* _ 4H] ) %8' '' ##   nl I " (( u  &*&6\&`@f      7 5#  Bm8  H o^_ R> 6de f =h  PQ@SI DSуCӃԃ SE$_ "  "  m #U "W" ʚ                     ƀ ր    Ҁ"Q͜"   뀀Ҝ 쀀՜         J       ƝΝ       倀蝀  Mπ Zـn[o#S" A C"\!C     !!!"CDEFGH236####$$$$$#$$#$###$#########%"x% & % % % ' ' ' % & ' % #0###$#$#$########################((%ǃ0##$####$$$######$############### $ # ######)##$)$$ $!#"###$#%#&#'#%0$####܌% %Ё0#############################%0*+,,-./..**- + ..*+****.*.****+***+*m*-,-*- *H*,0,,-,**012222222Ɂ0345522225622221222222222222 2 2  2 2 2 02252222222222 22202222222222 22222 2 0 20222 2  2022222 2 2 2ꃀ02 2          ̂02222222  ق0222222125222w2122222222 222222552222266252222221p2o2~2q2z2{2|2}2t2s2x2y220202 2 2 2 2I2K2d2X2e2h2j2i2l2f2g2L2W2Z2b2a2[2_2^2]2` P2T2V2R2S2U2M2N22 2 05  20 2  2 2    2 202 c2Y216252612  2 56 0a  777c00- M&O߫hϕ,ε߸T-4 C_ -ʥ-.X۞TU\8ξ х3XXӻ(޻֪+ɸظ٭ϲ߲ڲ=߾ؿH{~y|z}ĀImȭDArׯԋȌհ_>g̳Ya߭ͮݮa҄!kfe_onnotttoopssqsrsqr³_giiiijjjj hjldlmmmblccbcdddOhihhhccdddbccdO__`````aaaJb޳´ԴȵڵҶԷ¸θȹйʻԻμ޼Ľֽʾо־ܾʿؿҀ܁Ƃă܃ڄԅȆކ҇Ĉ܈ΉŠ؊ȋ܋ƌڌč؍Ž֎ԏҐБΒʓޓȔĕԖėޗƘؙȚޚțܛԜ̝̞ڞ̟ģΣأ¤Τڤ¥ڥ̠֠ġ̡֡deeeZ99\ZZ7Ƭފ"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у ?P ?P  ?PP  ?P  ?P  ?P  ?P  ?P  ?P  ?P  ?P| ?\>?\? ?\>?\???\>??\???\>??\? ?\>?\???\>??\? ?\>?\? ?>\??\ ?>\??\??>\???\??>\???\ ?>\??\??>\???\ ?>\??\?\??\???\???\??\???\??\? ?\ ?\ ?\ ?\?>>>X>/+?T?H?X?? ?H ?H ?HH ?H ?H ?H ?H ?H ?H ?\>?\?<?\??\? ?\ ?>\??\<??\??\ ?\ ?\ <?\ ?\>?\? ? \>? \?  ?t  ?t  ?t  ?t  ?t  ?tt ?t  ?t  ?t??D??D???D???D??D???D??D  ?DD??D<??D??D  ?D  ?D? ?D  ?D  ?D  ?D  ?D  ?D  ?D  ?D  ? D  ?D  ?D <?D ?D  ?(D??D  ?,D  ?D  ?llH ` `>>  ?l  ?l  ?l  ?l  ?l ??>\ ! ?Hl ! ?P ! ?P> ? x ?!|  ?pP ?Pq ?\>r ?\s ?\t ?>\r ?\u ?\v ?\w ?xH ?yH ?\>z ?\>{ ?\| ?>\z ?>\{ ?\>} ?\>~ ?>\} ?>\~ ?\ ?\ ?\ ?\ ?\> ?>\ ?\> ?\> ?\> ? \> ? \> ? \> ? \> ? \> ?>\ ?>\ ? \> ? \> ?\> ?\> ?\ ? ?D ?$D ?0  h1>  h1  h1 ?4 `>> `>> `>> `>> `>> ?8 ??8 ?D ?P o5PAD44VS_VERSION_INFOovov?DVarFileInfo$TranslationStringFileInfop000004b0TCommentsSystem.Data.Entity.Design.dllLCompanyNameMicrosoft CorporationdFileDescriptionSystem.Data.Entity.Design.dll@FileVersion4.0.30319.33440\InternalNameSystem.Data.Entity.Design.dll/LegalCopyright Microsoft Corporation. All rights reserved.dOriginalFilenameSystem.Data.Entity.Design.dllTProductNameMicrosoft .NET FrameworkDProductVersion4.0.30319.334408Assembly Version4.0.0.0PADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADD  D5>0> *H >s0>o1 0 +0L +7>0<0 +70 0!0 +_rHiVg^6۹j7φKJ%ȍagS/L,cʠRXsB4꓾L} O/]Ef_$FU҃rB":P 00U_KB 8f6VtYIf+0U#0#4RFp @v+50TUM0K0IGEChttp://crl.microsoft.com/pki/crl/products/MicrosoftTimeStampPCA.crl0X+L0J0H+0http://www.microsoft.com/pki/certs/MicCodSigPCA_08-31-2010.crt0  *H 1n*W3՝:DM^j[yvh M9 ]$:|ۭγl9,E}$T&0 Gf],{tOik$햠sjKb|HMDN;] U?@18u(^Fmzy@Eծ]>ufc`՚$04cBgJK:ﶕ:8%f00 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ชKWB40f +7 1X0V<:System.Data.Entity.Design.dllhttp://microsoft.com0  *H m08e#82D~&/UqN=Fiv'5%nu$46=dG'm6W~q$^LyoĻ(ml,f} {Veû{ovgT33J:aUVeZXyXcb WgeFs,|$%; F|ӛ&4 w?[[̸uiM-Tk/lVm{l TCX]BH@s9y[!Fvͫr9q'ٟCT!cnHzܝP䶃"G*D>8.0+Asp)&9L/*Z6>)P@2'c:Ӝr5Ex(kdtE@o\-,0(0U%0+ +7L0Ua??P.Cqc\BF0U#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  Ck]dRoP(tqO'CMf`a;W~/=E3]v`yN^|#qzA"L̊WC֮3=f;vdbWC;GujHN2 Lf÷>LH92 x[+07wo\CR,Gasrc3aI_,5O}k>YڞְHa뀱F5i?r~#Cܶ zե:ւMxK[ 4RNq㑹sy 64,I`0 &d]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 zP1000~1 0 UUS10U Washington10URedmond10U Microsoft Corporation1(0&UMicrosoft Code Signing PCA 20113y %XE0  `He0 *H  10 *H  1  +70 +7 10  +70/ *H  1" qX^ӴGq*tBu3pτ rI0f +7 1X0V<:System.Data.Entity.Design.dllhttp://microsoft.com0  *H 1Wl[ۋbVX9TL7A'>O%#Uö(gsj5B,~dvEl~/x\-ϜBуfAYBvMJ%@ ϳpoeK'T *.?3*ADriq{@jP0^Ȧ SŮvo8R; Kt)>Huh\>I8 &b%F|0Ġg⛁3Kڢ2<}PM'ۡI0E +71501 *H "010  `He0< *H  +'0# +Y 010  `He /[ByTֿٹtECQW20130807021548.22Z001 0 UUS10U Washington10URedmond10U Microsoft Corporation1 0 U MOPR1'0%U nCipher DSE ESN:BBEC-30CA-2DBE1%0#UMicrosoft Time-Stamp Service0q0Y a *0  *H  01 0 UUS10U Washington10URedmond10U Microsoft Corporation1200U)Microsoft Root Certificate Authority 20100 100701213655Z 250701214655Z0|1 0 UUS10U Washington10URedmond10U Microsoft Corporation1&0$UMicrosoft Time-Stamp PCA 20100"0  *H 0  w: iktTե |hK,_av>f+[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 jeg2}( F{ࢯ٠/i$a|c00U|͂CZ@ƫBۗ0U#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  E`_گ St:':)Z ]-"Y0SdT.#`LT{0A}ܤLÊ?+%!pf y xBDoToZV~<lh`a/#|Sʚ1G Ic*)ݺhCҟ|Q4:2mmaI'ܧtق&j51tm[ޝ'-|qtϸn@$%2aCe.v0^0㡁01 0 UUS10U Washington10URedmond10U Microsoft Corporation1 0 U MOPR1'0%U nCipher DSE ESN:BBEC-30CA-2DBE1%0#UMicrosoft Time-Stamp Service% 0 +7Y)9ls9C6j:Z001 0 UUS10U Washington10URedmond10U Microsoft Corporation1 0 U MOPR1'0%U nCipher NTS ESN:B027-C6F8-1D881+0)U"Microsoft Time Source Master Clock0  *H լ0"20130807002638Z20130808002638Z0t0: +Y 1,0*0 լ000 խd>06 +Y 1(0&0  +Y  0` 0 0  *H 5\i5&%zǿ6,'!/a44(UB&jzqM(.z%ni\5"VgLNi=iOѫu=Z5\wLFRGA;;{͘yd_OqzKCC Át.Y`_dug.:|梻w L{jHo:9BHcuZԤ%d)D>&.XNn! <oT1000|1 0 UUS10U Washington10URedmond10U Microsoft Corporation1&0$UMicrosoft Time-Stamp PCA 20103,)w;g,0  `He20 *H  1  *H  0/ *H  1" op@d0l,d9IIsac E#Zw^`htV?*ظ{5QPr !7ai^