Atribuindo da Classe para a Interface de Usuário via Reflection
Em mais um artigo da série Reflection na Prática: Uso na Classe de Conexão, desta vez abordo os métodos BindToUI e BindFromUI, mostrando como fazer a atribuição das propriedades de uma classe para os componentes da interface de usuário e vice-versa.
Trabalharemos mais neste método os componentes que recebem um único valor, tais como textboxes, checkboxes, dropdownlists, por aí.
Mas espera ae… o DropDownList recebe vários valores! Sim, mas não estou falando da lista em si, e sim do valor atualmente selecionado :P (e isto vale para os outros __list também!)
Vamos agora atribuir as propriedades da classe para a interface de usuário, ou seja, o método BindToUI da classe Conexão:
1: public void BindToUI(Page UI, Type type, ArrayList ExcludeFromBind)
2: {
3: Type t = this.GetType();
4: foreach (FieldInfo c in type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
5: {
6: if (ExcludeFromBind.Contains(c.Name))
7: {
8: continue;
9: }
10: if (c == null)
11: {
12: continue;
13: }
14: if (c.Name == null)
15: {
16: continue;
17: }
18:
19: //Retira o prefixo do nome do componente -> ele DEVE ter 3 letras, e o ID do controle deve ter mais que 3 letras
20: string PropertyPattern = (c.Name.Length < 3) ? "" : c.Name.Substring(3, c.Name.Length - 3);
21: PropertyPattern = PropertyPattern.Replace(t.Name, "");
22: if (PropertyPattern.Contains("_"))
23: {
24: PropertyPattern = PropertyPattern.Substring(0, PropertyPattern.IndexOf("_"));
25: }
26:
27: PropertyInfo pi = t.GetProperty(PropertyPattern);
28: if (pi != null)
29: {
30: if (pi.GetValue(this, null) == null)
31: {
32: continue;
33: }
34:
35: int IndexProp = -1;
36: HasIndexIdentifier(c.Name, out IndexProp);
37:
38: if (c.FieldType.FullName.Equals("System.Web.UI.WebControls.TextBox"))
39: {
40: int idx = 0;
41: string formatinfo = "";
42: if (ContainFormatInfo(pi.Name, out idx, out formatinfo))
43: {
44: if (!pi.PropertyType.IsArray)
45: {
46: (c.GetValue(UI) as TextBox).Text = String.Format(formatinfo, pi.GetValue(this, null));
47: }
48: else
49: {
50: object[] arrVal = (object[])pi.GetValue(this, null);
51: (c.GetValue(UI) as TextBox).Text = String.Format(formatinfo, arrVal[IndexProp]);
52: }
53: }
54: else
55: {
56: if (!pi.PropertyType.IsArray)
57: {
58: (c.GetValue(UI) as TextBox).Text = pi.GetValue(this, null).ToString();
59: }
60: else
61: {
62: object[] arrVal = (object[])pi.GetValue(this, null);
63: (c.GetValue(UI) as TextBox).Text = arrVal[IndexProp].ToString();
64: }
65: }
66: }
67: if (c.FieldType.FullName.Equals("System.Web.UI.WebControls.DropDownList"))
68: {
69: if (!pi.PropertyType.IsArray)
70: {
71: (c.GetValue(UI) as DropDownList).SelectedValue = pi.GetValue(this, null).ToString(); ;
72: }
73: else
74: {
75: object[] arrVal = (object[])pi.GetValue(this, null);
76: (c.GetValue(UI) as DropDownList).SelectedValue = arrVal[IndexProp].ToString();
77: }
78: }
79:
80:
81: if (c.FieldType.FullName.Equals("System.Web.UI.WebControls.RadioButton"))
82: {
83: if (pi.PropertyType.Name.Equals("System.Int16") || pi.PropertyType.Name.Equals("System.Int32") || pi.PropertyType.Name.Equals("System.Int64"))
84: {
85: if (!pi.PropertyType.IsArray)
86: {
87: (c.GetValue(UI) as RadioButton).Checked = ((int)pi.GetValue(this, null) > 0) ? true : false;
88: }
89: else
90: {
91: object[] arrVal = (object[])pi.GetValue(this, null);
92: (c.GetValue(UI) as RadioButton).Checked = ((int)arrVal[IndexProp] > 0) ? true : false;
93: }
94: }
95: if (pi.PropertyType.Name.Equals("System.Boolean"))
96: {
97: if (!pi.PropertyType.IsArray)
98: {
99: (c.GetValue(UI) as RadioButton).Checked = (bool)pi.GetValue(this, null);
100: }
101: else
102: {
103: object[] arrVal = (object[])pi.GetValue(this, null);
104: (c.GetValue(UI) as RadioButton).Checked = (bool)arrVal[IndexProp];
105: }
106: }
107: if (pi.PropertyType.Name.Equals("System.String"))
108: {
109: if (!pi.PropertyType.IsArray)
110: {
111: (c.GetValue(UI) as RadioButton).Checked = (pi.GetValue(this, null).ToString().ToUpper().Equals("SIM") || pi.GetValue(this, null).ToString().ToUpper().Equals("S"));
112: }
113: else
114: {
115: object[] arrVal = (object[])pi.GetValue(this, null);
116: (c.GetValue(UI) as RadioButton).Checked = ((arrVal[IndexProp].ToString().ToUpper().Equals("SIM") || arrVal[IndexProp].ToString().ToUpper().Equals("S")));
117: }
118: }
119: }
120: if (c.FieldType.FullName.Equals("System.Web.UI.WebControls.Label"))
121: {
122: string formatinfo = "";
123: int idx = 0;
124: if (ContainFormatInfo(pi.Name, out idx, out formatinfo))
125: {
126: if (!pi.PropertyType.IsArray)
127: {
128: (c.GetValue(UI) as Label).Text = String.Format(formatinfo, pi.GetValue(this, null));
129: }
130: else
131: {
132: object[] arrVal = (object[])pi.GetValue(this, null);
133: (c.GetValue(UI) as Label).Text = String.Format(formatinfo, arrVal[IndexProp]);
134: }
135: }
136: else
137: {
138: if (!pi.PropertyType.IsArray)
139: {
140: (c.GetValue(UI) as Label).Text = pi.GetValue(this, null).ToString();
141: }
142: else
143: {
144: object[] arrVal = (object[])pi.GetValue(this, null);
145: (c.GetValue(UI) as Label).Text = arrVal[IndexProp].ToString();
146: }
147: }
148: }
149: if (c.FieldType.FullName.Equals("System.Web.UI.WebControls.CheckBox"))
150: {
151: if (pi.PropertyType.Name.Equals("System.Int16") || pi.PropertyType.Name.Equals("System.Int32") || pi.PropertyType.Name.Equals("System.Int64"))
152: {
153: if (!pi.PropertyType.IsArray)
154: {
155: (c.GetValue(UI) as CheckBox).Checked = ((int)pi.GetValue(this, null) > 0) ? true : false;
156: }
157: else
158: {
159: object[] arrVal = (object[])pi.GetValue(this, null);
160: (c.GetValue(UI) as CheckBox).Checked = ((int)arrVal[IndexProp] > 0) ? true : false;
161: }
162: }
163: if (pi.PropertyType.Name.Equals("Boolean"))
164: {
165: if (!pi.PropertyType.IsArray)
166: {
167: (c.GetValue(UI) as CheckBox).Checked = (bool)pi.GetValue(this, null);
168: }
169: else
170: {
171: object[] arrVal = (object[])pi.GetValue(this, null);
172: (c.GetValue(UI) as CheckBox).Checked = (bool)arrVal[IndexProp];
173: }
174: }
175: if (pi.PropertyType.Name.Equals("System.String"))
176: {
177: if (!pi.PropertyType.IsArray)
178: {
179: (c.GetValue(UI) as CheckBox).Checked = (pi.GetValue(this, null).ToString().ToUpper().Equals("SIM") || pi.GetValue(this, null).ToString().ToUpper().Equals("S"));
180: }
181: else
182: {
183: object[] arrVal = (object[])pi.GetValue(this, null);
184: (c.GetValue(UI) as CheckBox).Checked = ((arrVal[IndexProp].ToString().ToUpper().Equals("SIM") || arrVal[IndexProp].ToString().ToUpper().Equals("S")));
185: }
186: }
187: }
188: if (c.FieldType.FullName.Equals("System.Web.UI.WebControls.CheckBoxList"))
189: {
190: if (!pi.PropertyType.IsArray)
191: {
192: (c.GetValue(UI) as CheckBoxList).SelectedValue = pi.GetValue(this, null).ToString();
193: }
194: else
195: {
196: object[] arrVal = (object[])pi.GetValue(this, null);
197: (c.GetValue(UI) as CheckBoxList).SelectedValue = arrVal[IndexProp].ToString();
198: }
199: }
200: if (c.FieldType.FullName.Equals("System.Web.UI.WebControls.RadioButtonList"))
201: {
202: if (!pi.PropertyType.IsArray)
203: {
204: (c.GetValue(UI) as RadioButtonList).SelectedValue = pi.GetValue(this, null).ToString();
205: }
206: else
207: {
208: object[] arrVal = (object[])pi.GetValue(this, null);
209: (c.GetValue(UI) as RadioButtonList).SelectedValue = arrVal[IndexProp].ToString();
210: }
211: }
212: if (c.FieldType.FullName.Equals("System.Web.UI.WebControls.GridView"))
213: {
214: if (!pi.PropertyType.IsArray)
215: {
216: (c.GetValue(UI) as GridView).DataSource = pi.GetValue(this, null);
217: (c.GetValue(UI) as GridView).DataBind();
218: }
219: else
220: {
221: object[] arrVal = (object[])pi.GetValue(this, null);
222: (c.GetValue(UI) as GridView).DataSource = arrVal[IndexProp];
223: (c.GetValue(UI) as GridView).DataBind();
224: }
225: }
226:
227:
228: if (c.FieldType.FullName.Equals("System.Web.UI.HtmlControls.HtmlInputHidden"))
229: {
230: string formatinfo = "";
231: int idx = 0;
232: if (ContainFormatInfo(pi.Name, out idx, out formatinfo))
233: {
234: if (!pi.PropertyType.IsArray)
235: {
236: (c.GetValue(UI) as HtmlInputHidden).Value = String.Format(formatinfo, pi.GetValue(this, null));
237: }
238: else
239: {
240: object[] arrVal = (object[])pi.GetValue(this, null);
241: (c.GetValue(UI) as HtmlInputHidden).Value = String.Format(formatinfo, arrVal[IndexProp]);
242: }
243: }
244: else
245: {
246: if (!pi.PropertyType.IsArray)
247: {
248: (c.GetValue(UI) as HtmlInputHidden).Value = pi.GetValue(this, null).ToString();
249: }
250: else
251: {
252: object[] arrVal = (object[])pi.GetValue(this, null);
253: (c.GetValue(UI) as HtmlInputHidden).Value = arrVal[IndexProp].ToString();
254: }
255: }
256: }
257: }
258: }
259: }
Sim, ele é um tanto longo, mas cada if trabalha da mesma maneira, por isso, quando chegar na parte de explicar a atribuição em si irei falar apenas sobre o primeiro componente, ou seja, de como atribuir o objeto em um TextBox; os outros serão análogos a este.
Como lembrete, soma-se ao lembrete do post anterior as convenções para nomearmos os componentes da interface de usuário: Prefixo de três (3) letras + Nome da Classe + Nome da Propriedade, todos estes sensíveis ao caso.
Por exemplo, temos uma classe chamada TFuncionario e uma propriedade chamada Nome será atribuída a um textbox. Seu nome deve ficar assim: tbxTFuncionarioNome.
O método pede como parâmetros o objeto Page que terá seus componentes atribuídos, as informações de seu tipo (método GetType() do objeto Page), e um ArrayList com os nomes de cada objeto que não será atribuído caso haja correspondência dele na classe.
Inicialmente, pego as informações de tipo do próprio objeto que vou atribuir e guardo na variável “t”.
Em seguida, faço uma iteração através de um laço foreach em todas as variáveis privadas ou protegidas da página que terá os valores dos componentes modificados. O método GetFields() da classe Type retorna uma coleção de objetos FieldInfo, que por sua vez correspondem às propriedades da classe referenciada pela variável “type” (segundo parâmetro do método BindToUI()). Este médodo pede como parâmetro os BindingFlags, sendo que colocamos o BindingFlags.Instance, já que queremos as variáveis de instância e BindingFlags.NonPublic, já que todos os componentes de uma página Web são declarados como protected.
Com cada item a ser iterado guardado na variável “c” declarada no foreach, verificamos se o mesmo está dentro do ArrayList ExcludeFromBind através de seu nome. Se estiver, passamos para a próxima iteração. Passamos para a próxima iteração caso o objeto seja nulo ou a propriedade Name for nula também.
Em seguida, isolamos o nome da propriedade da classe do nome do componente. Retiramos o prefixo, o nome da classe, e se ele for sucedido de underline (_) mais um número, isolamos isso também. Guardamos o resultado na variável “PropertyPattern”.
Em seguida, instanciamos um objeto do tipo PropertyInfo, que é análogo ao FieldInfo, só que neste caso iremos trabalhar sobre Propriedades e não sobre campos, ou seja, as variáveis de uma classe que possuem métodos get() e/ou set(). Para isso, inicializamos a variável “pi” utilizando o método GetProperty() da classe Type (a variável “t”) passando como parâmetro o nome da propriedade que iremos atribuir em seu correspondente na UI.
Se a propriedade for nula e seu valor, que pegamos através do método GetValue() de PropertyInfo, que pede como parâmetros o objeto a ser verificado (ponteiro this) e o índice (caso a propriedade seja indexada), também for nulo, passamos para a próxima iteração do foreach.
Criamos uma variável inteira chamada IndexProp, que denota se a nossa propriedade em questão é indexada: Se seu valor for –1, significa que não é indexada, caso contrário, denota o próprio índice.
Este índice é buscado através do método privado de Conexão HasIndexIndentifier, que recebe como parâmetros o nome do componente e devolve como saída o índice.
Agora a brincadeira da atribuição começa. Vou destacar aqui como atribuímos para um TextBox, que é o componente mais recorrente em uma interface de usuário:
1: if (c.FieldType.FullName.Equals("System.Web.UI.WebControls.TextBox"))
2: {
3: int idx = 0;
4: string formatinfo = "";
5: if (ContainFormatInfo(pi.Name, out idx, out formatinfo))
6: {
7: if (!pi.PropertyType.IsArray)
8: {
9: (c.GetValue(UI) as TextBox).Text = String.Format(formatinfo, pi.GetValue(this, null));
10: }
11: else
12: {
13: object[] arrVal = (object[])pi.GetValue(this, null);
14: (c.GetValue(UI) as TextBox).Text = String.Format(formatinfo, arrVal[IndexProp]);
15: }
16: }
17: else
18: {
19: if (!pi.PropertyType.IsArray)
20: {
21: (c.GetValue(UI) as TextBox).Text = pi.GetValue(this, null).ToString();
22: }
23: else
24: {
25: object[] arrVal = (object[])pi.GetValue(this, null);
26: (c.GetValue(UI) as TextBox).Text = arrVal[IndexProp].ToString();
27: }
28: }
29: }
Se o tipo do componente da iteração do foreach for do tipo System.Web.UI.WebControls.TextBox (um TextBox), verificamos primeiro se ele possui informações para a formatação de seu conteúdo, através do método ContainFormatInfo() da classe Conexao. Ele verifica a coleção _FormatProperties, e pede como parâmetros o nome da propriedade; e devolve como parâmetros de saída o índice do item a ser formatado e a string de formatação.
Se a propriedade em questão não é do tipo array (indexada), é feito um cast do componente da iteração atual do foreach para TextBox, que estará no método GetValue() nossa variável “c”) e atribuímos na propriedade Text o valor da propriedade correspondente no objeto, utilizando o método GetValue do objeto “pi”.
Caso a propriedade seja indexada, primeiro pegamos os valores para um array de object, para em seguida atribuir deste array somente o valor do índice que armazenamos anteriormente em IndexProp.
E se fomos formatar a propriedade para exibí-la, no passo anterior fazemos a atribuição através de um comando String.Format.
Para os outros componentes, o método é análogo.
O método BindFromUI() faz a operação inversa, tendo a mesma lógica do BindToUI(), porém ele faz uma troca de tipos, como veremos na transcrição do código a seguir:
1: public void BindFromUI(Page UI, Type type, ArrayList ExcludeFromBind)
2: {
3: Type t = this.GetType();
4: foreach (FieldInfo c in type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
5: {
6: if (ExcludeFromBind.Contains(c.Name))
7: {
8: continue;
9: }
10: if (c == null)
11: {
12: continue;
13: }
14: if (c.Name == null)
15: {
16: continue;
17: }
18:
19: //Retira o prefixo do nome do componente -> ele DEVE ter 3 letras, e o ID do controle deve ter mais que 3 letras
20: string PropertyPattern = (c.Name.Length < 3) ? "" : c.Name.Substring(3, c.Name.Length - 3);
21: PropertyPattern = PropertyPattern.Replace(t.Name, "");
22: if (PropertyPattern.Contains("_"))
23: {
24: PropertyPattern = PropertyPattern.Substring(0, PropertyPattern.IndexOf("_"));
25: }
26:
27:
28: PropertyInfo pi = t.GetProperty(PropertyPattern);
29: if (pi != null)
30: {
31: if (pi.GetSetMethod() == null)
32: {
33: continue;
34: }
35: int IndexProp = -1;
36: HasIndexIdentifier(c.Name, out IndexProp);
37:
38: if (c.FieldType.FullName.Equals("System.Web.UI.WebControls.TextBox"))
39: {
40: if ((c.GetValue(UI) as TextBox).Text.Trim().Equals(""))
41: {
42: pi.SetValue(this, null, null);
43: }
44: else
45: {
46: pi.SetValue(this, Convert.ChangeType((c.GetValue(UI) as TextBox).Text, pi.PropertyType.Name.Equals("Nullable`1") ? System.Nullable.GetUnderlyingType(pi.PropertyType) : pi.PropertyType), null);
47: }
48: }
49:
50: if (c.FieldType.FullName.Equals("System.Web.UI.WebControls.DropDownList"))
51: {
52: if ((c.GetValue(UI) as DropDownList).SelectedValue.Trim().Equals(""))
53: {
54: pi.SetValue(this, null, null);
55: }
56: else
57: {
58: pi.SetValue(this, Convert.ChangeType((c.GetValue(UI) as DropDownList).SelectedValue, pi.PropertyType.Name.Equals("Nullable`1") ? System.Nullable.GetUnderlyingType(pi.PropertyType) : pi.PropertyType), null);
59: }
60: }
61: if (c.FieldType.FullName.Equals("System.Web.UI.WebControls.RadioButton"))
62: {
63: if (pi.PropertyType.Name.Equals("System.Int16") || pi.PropertyType.Name.Equals("System.Int32") || pi.PropertyType.Name.Equals("System.Int64"))
64: {
65: pi.SetValue(this, ((c.GetValue(UI) as RadioButton).Checked ? 1 : 0), null);
66: }
67: if (pi.PropertyType.Name.Equals("Boolean"))
68: {
69: pi.SetValue(this, (c.GetValue(UI) as RadioButton).Checked, null);
70: }
71: if (pi.PropertyType.Name.Equals("System.String"))
72: {
73: pi.SetValue(this, ((c.GetValue(UI) as RadioButton).Checked ? "S" : "N"), null);
74: }
75: }
76: if (c.FieldType.FullName.Equals("System.Web.UI.WebControls.Label"))
77: {
78: pi.SetValue(this, Convert.ChangeType((c.GetValue(UI) as Label).Text, pi.PropertyType.Name.Equals("Nullable`1") ? System.Nullable.GetUnderlyingType(pi.PropertyType) : pi.PropertyType), null);
79: }
80:
81: if (c.FieldType.FullName.Equals("System.Web.UI.WebControls.CheckBox"))
82: {
83: if (pi.PropertyType.Name.Equals("System.Int16") || pi.PropertyType.Name.Equals("System.Int32") || pi.PropertyType.Name.Equals("System.Int64"))
84: {
85: pi.SetValue(this, ((c.GetValue(UI) as CheckBox).Checked ? 1 : 0), null);
86: }
87: if (pi.PropertyType.Name.Equals("Boolean"))
88: {
89: pi.SetValue(this, (c.GetValue(UI) as CheckBox).Checked, null);
90: }
91: if (pi.PropertyType.Name.Equals("System.String"))
92: {
93: pi.SetValue(this, ((c.GetValue(UI) as CheckBox).Checked ? "S" : "N"), null);
94: }
95: }
96: if (c.FieldType.FullName.Equals("System.Web.UI.WebControls.CheckBoxList"))
97: {
98: if ((c.GetValue(UI) as CheckBoxList).SelectedValue.Trim().Equals(""))
99: {
100: pi.SetValue(this, null, null);
101: }
102: else
103: {
104: pi.SetValue(this, Convert.ChangeType((c.GetValue(UI) as CheckBoxList).SelectedValue, pi.PropertyType.Name.Equals("Nullable`1") ? System.Nullable.GetUnderlyingType(pi.PropertyType) : pi.PropertyType), null);
105: }
106: }
107: if (c.FieldType.FullName.Equals("System.Web.UI.WebControls.RadioButtonList"))
108: {
109: if ((c.GetValue(UI) as RadioButtonList).SelectedValue.Trim().Equals(""))
110: {
111: pi.SetValue(this, null, null);
112: }
113: else
114: {
115: pi.SetValue(this, Convert.ChangeType((c.GetValue(UI) as RadioButtonList).SelectedValue, pi.PropertyType.Name.Equals("Nullable`1") ? System.Nullable.GetUnderlyingType(pi.PropertyType) : pi.PropertyType), null);
116: }
117: }
118: if (c.FieldType.FullName.Equals("System.Web.UI.HtmlControls.HtmlInputHidden"))
119: {
120: if ((c.GetValue(UI) as HtmlInputHidden).Value.Trim().Equals(""))
121: {
122: pi.SetValue(this, null, null);
123: }
124: else
125: {
126: pi.SetValue(this, Convert.ChangeType((c.GetValue(UI) as HtmlInputHidden).Value, pi.PropertyType.Name.Equals("Nullable`1") ? System.Nullable.GetUnderlyingType(pi.PropertyType) : pi.PropertyType), null);
127: }
128: }
129: }
130: }
131: }
Se fomos atribuir a propriedade Text de um TextBox em uma propriedade inteira, teremos um erro na execução do programa. Para isso, no momento da atribuição utilizo o método Convert.ChangeType, que pede como parâmetros o valor e o tipo de destino, que no nosso caso é o tipo da propriedade a ser atribuída.
Para pegar o tipo, primeiro verificamos se a propriedade é do tipo nulável, pois caso afirmativo deveremos pegar o tipo encapsulado ao invés do tipo real. Utilizando o método System.Nullable.GetUnderlyingType() conseguimos fazer isso.
A lógica deste método é análoga ao BindToUI(), o que dispensa maiores comentários a respeito deste código.
Foi trabalhoso no início, mas depois poupou um trabalho…
Um abraço!
0 comentários:
Postar um comentário