vbdotnet.it

Tricks & tips, workaround, forum and ideas with .Net

About the author

Enrico Rossini è il gestore di questo blog.
E-mail me Send mail

Recent posts

Recent comments

Contributi

Best 6 ~ 6 users ~ 6 comments

Info legali

Le opinioni espresse in questo blog sono strettamente personali e ogni persona è responsabile dei commenti che inserisce. I marchi citati sono delle rispettive aziende.

© Copyright 2010

Advertising


Accedere ad un file di risorsa globale in ASP.NET

Buon anno! Questo veloce tips per darvi il codice per accedere ad un elemento di una risorsa ovvero un file .resx che si trova all'interno della cartella App_GlobalResources. Ammettendo di aver creato il file Messages.resx ed aver inserito un elemento con nome Saluto, il codice da scrivere è il seguente:

Me.GetGlobalResourceObject("Messages", "Saluto").ToString

È necessario importare System.Globalization.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,
Posted by enrico on Tuesday, January 05, 2010 11:51 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Conversione progetto da .NET 1.x: errore allowDefinition = 'MachineToApplication'

Nel convertire un progetto .NET 1.x alla versione 2.0 o superiore, ci si imbatte quasi sempre in questo criptico errore. "It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level This error can be caused by a virtual directory not being configured as an application in IIS."  Il problema è che la conversione crea una cartella Backup con all'interno un file web.config che va in conflitto con quello presente nella cartella principale.

Cancellando la cartella Backup il problema viene risolto.

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by enrico on Friday, October 23, 2009 3:35 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Formattazione con String.Format

formatting strings

exampleoutput
String.Format("--{0,10}--", "test"); --      test--
String.Format("--{0,-10}--", "test"); --test      --

formatting numbers

specifiertypeformatoutput
(double 1.2345)
output
(int -12345)
c currency {0:c} £1.23 -£12,345.00
d decimal
(whole number)
{0:d} System.FormatException -12345
e exponent / scientific {0:e} 1.234500e+000 -1.234500e+004
f fixed point {0:f} 1.23 -12345.00
g general {0:g} 1.2345 -12345
n number {0:n} 1.23 -12,345.00
r round trippable {0:r} 1.23 System.FormatException
x hexadecimal {0:x4} System.FormatException ffffcfc7

custom number formatting

specifiertypeformatoutput
(double 1234.56)
0 zero placeholder {0:00.000} 1234.560
# digit placeholder {0:#.##} 1234.56
. decimal point placeholder {0:0.0} 1234.6
, thousand separator {0:0,0} 1,235
% percentage {0:0%} 123456%

date formatting

specifiertypeoutput
(June 8, 1970 12:30:59)
d Short Date 08/06/1970
D Long Date 08 June 1970
t Short Time 12:30
T Long Time 12:30:59
f Full date and time 08 June 1970 12:30
F Full date and time (long) 08 June 1970 12:30:59
g Default date and time 08/06/1970 12:30
G Default date and time (long) 08/06/1970 12:30:59
M Day / Month 8 June
r RFC1123 date string Mon, 08 Jun 1970 12:30:59 GMT
s Sortable date/time 1970-06-08T12:30:59
u Universal time, local timezone 1970-06-08 12:30:59Z
Y Month / Year June 1970

custom date formatting

specifiertypeoutput
(June 8, 1970 12:30:59)
dd Day 08
ddd Short Day Name Mon
dddd Full Day Name Monday
hh 2 digit hour 12
HH 2 digit hour (24 hour) 12
mm 2 digit minute 30
MM Month 06
MMM Short Month name Jun
MMMM Month name June
ss seconds 59
tt AM/PM PM
yy 2 digit year 70
yyyy 4 digit year 1970
: seperator, e.g. {0:hh:mm:ss} 12:30:59
/ seperator, e.g. {0:dd/MM/yyyy} 08/06/1970

Currently rated 3.0 by 2 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: asp.net | Generalità | vb.net
Posted by enrico on Friday, August 07, 2009 11:15 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Leggere un file Microsoft Excel 97/2003 o 2007

