01.Blogs :
abassi  
André Bassi
______________________________________
Microsoft Certified Application Developer .NET

-- Alterando dinamicamente uma key do appSettings da sua aplicação Winform
Sunday, October 15, 2006 3:25 AM



Se houver a necessidade de mudar por exempo a key ConnString do SQL Server ou a PathImagens da sua aplicação configurada na app.config de forma dinâmica em um projeto Winform que seja na instalação ou em tempo de execução, segue a solução aplicada para .NET Framework 1.1 abaixo:

Apartir de vários exemplos que a microsoft oferece eu cheguei a uma solução para esta tal tarefa:

Após a classe AppSettings logo abaixo adicionada ao projeto vamos aplicá-la em um exemplo:

  'Instancia a classe AppSettings para o app.Config receber as atualizações
  Dim m_AppSettings As AppSettings
 
 
m_AppSettings = New AppSettings("C:\Projetos\Exemplo\AppSetting\Exemplo.exe.config", True)

   'Atualiza a key do app.config  "Image_Folder"
   Dim m_AppSetting As AppSetting
  
m_AppSetting = New AppSetting("Image_Folder", "C:\Projetos\Exemplo\AppSetting\ImagensX")
   m_AppSettings.Update(m_AppSetting)


PS: Crie uma classe chamada AppSetting em VB.NET, conforme abaixo, ou você poderá transcrever o código para C# facilmente

 

<-- Início da classe -->

Option Strict On

Imports System.Configuration
Imports System.Collections
Imports System.Xml


Public Class AppSetting

    Private mParent As AppSettings
    Private mstrKey As String
    Private mstrValue As String

    Public Property Key() As String
        Get
            Return mstrKey
        End Get
        Set(ByVal Value As String)
            Me.UpdateParent()
            Value = mstrKey
        End Set
    End Property

    Public Property Value() As String
        Get
            Return mstrValue
        End Get
        Set(ByVal Value As String)
            Me.UpdateParent()
            mstrValue = Value
        End Set
    End Property

    Private Sub UpdateParent()
        If Not Me.mParent Is Nothing Then
            Me.mParent.Update(Me)
        End If
    End Sub

    Public Sub New()
        Me.New(String.Empty, String.Empty)
    End Sub

    Public Sub New(ByVal Key As String, ByVal Value As String)
        Me.New(Key, Value, Nothing)
    End Sub

    Friend Sub New(ByVal Key As String, ByVal Value As String, ByVal Parent As AppSettings)
        MyBase.New()
        Me.mstrKey = Key
        Me.mstrValue = Value
        Me.mParent = Parent
    End Sub
End Class

