Category Archives: Code Snippets

Code Snippets Delphi

Gerenating a GUID using Delphi 7

GUID – Globally Unique IDentifier

In Delphi, GUID values are represented with the TGuid record defined in the System unit. A Guid value is a 128-bit integer (16 bytes) that can be used in database applications when a unique identifier is required.
When developing database applications, the TGuidField is used to represents a guid field in a dataset.


procedure TForm1.btnGetGUIDClick(Sender: TObject);
var
  Guid: TGUID;
begin
  CreateGUID(Guid);
  form1.label1.Caption := GUIDToString(Guid);
end;

read more »

Code Snippets Delphi web services

Consuming ASP.NET 2.0 Web Services in Delphi for Win32

A couple of years ago I wrote an article Consuming C# Web Services with Delphi 7 Professional, and while the information in the article is still correct, it’s no longer complete, because ASP.NET 2.0 changed the rules a little bit.
Even if you follow the examples exactly on creating the web service in C# and in creating the consuming application in Delphi for Win32, no matter what you try to echo, the result will always come back as 0 for numbers or as an empty string for strings.

This is due to the fact that the C# web service is deployed on an ASP.NET 2.0 machine (which changed some of the ways WSDL was published compared to .NET 1.1).

The problem is caused by the fact that any .NET Web Service is using the document|literal binding. With ASP.NET 1.x Web Services, this was specified using element, but with ASP.NET 2.0 Microsoft has changed that and now specifies the style in the operation input and output nodes instead of the binding element. The Delphi Win32 WSDL Importer is not able to recognise this, and as a result the generated import unit is using the (for Delphi default) binding type of RPC instead of the .NET document|literal binding type.
CodeGear is aware of the situation, and is already working on fixing the problem in the Win32 WSDL Importer. In the meantime, there is a workaround available that you can use, namely manually specifying the ioDocument as InvokeOptions for the SOAP interface type, as follows:

  InvRegistry.RegisterInvokeOptions(TypeInfo(xxx), ioDocument);

Where xxx is the name of your SOAP interface type.

This line of code needs to be added to the initialization section of the generated Win32 import unit, and will make sure the parameters and result types are no longer empty when Win32 clients are talking to ASP.NET 2.0 Web Services.

 

source link:
Bob Swart 2/5/2007 10:04:56 AM (GMT+1)

Code Snippets .NET Tips & tricks