La funzione che presento oggi consente di importare un foglio di Microsoft Excel in un dataset nelle versioni 97, 2003 e 2007.

 

   1: ''' <summary>
   2: ''' Reads the data from excel.
   3: ''' </summary>
   4: ''' <param name="excelfilename">The excelfilename.</param>
   5: ''' <returns></returns>
   6: Function ReadDataFromExcel(ByVal excelfilename As String) As DataSet
   7:     Dim ds As New DataSet
   8:     Dim da As OleDbDataAdapter
   9:     Dim conn As OleDbConnection
  10:  
  11:     Try
  12:         If System.IO.Path.GetExtension(excelfilename) = ".xls" Then
  13:             conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & excelfilename & "; Extended Properties=Excel 8.0;")
  14:         ElseIf System.IO.Path.GetExtension(excelfilename) = ".xlsx" Then
  15:             conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & excelfilename & "; Extended Properties=Excel 8.0;")
  16:         End If
  17:  
  18:         da = New OleDbDataAdapter("SELECT * FROM [Foglio1$]", conn)
  19:  
  20:         conn.Open()
  21:         da.Fill(ds)
  22:     Catch ex As Exception
  23:         MsgBox(ex.Message)
  24:     Finally
  25:         If conn.State = ConnectionState.Open Then
  26:             conn.Close()
  27:         End If
  28:     End Try
  29:     ReadDataFromExcel = ds
  30: End Function

Buon lavoro e ricordatevi il nostro forum!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by enrico on Tuesday, April 07, 2009 7:32 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Inviare un'email con autenticazione in ASP.NET 2.0

Questo semplice codice illustra come poter inviare un’email da ASP.NET 2.0 e successivi con l’autenticazione del server SMTP.

   1: ' crea un nuovo oggetto MailMessage e specifica mittente e destinatario
   2: Dim Email As New System.Net.Mail.MailMessage( _
   3:    "info@vbdotnet.it", "info@pippo.com")
   4: Email.Subject = "test subject"
   5: Email.Body = "this is a test"
   6: Dim mailClient As New System.Net.Mail.SmtpClient()
   7:  
   8: ' questo oggetto salva le credenziali per l'accesso al server SMTP
   9: Dim basicAuthenticationInfo As _
  10:    New System.Net.NetworkCredential("username", "password")
  11:  
  12: ' inserire qui il tuo server remoto o quello del tuo providers
  13: mailClient.Host = "Mail.RemoteMailServer.com"
  14: mailClient.UseDefaultCredentials = False
  15: mailClient.Credentials = basicAuthenticationInfo
  16: mailClient.Send(Email)

Ciao

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: asp.net | vb.net | web
Posted by enrico on Friday, March 27, 2009 1:09 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Aggiungere uno script JS ad un ScriptManager (ad esempio JQuery)

Utilizzando Ajax può capitare di dover inserire uno script JS all’interno della pagina. Per poterlo fare basta utilizzare la seguente sintassi:

   1: <asp:ScriptManager ID="ScriptManager1" runat="server">
   2:    <Scripts>
   3:       <asp:ScriptReference Path="~/js/jquery/jquery-1.2.6.min.js" />
   4:    </Scripts>
   5: </asp:ScriptManager>

Buon lavoro!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by enrico on Monday, March 23, 2009 3:24 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Impostare una cultura in un progetto ASP.NET

Mi è capitato di installare un’applicazione su un server web e molti utenti esterni mi creavano dei problemi sulle date. Ho scoperto che alcuni utenti avevano il sistema operativo in Inglese e quindi le date venivano invertite ma non riconosciute dal server.

Ho risolto imponendo direttamente nel web.config le impostazioni sulla cultura in questo modo:

   1: <configuration>
   2:   <system.web>
   3:     <globalization culture="it-IT" uiCulture="it" requestEncoding="UTF-8" responseEncoding="UTF-8" fileEncoding="UTF-8" />
   4:   <system.web>
   5: </configuration>

Buon lavoro!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by enrico on Wednesday, February 18, 2009 6:23 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Convalida di viewstate MAC non riuscita

Oggi mi è capitato un errore interessante che è il seguente:

[HttpException (0x80004005): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.]

Il problema è che il mio PC portatile ha Vista e non ha alcun tipo di cluster e non è sicuramente in una webfarm.

Ho rilevato che il bug si verifica con i controlli Data (gridview, datalist, formview) di ASP.NET che usano il DataKeyName o in pagine lente. Un’altra possibilità è che il form sia multipart e si sia definito nel tag form un’action su una pagina diversa.

La soluzione è di aggiungere nella sezione pages alcuni parametri:

   1:  <configuration>
   2:     <system.web>
   3:        <pages enableEventValidation="false" enableViewStateMac="false" viewStateEncryptionMode ="Never" >
   4:     </system.web>
   5:  </configuration>

Ciao, buon lavoro

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:
Categories: asp.net
Posted by enrico on Wednesday, January 28, 2009 2:57 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Esportare un report di Crystal Report direttamente in PDF con ASP.NET

Già creare un report alle volte non è una cosa velocissima ma quando all’utente gli viene proposta la pagina di selezione di tipologia di report da stampare, va in panico. È meglio quindi far in modo che il report creato con Crystal Report venga subito visualizzato in un file PDF.

La risoluzione è abbastanza semplice. Innanzitutto inserire gli opportuni import che sono i seguenti:

   1:  Imports CrystalDecisions.CrystalReports.Engine
   2:  Imports CrystalDecisions.Shared
   3:  Imports CrystalDecisions.Web.Design

Poi nella funzione di generazione dei report e del suo binding, inserire questo codice (oReport è di tipo ReportDocument):

   1:  Dim objMem As New MemoryStream
   2:  objMem = CType(oReport.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat), System.IO.MemoryStream)
   3:  oReport.Close()
   4:   
   5:  Response.Clear()
   6:  Response.AddHeader("content-disposition", "attachment;filename=Export.pdf")
   7:  Response.Buffer = True
   8:  Response.ContentType = "application/pdf"
   9:  Response.BinaryWrite(objMem.ToArray())
  10:  Response.End()

Ciao.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by enrico on Thursday, January 22, 2009 4:36 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Selezionare un’opzione di un menu in ASP.NET

Mi è capitato di aver un controllo menu di ASP.NET creato dinamicamente in un form ASPX. Ogni elemento del menu ha un valore. Il mio problema era di selezionare il menu con il valore che mi interessava.

Dopo un po’ di ricerche molti hanno avuto il mio stesso problema e quindi ho deciso di postare la soluzione per altro semplice. Si presume che il controllo menu nel form si chiami Menu1.

   1:  Dim mi As MenuItem = Me.Menu1.FindItem(Request.QueryString("VoceMenu"))
   2:  mi.Selected = True

Buon lavoro a tutti!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by enrico on Thursday, January 22, 2009 3:42 PM
Permalink | Comments (0) | Post RSSRSS comment feed