Public Class AppSettings
    Implements IEnumerable, IDisposable

    Private ArquivoConfig As New XmlDocument
    Private NoXML As XmlNode
    Private strArquivo As String
    Private blnSalvarAutomatico As Boolean
    Private m_Itens() As AppSetting
    Private m_Disposing As Boolean
    Private m_Disposed As Boolean

    Private Const Elemento_AppSetting As String = "configuration//appSettings"
    Private Const Novo_Elemento As String = "add"
    Private Const xPath_Nova_Key As String = "//add"
    Private Const xPath_Nova_Key2 As String = "//add[@key='{0}']"

    Public Sub New(ByVal ConfigFile As String)
        Me.New(ConfigFile, False)
    End Sub

    Public Sub New(ByVal ConfigFile As String, ByVal AutoSave As Boolean)
        MyBase.New()
        If ConfigFile.Length = 0 Then
            Throw New ArgumentNullException("You must pass in a valid file name.")
        Else
            If System.IO.File.Exists(ConfigFile) Then
                Try
                    ArquivoConfig.Load(ConfigFile)

                Catch exp As Exception
                    Throw New System.IO.FileLoadException("O arquivo especificado não pode ser carregado.", exp)
                End Try

                NoXML = ArquivoConfig.SelectSingleNode(Elemento_AppSetting)

                If NoXML Is Nothing Then
                    Throw New ConfigurationException("O arquivo especificado não é um arquivo de configuração válido")
                End If

                strArquivo = ConfigFile

                Me.AutoSave = AutoSave

            Else
                Throw New System.IO.FileNotFoundException(String.Format("O arquivo especificado {0} não existe.", ConfigFile))
            End If
        End If

    End Sub

    Public Sub Dispose() Implements System.IDisposable.Dispose
        Me.m_Disposing = True
        Me.m_Disposed = True
        Me.m_Disposing = False
        GC.SuppressFinalize(Me)
    End Sub

    Protected Overrides Sub Finalize()
        MyBase.Finalize()
        If Not Me.m_Disposed Then
            If Not Me.m_Disposing Then
                Me.Dispose()
            End If
        End If
    End Sub

    Public Property AutoSave() As Boolean
        Get
            Return Me.blnSalvarAutomatico
        End Get
        Set(ByVal Value As Boolean)
            Me.blnSalvarAutomatico = Value
        End Set
    End Property

    Public Sub Add(ByVal NewSetting As AppSetting)
        Dim newElem As XmlElement
        Dim newAttr As XmlAttribute

        newElem = ArquivoConfig.CreateElement(Novo_Elemento)

        newAttr = ArquivoConfig.CreateAttribute("key")
        newAttr.Value = NewSetting.Key
        newElem.Attributes.Append(newAttr)

        newAttr = ArquivoConfig.CreateAttribute("value")
        newAttr.Value = NewSetting.Value
        newElem.Attributes.Append(newAttr)

        NoXML.AppendChild(newElem)

        If Me.AutoSave Then
            Me.Save()
        End If
    End Sub

    Public Function Add(ByVal Key As String, ByVal Value As String) As AppSetting
        Dim NewSetting As New AppSetting(Key, Value, Me)
        Me.Add(NewSetting)
        Return NewSetting
    End Function

    Public Function Item(ByVal Key As String) As AppSetting
        Dim xNode As XmlNode
        Dim strSearch As String = xPath_Nova_Key2

        xNode = NoXML.SelectSingleNode(String.Format(strSearch, Key))

        If xNode Is Nothing Then
            Throw New ArgumentOutOfRangeException("Key", Key, "O item informado para atualização não existe.")
        Else
            Dim las As New AppSetting
            las.Key = Key
            las.Value = xNode.Attributes.Item(1).Value

            Return las
        End If
    End Function

    Public Sub RemoveByKey(ByVal Setting As AppSetting)
        Dim xNode As XmlNode
        Dim strSearch As String = xPath_Nova_Key2

        xNode = NoXML.SelectSingleNode(String.Format(strSearch, Setting.Key))

        If Not xNode Is Nothing Then

        End If

        If Me.AutoSave Then
            Me.Save()
        End If

    End Sub

    Public Function Update(ByVal Key As String, ByVal Value As String) As AppSetting
        Dim NewSetting As New AppSetting(Key, Value, Me)
        Me.Update(NewSetting)
        Return NewSetting
    End Function

    Public Sub Update(ByVal NewSetting As AppSetting)
        Dim xNode As XmlNode
        Dim strSearch As String = xPath_Nova_Key2

        xNode = NoXML.SelectSingleNode(String.Format(strSearch, NewSetting.Key))

        If xNode Is Nothing Then
            Throw New ArgumentOutOfRangeException("Key", NewSetting.Key, "O item informado para atualização não existe.")
        Else
            xNode.Attributes.Item(1).Value = NewSetting.Value
        End If

        If Me.AutoSave Then
            Me.Save()
        End If
    End Sub

    Public Sub Save()
        ArquivoConfig.Save(Me.strArquivo)
    End Sub

    Private Function GetAllItems() As AppSetting()
        Dim xNode As XmlNode
        Dim xNodeList As XmlNodeList
        Dim atts As XmlAttributeCollection

        xNodeList = NoXML.SelectNodes(xPath_Nova_Key)

        Dim xa As XmlAttribute
        Dim asa(xNodeList.Count - 1) As AppSetting
        Dim asi As AppSetting
        Dim i As Integer = -1

        For Each xNode In xNodeList
            i += 1
            atts = xNode.Attributes

            With atts
                asi = New AppSetting(.Item(0).Value, .Item(1).Value, Me)
            End With
            asa(i) = asi
        Next

        Return asa
    End Function

    Private Function GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
        Me.m_Itens = Me.GetAllItems()
        Return New Iterator(Me.m_Itens)
    End Function

    Private Class Iterator
        Implements IEnumerator

        Private mData() As AppSetting
        Private Index As Integer = -1

        Public Sub New(ByVal Keys() As AppSetting)
            mData = Keys
        End Sub
        Private ReadOnly Property Current() As Object Implements System.Collections.IEnumerator.Current
            Get
                Return mData(Index)
            End Get
        End Property
        Private Function MoveNext() As Boolean Implements System.Collections.IEnumerator.MoveNext
            Index += 1
            If (Index <= (mData.Length - 1)) Then
                Return True
            End If
        End Function
        Private Sub Reset() Implements System.Collections.IEnumerator.Reset
            Index = -1
        End Sub
    End Class

End Class

<-- Término da classe -->

 

 

0 Comments | Post a Comment |

posted  by  abassi  with 

-- Performace: Compactação de viewstate quando necessário
Saturday, October 14, 2006 6:17 AM

Em um cliente da empresa no qual presto serviço, houve a necessidade de otimizar páginas que continham grids e controles que retornavam a viewstate absurdamente enorme. A solução que encontrei foi a compactação com ICSharpCode.SharpZipLib que pode ser encontrado em http://www.icsharpcode.net/OpenSource/SharpZipLib/

