Exception error
Hey guys,
I have a form where the user uploads their documents. The issue is that there are times when the following error occurs:
Object reference not defined for an instance of an object.
Description: An untreated exception occurred during the execution of the current web request. Examine stack tracking for more information about the error and where it originated in the code.
Out of Exception: System.NullReferenceException: Object reference not defined for an instance of an object.
Error of Origin:
Exception without treatment was generated during the execution of the current web request. Information related to the source and the location of the exception can be identified using the exception stack tracking below.
Tracking of the Pile:
[NullReferenceException: Referência de objeto não definida para uma instância de um objeto.] aluno_Anexos.SalvaArquivoBanco(FileUpload pFileUpload, Int32 pTipoDoc) in C:\Users\Ilano\AppData\Local\Temp\WebSitePublish\CVTWEB-928806625\obj\Debug\AspnetCompileMerge\Source\aluno\Anexos.aspx.vb:117 aluno_Anexos.BtnEnviar_Click(Object sender, EventArgs e) in C:\Users\Ilano\AppData\Local\Temp\WebSitePublish\CVTWEB-928806625\obj\Debug\AspnetCompileMerge\Source\aluno\Anexos.aspx.vb:248 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +11594515 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +273 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1889
Follow the HTML of the aspx page:
<%@ Page Title="" Language="VB" MasterPageFile="~/aluno/MasterPage.master" AutoEventWireup="false" CodeFile="Anexos.aspx.vb" Inherits="aluno_Anexos" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<ajaxToolkit:ModalPopupExtender ID="mpeImgJpeg" runat="server" PopupControlID="panImgJpeg" TargetControlID="BtnImgOculto" CancelControlID="BtnFechaImg" BackgroundCssClass="fundo-fosco" DropShadow="true">
</ajaxToolkit:ModalPopupExtender>
<ajaxToolkit:ModalPopupExtender ID="mpeExclusao" runat="server" PopupControlID="panExclusao" TargetControlID="BtnExcluirOculto" CancelControlID="BtnCancelaExclusao" BackgroundCssClass="fundo-fosco" DropShadow="true">
</ajaxToolkit:ModalPopupExtender>
<div style="display:none;">
<asp:Button ID="BtnExcluirOculto" runat="server" Text="Abre alerta" />
<asp:Button ID="BtnImgOculto" runat="server" Text="Abre alerta" />
</div>
<div>
<asp:Panel ID="panImgJpeg" runat="server" CssClass="alert alert-info" Style="padding:10px !important; background-color:#FFF; display:none;" >
<div class="form-group">
<div class="row">
<div class="col-sm-11">
<h3>Visualização de Imagem</h3>
</div>
<div class="col-sm-1">
<div style="text-align:right;"><asp:Button ID="BtnFechaImg" runat="server" CssClass="btn btn-danger btn-sm" Text="X" /></div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-panel">
<div style="overflow:scroll; height:400px;"><asp:Image ID="imgJpeg" runat="server" CssClass="figure-img" /></div>
</div>
</div>
</div>
</div>
</asp:Panel>
</div>
<div>
<asp:Panel ID="panExclusao" runat="server" CssClass="alert alert-danger" Style="padding:10px !important; background-color:#FFF; display:none;" >
<div class="form-group">
<div class="row">
<div class="col-sm-12">
<div><h3>Exclusão</h3></div>
<hr />
<div>
<asp:HiddenField ID="hfIDExclusao" runat="server" />
<asp:Label ID="LbExclusao" runat="server" ></asp:Label>
</div>
<hr />
<div style="text-align:center;">
<asp:Button ID="BtnExcluir" runat="server" CssClass="btn btn-danger" style="margin-right:5px;" Text="Excluir" />
<asp:Button ID="BtnCancelaExclusao" runat="server" CssClass="btn btn-secondary" Text="Cancelar" />
</div>
</div>
</div>
</div>
</asp:Panel>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-12">
<h3>Anexos</h3>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div><asp:Label ID="LbPessoa" runat="server" ></asp:Label></div>
<div><asp:Label ID="LbAnexo" runat="server" ></asp:Label></div>
<div><asp:HiddenField ID="hfID" runat="server" /></div>
<div></div>
</div>
</div>
<div class="row" style="margin-top:20px !important;">
<div class="col-sm-12">
<div>Tipo do documento:*</div>
<div><asp:DropDownList ID="ComboTipoDocumento" runat="server" CssClass="form-control" DataValueField="ID" DataTextField="NOME" ></asp:DropDownList></div>
<div style="margin-top:10px;">Selecione um arquivo apenas com <b>extensão .pdf, .jpg ou .jpeg</b>. O tamanho do arquivo deve ser de <b>130.000 bytes</b>.</div>
<div>
<asp:Panel ID="panFU" runat="server" CssClass="form-panel">
<asp:FileUpload ID="FileUpload1" runat="server" />
</asp:Panel>
</div>
<div><asp:Label ID="ContaObrigatorios" runat="server" ></asp:Label></div>
<div style="margin-top:10px;">
<asp:Button ID="BtnEnviar" runat="server" CssClass="btn btn-info" style="margin-right:5px;" Text="Enviar" />
<asp:Button ID="BtnSair" runat="server" CssClass="btn btn-danger" Text="Sair" />
</div>
</div>
</div>
<div class="row" style="margin-top:20px !important;">
<div class="col-sm-12">
<asp:DataGrid ID="DataGrid1" runat="server" AutoGenerateColumns="False" CssClass="gGrid">
<AlternatingItemStyle CssClass="gGridAlternate" />
<Columns>
<asp:BoundColumn DataField="ID" HeaderText="ID" Visible="False"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="TIPO DOCUMENTO">
<ItemTemplate>
<asp:Label ID="gLbTipoDocumento" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.DOCUMENTO") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="DOCUMENTO">
<ItemTemplate>
<asp:Label ID="gLbNomeArquivo" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.NOMEARQUIVO") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<asp:ImageButton ID="gBtnExcluir" runat="server" CommandName='<%# "Delete" %>' ImageUrl="~/imagens/BtnExclui.png" />
</ItemTemplate>
<HeaderStyle Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" HorizontalAlign="Center" />
<ItemStyle Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" HorizontalAlign="Center" />
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<asp:ImageButton ID="BtnVisualizarImg" runat="server" ImageUrl="~/imagens/BtnConsulta.png" CommandName='<%# "verImagem" %>' />
</ItemTemplate>
<HeaderStyle Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" HorizontalAlign="Center" />
<ItemStyle Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" HorizontalAlign="Center" />
</asp:TemplateColumn>
</Columns>
<HeaderStyle CssClass="gGridHeader" />
</asp:DataGrid>
</div>
</div>
</div>
</asp:Content>
And the VB code:
Imports System.Diagnostics
Imports System.IO
Imports System.IO.Directory
Imports System.IO.Stream
Partial Class aluno_Anexos
Inherits System.Web.UI.Page
Private Pessoas As New DETI.objPessoas
Private Anexos As New DETI.objPessoasAnexos
Private TipoDocumento As DETI.objTipoDocumentos
Private Fn As New Funcoes.classFuncao
Function ImageToBase64(ByVal pPath As String) As String
Dim pCaminho As String = Fn.PegandoDiretorioDoArquivo(pPath)
Dim base64String As String
Using image As System.Drawing.Image = System.Drawing.Image.FromFile(pCaminho)
Using m As MemoryStream = New MemoryStream()
image.Save(m, image.RawFormat)
Dim imageBytes As Byte() = m.ToArray()
base64String = Convert.ToBase64String(imageBytes)
Return base64String
End Using
End Using
End Function
Function Base64ToImage(ByVal pBase64String As String) As System.Drawing.Image
Dim imageBytes As Byte() = Convert.FromBase64String(pBase64String)
Dim ms As MemoryStream = New MemoryStream(imageBytes, 0, imageBytes.Length)
ms.Write(imageBytes, 0, imageBytes.Length)
Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(ms, True)
Return image
End Function
Private Sub AbrirImagem(ByVal pString As String)
Base64ToImage(pString).Save(Server.MapPath("~/imagens/Hello.jpg"))
'Image1.ImageUrl = "~/imagens/Hello.jpg"
End Sub
Function CheckFileExtensions(ByVal FileName As String) As Boolean
Dim pTamanhoNome As Integer
If String.IsNullOrEmpty(FileName) Then Return False
Dim extension As String = FileName.Substring(FileName.LastIndexOf(".") + 1)
pTamanhoNome = TamanhoArquivo(Trim(FileName)) 'Pega o tamanho do arquivo.
If extension = "jpg" OrElse extension = "jpeg" OrElse extension = "pdf" Then
'If pTamanhoNome > 0 And pTamanhoNome < 80 Then Return True Else Return False
Return True
Else
Return False
End If
End Function
Function TamanhoArquivo(ByVal pNome As String) As Integer
Dim Ds As Data.DataSet
Dim I As Integer
I = 0
Ds = Anexos.TamanhoArquivo(pNome)
If Not Ds Is Nothing Then
If Ds.Tables(0).Rows.Count > 0 Then I = Ds.Tables(0).Rows(0)("TAMANHO") Else I = 0
Else
If Ds Is Nothing Then
I = 0
End If
End If
Return I
End Function
Private Sub VisualizarArquivo(ByVal pNomeArquivo As String, ByVal pArquivo As Byte())
Try
Dim arquivoTemp = Path.GetTempFileName()
arquivoTemp = Path.ChangeExtension(arquivoTemp, Path.GetExtension(pNomeArquivo))
File.WriteAllBytes(arquivoTemp, pArquivo)
Process.Start(arquivoTemp)
Catch ex As Exception
Fn.Alerta(ex.Message, Page)
End Try
End Sub
Private Sub ExibeImagemJpg(ByVal pNomeArquivo As String, ByVal pArquivo As Byte())
imgJpeg.ImageUrl = "data:image/jpg;base64," & Convert.ToBase64String(CType((pArquivo), Byte()))
'LbNomeImgJpeg.Text = pNomeArquivo
mpeImgJpeg.Show()
End Sub
Private Sub DownloadPDF(ByVal pNomeArquivo As String, ByVal pArquivo As Byte())
Response.Clear()
Response.Buffer = True
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=" & pNomeArquivo)
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.BinaryWrite(CType(pArquivo, Byte()))
Response.[End]()
End Sub
Function SalvaArquivoBanco(ByVal pFileUpload As WebControls.FileUpload, ByVal pTipoDoc As Integer) As String
Dim pMsg As String = DBNull.Value.ToString
Dim pTamDoc As Integer = TipoDocumento.TamanhoDoc(pTipoDoc)
If pFileUpload.HasFile Then
If CheckFileExtensions(pFileUpload.FileName) = True Then
Dim pArquivo As Byte() = pFileUpload.FileBytes
Dim pTipo As String = pFileUpload.PostedFile.ContentType
Dim pTamanho As Long = pFileUpload.PostedFile.ContentLength
Dim pNomeArquivo As String = pFileUpload.PostedFile.FileName
Dim pExtensao As String = System.IO.Path.GetExtension(pNomeArquivo).ToLower()
If pTamanho > 0 And pTamanho < pTamDoc Then
With Anexos
.ID = 0
.PESSOAID = Session("sPessoaID") 'hfID.Value
.TIPODOCUMENTOID = pTipoDoc
.DIRETORIOFISICO = Trim("-")
.DIRETORIOVIRTUAL = Trim("-")
.NOMEARQUIVO = Trim(pNomeArquivo)
.EXTENSAO = Trim(pExtensao)
.ARQUIVOIMAGEM = pArquivo
.TAMANHOIMAGEM = pTamanho
.USUARIO = Session("sUsuario")
End With
If pExtensao = ".jpg" Then
pMsg = "<div class='alert alert-info' style='margin:10px 0px 10px 0px;'>" & Anexos.Inserir() & "</div>"
Else
If pExtensao = ".jpeg" Then
pMsg = "<div class='alert alert-info' style='margin:10px 0px 10px 0px;'>" & Anexos.Inserir() & "</div>"
Else
If pExtensao = ".pdf" Then
pMsg = "<div class='alert alert-info' style='margin:10px 0px 10px 0px;'>" & Anexos.Inserir() & "</div>"
Else
pMsg = "<div style='color: #721c24;'>O sistema não aceita arquivos com estensão " & pExtensao & ".</div>"
End If
End If
End If
Else
If pTamanho >= pTamDoc Then
pMsg = "<div class='alert alert-danger' style='margin:10px 0px 10px 0px;'>A imagem " & pNomeArquivo & " é muito grande " & pTamanho & " bytes.<br />O arquivo deve ser menor que " & pTamDoc & " bytes.</div>"
End If
End If
Else
If CheckFileExtensions(pFileUpload.FileName) = False Then
pMsg = "<div class='alert alert-danger' style='margin:10px 0px 10px 0px;'>Só é possível armazenar arquivos com extensão .pdf, .jpg ou .jpeg.</div>"
End If
End If
End If
Return pMsg
End Function
Private Sub ContarObrigatorios()
Dim Ds As Data.DataSet
Ds = Anexos.ConsultaGenerica(" SELECT CONTAR = (SELECT COUNT(*) FROM TIPOSDOCUMENTOS WHERE OBRIGATORIO = 'True') - " &
" (SELECT COUNT(*) FROM PESSOASDOCUMENTOS X " &
" INNER JOIN TIPOSDOCUMENTOS Z ON (Z.ID = X.TIPODOCUMENTOID) " &
" WHERE Z.OBRIGATORIO = 'True' AND X.PESSOAID = " & Session("sPessoaID") & ") ")
If Not Ds Is Nothing Then
If Ds.Tables(0).Rows.Count > 0 Then
If Ds.Tables(0).Rows(0)("CONTAR") > 0 Then ContaObrigatorios.Text = "<div class='alert alert-danger' style='margin:20px 0px 20px 0px !important;'>Você tem " & Ds.Tables(0).Rows(0)("CONTAR") & " documento(s) obrigatório(s) para anexar.</div>" Else ContaObrigatorios.Text = ""
End If
End If
End Sub
Private Sub RecebeParametros()
If Not Request("pComp") Is Nothing Then
ViewState("vlComp") = Request("pComp")
Else
If Request("pComp") Is Nothing Then
ViewState("vlComp") = "False"
End If
End If
End Sub
Private Sub PovoaTipoDocumento()
Dim Ds As Data.DataSet
Ds = Anexos.ConsultaGenerica(" SELECT A.ID, NOME = CASE WHEN A.OBRIGATORIO = 'True' THEN A.NOME + ' (Obrigatório)' ELSE A.NOME END " &
" FROM TIPOSDOCUMENTOS A " &
" WHERE A.GRUPOPESSOA = 1 " &
" AND A.ID Not IN (SELECT X.TIPODOCUMENTOID " &
" FROM PESSOASDOCUMENTOS X " &
" WHERE X.PESSOAID = " & Session("sPessoaID") & ") " &
" ORDER BY A.NOME ")
ComboTipoDocumento.DataSource = Ds
ComboTipoDocumento.DataBind()
ComboTipoDocumento.Items.Insert(0, New ListItem("--SELECIONE--", "0"))
End Sub
Private Sub PovoaGrid()
Dim Ds As Data.DataSet
Ds = Anexos.ConsultaAvancada(" A.PESSOAID = " & Session("sPessoaID"), "")
DataGrid1.DataSource = Ds
DataGrid1.DataBind()
ContarObrigatorios()
End Sub
Protected Sub BtnEnviar_Click(sender As Object, e As EventArgs) Handles BtnEnviar.Click
Dim I As Integer = 0
If ComboTipoDocumento.SelectedValue = 0 Then
I = I + 1
ComboTipoDocumento.CssClass = "form-control Is-invalid"
Else
If ComboTipoDocumento.SelectedValue > 0 Then
ComboTipoDocumento.CssClass = "form-control"
End If
End If
If Not FileUpload1.HasFile Then
I = I + 1
panFU.CssClass = "form-panel Is-invalid"
Else
If FileUpload1.HasFile Then
panFU.CssClass = "form-panel"
End If
End If
If I = 0 Then
LbAnexo.Text = SalvaArquivoBanco(FileUpload1,
ComboTipoDocumento.SelectedValue)
PovoaGrid()
PovoaTipoDocumento()
Else
If I > 0 Then
LbAnexo.Text = "<div class='alert alert-danger' " &
" style='margin:10px 0px 10px 0px;'>Por favor, preencha todos os campos corretamente.</div>"
End If
End If
End Sub
Function DadosSelecionados(ByVal pID As Integer) As String
Dim Ds As Data.DataSet
Dim pTipo As String = ""
Dim pDocumento As String = ""
Dim pDados As String = ""
Ds = Anexos.ConsultaAvancada(" A.ID = " & pID, "")
If Not Ds Is Nothing Then
If Ds.Tables(0).Rows.Count > 0 Then
pTipo = Ds.Tables(0).Rows(0)("DOCUMENTO")
pDocumento = Ds.Tables(0).Rows(0)("NOMEARQUIVO")
pDados = "<b>Tipo do Documento:</b><br />" & pTipo & "<br /><b>Nome do Arquivo:</b><br />" & pDocumento & "<br />"
Else
If Ds.Tables(0).Rows.Count = 0 Then
pDados = ""
End If
End If
Else
If Ds Is Nothing Then
pDados = ""
End If
End If
Return pDados
End Function
Private Sub DataGrid1_ItemCommand(source As Object, e As DataGridCommandEventArgs) Handles DataGrid1.ItemCommand
If e.CommandName = "verImagem" Then
DataGrid1.CurrentPageIndex = 0
Dim Ds As Data.DataSet
Ds = Anexos.Consultar(" ID = " & e.Item.Cells(0).Text, "")
If Not Ds Is Nothing Then
If Ds.Tables(0).Rows.Count > 0 Then
If Ds.Tables(0).Rows(0)("EXTENSAO") = ".pdf" Then
VisualizarArquivo(Ds.Tables(0).Rows(0)("NOMEARQUIVO"), Ds.Tables(0).Rows(0)("ARQUIVOIMAGEM"))
Else
If Ds.Tables(0).Rows(0)("EXTENSAO") = ".jpg" Then
ExibeImagemJpg(Ds.Tables(0).Rows(0)("NOMEARQUIVO"), Ds.Tables(0).Rows(0)("ARQUIVOIMAGEM"))
Else
If Ds.Tables(0).Rows(0)("EXTENSAO") = ".jpeg" Then
ExibeImagemJpg(Ds.Tables(0).Rows(0)("NOMEARQUIVO"), Ds.Tables(0).Rows(0)("ARQUIVOIMAGEM"))
End If
End If
End If
End If
End If
Else
If e.CommandName = "Delete" Then
DataGrid1.CurrentPageIndex = 0
hfIDExclusao.Value = e.Item.Cells(0).Text
LbExclusao.Text = "Tem certeza de que deseja excluir o registro:<br /><br />" &
DadosSelecionados(e.Item.Cells(0).Text)
mpeExclusao.Show()
End If
End If
End Sub
Private Sub DataGrid1_ItemCreated(sender As Object, e As DataGridItemEventArgs) Handles DataGrid1.ItemCreated
If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then
e.Item.Attributes.Add("onMouseOver", "selecionaGrid(this)")
e.Item.Attributes.Add("onMouseOut", "deSelecionaGrid(this)")
e.Item.Style("cursor") = "hand" ' Cursor vira uma mãozinha
End If
End Sub
Private Sub aluno_Anexos_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
hfIDExclusao.Value = 0
hfID.Value = 0
RecebeParametros()
PovoaTipoDocumento()
PovoaGrid()
End If
End Sub
Protected Sub BtnExcluir_Click(sender As Object, e As EventArgs) Handles BtnExcluir.Click
Anexos.ExecutaSQLGenerica(" DELETE FROM PESSOASDOCUMENTOS " &
" WHERE ID = " & hfIDExclusao.Value &
" AND PESSOAID = " & Session("sPessoaID"))
LbExclusao.Text = DBNull.Value.ToString
hfIDExclusao.Value = 0
PovoaGrid()
End Sub
Protected Sub BtnSair_Click(sender As Object, e As EventArgs) Handles BtnSair.Click
Response.Redirect("index.aspx")
End Sub
End Class
What that happens is taking the directory from the development environment, instead of the server environment?
Grateful,
Ilano