Code Translation for .NET (C#<->VB.NET)

This service will translate the code for you, just start typing the code or upload a file to convert it.
For now it only supports from VB.NET to C# and from C# to VB.NET.
To use it you can either:

  1. Start typing your code.
  2. Copy and Paste the code in the Code Text Box.
  3. Translate an entire file using the file upload.

Disclaimer: No copy is done whatsoever of the code that you either type, or upload for translation. Everything is processed in the server in memory and returned immediately to the browser.
If you want to give feedback on the translation, please send me an email including the code you used and the desired translation to me@carlosag.net.

http://www.carlosag.net/Tools/CodeTranslator/

see also:

http://www.developerfusion.com/tools/convert/csharp-to-vb/

Code Snippets Tips & tricks Utils

Using Character Encoding in ASP.NET

Open the file named web.config in the ASP.NET project. The value of requestEncoding attribute in globalization element is “utf-8”. It means the requested texts were encoded as UTF-8 character set. Because SCO5.05 does not support UTF-8, therefore the requested texts where changed.

VB:

Public Shared Function unicode_iso8859(ByVal src As String) As String
Dim iso As Encoding = Encoding.GetEncoding(“iso8859-1”)
Dim unicode As Encoding = Encoding.UTF8
Dim unicodeBytes As Byte() = unicode.GetBytes(src)
Return iso.GetString(unicodeBytes)
End Function

Public Shared Function iso8859_unicode(ByVal src As String) As String
Dim iso As Encoding = Encoding.GetEncoding(“iso8859-1”)
Dim unicode As Encoding = Encoding.UTF8
Dim isoBytes As Byte() = iso.GetBytes(src)
Return unicode.GetString(isoBytes)
End Function

label1.Text = iso8859_unicode(MyString)

more details in http://www.codeproject.com/KB/aspnet/Encoding_in_ASPNET.aspx

Code Snippets

Excel: Automated Trim Function For Whole Column

Sub trimcol()
Dim r As Range
Set r = Intersect(Range(“C1”).EntireColumn, ActiveSheet.UsedRange)
r.Value = Evaluate(“IF(ROW(” & r.Address & “),IF(” & r.Address & “<>””””,TRIM(” & r.Address & “),””””))”)
End Sub

Code Snippets

Export image to PDF in Silverlight

After a few hours serching a way to put a image into pdf in silverlight, something worked out, here goes:

Libraries used:
Imports silverPDF
Imports PdfSharp.Pdf
Imports PdfSharp.Drawing
Imports iTextSharp.text
Imports ImageTools
Imports ImageTools.IO.Jpeg
Imports ImageTools.ImageBase
Imports ImageTools.Helpers
Imports ImageTools.ImageExtensions

Code snippet (vb):

        Dim d As New SaveFileDialog()
        d.Filter = "PDF file format|*.pdf"
        ' Save the document...
        If d.ShowDialog() = True Then
            Dim document As New PdfDocument()
            Dim page As PdfPage = document.AddPage()
            Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
            Dim img As ImageTools.ImageBase = Me.canvas1.ToImage()
            Dim mstream As New MemoryStream()
            Dim encoder As New JpegEncoder()
            encoder.Encode(img, mstream)
            mstream.Seek(0, SeekOrigin.Begin)
            Dim pdfImg As XImage = XImage.FromStream(mstream)
            gfx.DrawImage(pdfImg, 0, 0)
            document.Save(d.OpenFile())
        End If

CodeSnippet (C#):

SaveFileDialog d = new SaveFileDialog();
d.Filter = "PDF file format|*.pdf";

// Save the document...
if (d.ShowDialog() == true) {
	PdfDocument document = new PdfDocument();
	PdfPage page = document.AddPage();
	XGraphics gfx = XGraphics.FromPdfPage(page);

	ImageTools.ImageBase img = this.canvas1.ToImage();
	MemoryStream mstream = new MemoryStream();
	JpegEncoder encoder = new JpegEncoder();
	encoder.Encode(img, mstream);
	mstream.Seek(0, SeekOrigin.Begin);
	XImage pdfImg = XImage.FromStream(mstream);
	gfx.DrawImage(pdfImg, 0, 0);

	document.Save(d.OpenFile());

}
Code Snippets ASP.Net 2.0

problema com asp:menu no IE8

O internet explorer 8 se tornou muito, muito mais compatível com os padrões W3C do que as versões anteriores.

A diferença foi tanta que o IE 8 precisou criar o modo de compatibilidade, para que páginas que ainda não são totalmente compatíveis com este padrão possam continuar funcionando.

Desenvolvedores podem configurar seus sites para serem sempre rodados em modo de compatibilidade

Até mesmo o mais inesperado foi atingido pelas mudanças no IE 8 : O webcontrol de menu nativo do ASP.NET não encontrava-se 100% compatível com o W3C e consequentemente os sites que utilizam o webcontrol de menu apenas continuarão funcionando em modo de compatibilidade.

Existe uma solução simples em CSS que os sites que utilizam o webcontrol de menu podem utilizar :

   1: <style type="text/css">
   2: .adjustedZIndex {
   3:      z-index: 1;
   4:     }
   5: </style>

Adiciona-se este estilo em uma masterpage, por exemplo, e define-se como a cssClass do dynamicMenuStyle :

   1: <asp:Menu ID="Menu1" runat="server">
   2:     <DynamicMenuStyle CssClass="adjustedZIndex" />
   3: </asp:Menu>

Sendo que esta última parte pode ser feita através da janela de propriedades.

Sem dúvida esta é a forma mais simples de corrigir o problema. A Microsoft, porém, por obrigação, disponibilizou um patch de correção que resolve o problema do menu. A forma mais fácil de localizar este path é através deste KB .

Se vocês seguirem os links indicados no KB para o patch, encontrarão descrições muito estranhas, se referindo a problemas do IIS entre outros. Ocorre que o patch para o menu do ASP.NET foi discretamente inserido dentro destes outros.

Considerando as dificuldades de instalar isso em provedores, por exemplo, a solução com CSS é bem mais simples

por Dennes Oliveira

Code Snippets ASP.Net

ASP.Net Get File Size

Dim MyFile As String = “~/photos/myImage.gif”

Dim finfo As New FileInfo(Server.MapPath(MyFile))

Dim FileInBytes As Long = finfo.Length

Dim FileInKB As Long = finfo.Length / 1024

Response.Write((“File Size: ” & FileInBytes.ToString() & ” bytes (“) + FileInKB.ToString() & ” KB)”)

Code Snippets ASP.Net 2.0 SQL Server

Configurações para começar a utilizar WebParts

Para começar a usar Webparts é necessário ter uma base de dados de suporte.

Para criar essa base de dados é necessários executar a aplicação aspnet_reqsql.exe que se encontra no directorio do .Net framework, normalmente C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

Depois é necessário dar permissões a um utilizador para aceder à base de dados criada, no SQLServer.

Estando o SQL preparado necessitamos de criar as ligações no nosso webSite:

no ficheiro web.config devemos criar uma nova connection (por exemplo):

<connectionStrings>
<add name=”connASPNETDB” connectionString=”Server=MEUSERVER; Database=ASPNETDB; User Id=MEUUSER;Password=USERPASS;” providerName=”System.Data.SqlClient” />
</connectionStrings>

e definir o sqlpersonalization provider :

<webParts>
<personalization defaultProvider=”AspNetSqlPersonalizationProvider”>
<providers>
<clear/>
<add name=”AspNetSqlPersonalizationProvider”
type=”System.Web.UI.WebControls.WebParts.SqlPersonalizationProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”
connectionStringName=”connASPNETDB” />
</providers>
</personalization>
</webParts>

e bem-vindo ao mundo das webparts 🙂

Code Snippets Networking Utils

Executar scripts em AD

Se o dominio estiver bem configurado na script, execute a script a partir da linha de comandos usando:

runas /u:domain\admin cmd.exe

e usando o comando

cscript.exe scriptname.vbs

Â