A decisão de utilizar o SharpZipLib foi pelo motivo do .NET Framework 1.1 não possuir recursos de compactação, sendo que para quem já codifica para o Framework 2.0 já há namespace (em System.IO.Compression) para isso, portanto a classe abaixo é destinada ao .NET Framework 1.1.



Criei uma classe específica (Compression.cs)  de compactação:

<--- Início da classe --->

using System;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib;
 

public enum CompressionType

{

 GZip,

 BZip2,

 Zip

}


// Implementado por Andre Bassi - 12/07/2006
// Classe para realizar a compressao do viewstate pelo motivo que todos os controles sao manipulados
// via viewstate

public class Compression

{

 public static CompressionType CompressionProvider = CompressionType.BZip2;

 

 private static Stream OutputStream(Stream inputStream)

 {

  switch(CompressionProvider)

  {

   case CompressionType.BZip2:

    return new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(inputStream);

   case CompressionType.GZip:

    return new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(inputStream);

   case CompressionType.Zip:

    return new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(inputStream);

   default:

    return new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(inputStream);

                                           

  }

 }

 

 private static Stream InputStream(Stream inputStream)

 {

  switch(CompressionProvider)

  {

   case CompressionType.BZip2:

    return new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(inputStream);

   case CompressionType.GZip:

    return new ICSharpCode.SharpZipLib.GZip.GZipInputStream(inputStream);

   case CompressionType.Zip:

    return new ICSharpCode.SharpZipLib.Zip.ZipInputStream(inputStream);

   default:

    return new ICSharpCode.SharpZipLib.GZip.GZipInputStream(inputStream);                                                                       

  }

 }

       

 public static byte[] Compress(byte[] bytesToCompress)

 {

  MemoryStream ms = new MemoryStream();

  Stream s = OutputStream(ms);

  s.Write(bytesToCompress,0, bytesToCompress.Length);

  s.Close();

  return  ms.ToArray();

 }

 

 public static string Compress(string stringToCompress)

 {

  byte[] compressedData = CompressToByte(stringToCompress);

  string strOut = Convert.ToBase64String(compressedData);

  return strOut;

 }

 public static  byte[] CompressToByte(string stringToCompress)

 {

  byte[] bytData = Encoding.Unicode.GetBytes(stringToCompress);

  return Compress(bytData);;

 }

 

 public static string DeCompress(string stringToDecompress)

 {

  string outString = string.Empty;

  if (stringToDecompress == null)

  {

   throw new ArgumentNullException("stringToDecompress","String null!");

  }

  try

  {

   byte[] inArr = Convert.FromBase64String(stringToDecompress.Trim());

   outString = System.Text.Encoding.Unicode.GetString(DeCompress(inArr));

  }

  catch (NullReferenceException  nEx)

  {

   return nEx.Message;

  }

  return outString;

 }

 

 public static  byte[]  DeCompress(byte[] bytesToDecompress)

 {

  byte[] writeData = new byte[4096];

  Stream s2 = InputStream(new MemoryStream(bytesToDecompress));

  MemoryStream outStream = new MemoryStream();

  while(true)

  {

   int size = s2.Read(writeData,0,writeData.Length);

   if(size>0)

   {

    outStream.Write(writeData,0,size);

   }

   else

   {

    break;

   }

  }

  s2.Close();

  byte[] outArr = outStream.ToArray();

  outStream.Close();

  return outArr;

 }

}

<--- Término da classe --->


Com isso uma classe denominada CompressedVSBasePage herdando da namespace System.Web.UI.Page foi criada, ou seja, todas as páginas que precisem de otimização poderão ser herdadas de CompressedVSBasePage já com o recurso de otimização de compactação da viewstate: 


<--- Início da classe --->

public class CompressedVSBasePage : System.Web.UI.Page
{
 /// <summary>
 /// Main constructor.
 /// </summary>
 public CompressedVSBasePage()
 {
  this.Load += new System.EventHandler(this.BasePage_Load);
 }

 protected override void SavePageStateToPersistenceMedium(object viewState)
 {
  LosFormatter  _formatter = new LosFormatter();
  StringWriter sw = new StringWriter();
  _formatter.Serialize(sw, viewState);
  string outStr = Compression.Compress(sw.ToString());
  Page.RegisterHiddenField("__COMPRESSEDVIEWSTATE",outStr);
 }

 protected override object LoadPageStateFromPersistenceMedium()
 {
  LosFormatter  _formatter = new LosFormatter();
  string vsString = Request.Form["__COMPRESSEDVIEWSTATE"];
  string outStr = Compression.DeCompress(vsString);
  return _formatter.Deserialize(outStr);
 }


<--- Término da classe -