Click here to Skip to main content
15,893,588 members

Object reference not set to an instance of an object.

Shingala Anil asked:

Open original thread
Hello,


UploadCS.ascx File Code:

C#
<%@ WebHandler Language="C#" Class="UploadCS" %>
using System;
using System.Web;
using System.IO;
using System.Web.SessionState;
using System.Collections.Generic;
public class UploadCS : IHttpHandler, IRequiresSessionState {
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Expires = -1;
        try
        {
            List<httppostedfile> files = (List<httppostedfile>)context.Session["Files"];
            HttpPostedFile postedFile = context.Request.Files["Filedata"];
            files.Add(postedFile);
            string filename = postedFile.FileName;
            context.Response.Write(filename);
            context.Response.StatusCode = 200;
        }
        catch (Exception ex)
        {
            context.Response.Write("Error: " + ex.Message);
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}

.CS File Code

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Configuration;
using System.Net.Mail;
using System.IO;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["Files"] = new List<httppostedfile>();
        }
    }

    protected void btnSend_Click(object sender, EventArgs e)
    {
        using (MailMessage mailMessage = new MailMessage())
        {
            mailMessage.From = new MailAddress("user@gmail.com");
            mailMessage.Subject = txtSubject.Text.Trim();
            mailMessage.Body = txtBody.Text.Trim();
            mailMessage.IsBodyHtml = true;
            mailMessage.To.Add(new MailAddress(txtTo.Text.Trim()));
            List<httppostedfile> files = (List<httppostedfile>)Session["Files"];
            foreach (HttpPostedFile file in files)
            {
                mailMessage.Attachments.Add(new Attachment(file.InputStream, Path.GetFileName(file.FileName), file.ContentType));
            }

            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
            NetworkCred.UserName = mailMessage.From.Address;
            NetworkCred.Password = "<password>";
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = 587;
            smtp.Send(mailMessage);
        }
        Response.Redirect(Request.Url.AbsoluteUri);
    }

    [WebMethod]
    public static void RemoveFile(string fileName)
    {
        List<httppostedfile> files = (List<httppostedfile>)HttpContext.Current.Session["Files"];
        files.RemoveAll(f => f.FileName.ToLower().EndsWith(fileName.ToLower()));
    }
}


.aspx File code

XML
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
        input[type=text]{width:250px}
        textarea{width:250px;height:150px}
    </style>
    <link rel="Stylesheet" type="text/css" href="CSS/uploadify.css" />
    <script type="text/javascript" src="scripts/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="scripts/jquery.uploadify.js"></script>
    <script type="text/javascript">
        $(function () {
            $("[id*=FileUpload1]").fileUpload({
                'uploader': 'scripts/uploader.swf',
                'cancelImg': 'images/cancel.png',
                'buttonText': 'Attach Files',
                'script': 'UploadCS.ashx',
                'folder': 'uploads',
                'multi': true,
                'auto': true,
                'onSelect': function (event, ID, file) {
                    $("#attachedfiles tr").each(function () {
                        if ($("td", this).eq(0).html() == file.name) {
                            alert(file.name + " already uploaded.");
                            $("[id*=FileUpload1]").fileUploadCancel(ID);
                            return;
                        }
                    });
                },
                'onComplete': function (event, ID, file, response, data) {
                    $("#attachedfiles").append("<tr><td>" + file.name + "</td><td><a href = 'javascript:;'>[x]</a></td></tr>");
                }
            });
        });

        $("#attachedfiles a").live("click", function () {
            var row = $(this).closest("tr");
            var fileName = $("td", row).eq(0).html();
            $.ajax({
                type: "POST",
                url: "CS.aspx/RemoveFile",
                data: '{fileName: "' + fileName + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () { },
                failure: function (response) {
                    alert(response.d);
                }
            });
            row.remove();
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <table>
    <tr><td>To:</td><td><asp:TextBox ID="txtTo" runat="server"></asp:TextBox></td></tr>
    <tr><td>Subject:</td><td><asp:TextBox ID="txtSubject" runat="server"></asp:TextBox></td></tr>
    <tr><td>Body:</td><td><asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine"></asp:TextBox></td></tr>
    <tr><td></td><td><asp:FileUpload ID="FileUpload1" runat="server"/></td></tr>
    <tr><td></td><td><table id="attachedfiles"></table></td></tr>
    <tr><td></td><td><asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click"/></td></tr>
    </table>
    </form>
</body>
</html>



i cant get value in code behind session variable and also error in .ascx file when we add files object.

[edit]Code blocks added - OriginalGriff[/edit]
Tags: C#, Visual Basic, ASP.NET

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900