Solved

Can a stream be opened for reading after it is read once?

Posted on 2006-07-13
33
224 Views
Last Modified: 2008-01-09
I am using Visual Studio .NET 2002 and ASP.NET.
I am using a StreamReader to read the contents fo a stream.
I want to find out if a stream can be opened for reading again after it is read once.

Thanks.
0
Comment
Question by:balabommala
  • 18
  • 15
33 Comments
 

Author Comment

by:balabommala
ID: 17102734
Increasing points because of urgency
0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 17104139
I do not think so. Once the stream has been read, you have to open the file handle again to read it. What you are trying to achieve?

-Nauman.
0
 

Author Comment

by:balabommala
ID: 17105023
I am trying to upload a .csv file to the dB. I don't have permissions to upload it to the webserver. So I used the InputStream property of the PostedFile

I have a HtmlInputFile control. Here is the code:
System.IO.Stream myStream
myStream = UploadFile.PostedFile.InputStream;
bll.Import bllImp = new bll.Import();
DataTable errorData = bllImp.ValidateFile(myStream);
int totalRecords = bllImp.TotalFile(myStream);
int recordsUploaded = bllImp.UploadFile(myStream);

So I have to use myStream 3 times.

How do I open the file handle to read it.

Thanks for your help.


0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 17108329
Where is this bll.Import class declared. Instead of using three methods, pass the stream to the class constructor and then declare methods to determine if the file is valid and what is the total size of the file and a method to upload the file when valid. Something like the following:

Public Class Import
   
    'Global Variables
    Private _fileStream As Stream
   
    'Default constructor
    Public Sub New()
        MyBase.New
       
    End Sub
   
    Public Sub New(ByVal fileStream As Stream)
        MyBase.New
        Me._fileStream = fileStream
    End Sub
   
    Public Function ValidateStream() As Boolean
        Dim isFileValid As Boolean = false
        If (Me._fileStream = Nothing) Then
            Throw New Exception("Stream is not valid")
        Else
            'Validate file
        End If
        Return isFileValid
    End Function
   
    Public Function GetRecordCount() As Integer
        Dim recordCount As Integer = 0
        If (Me.ValidateStream = true) Then
            ' get record count
        End If
        Return recordCount
    End Function
   
    Public Function UploadFile() As Boolean
        Dim fileUploaded As Boolean = false
        If (Me.ValidateStream = true) Then
            'upload file
            fileUploaded = true
        End If
        Return fileUploaded
    End Function
End Class



--Nauman.
0
 

Author Comment

by:balabommala
ID: 17108544
The code I wrote is in the code-behind layer.
I have to pass the stream from code-behind to BLL(ofcourse to all those 3 methods).
How do I do that?

Thanks.
0
 

Author Comment

by:balabommala
ID: 17108660
Increasing point because of urgency
0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 17108772
As I said, modify your class constructor and pass the stream as a parameter to it like this:

Public Sub New(ByVal fileStream As Stream)
        MyBase.New
        Me._fileStream = fileStream
    End Sub

Once you have passed the stream as a parameter it will be available to all the methods in the class as long as your dispose the class.


in .aspx.vb
-------------
System.IO.Stream myStream
myStream = UploadFile.PostedFile.InputStream;
Import bllImp = new Import(myStream)

-Nauman.
0
 

Author Comment

by:balabommala
ID: 17108941
I have to use the call the methods (that are in BLL) in DAL also.
How should I do that?
Sorry I am dumb and in the process of learning things.

Thanks.
0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 17109030
ok lets move step by step then :)

Take backup of existing project.
Modify your class
 - Add Private _fileStream As Stream as a global variable
 - Modify constructor as I stated so that it accept a stream parameter
 - Modify ValidateFile, TotalFile, and UploadFile methods so that they use _fileStream variable.

Let me know when this is done.

--Nauman.
 
0
 

Author Comment

by:balabommala
ID: 17109056
They are done:
But you know what? In my UploadFile method, I am trying to read the stream using StreamReader and it gives me a nullvalue exception.
0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 17109155
Are you sure that the stream parameter is passed to the constructor and you have assigned the _fileStream parameter like this:

Public Sub New(ByVal fileStream As Stream)
        MyBase.New
        Me._fileStream = fileStream
    End Sub

-Nauman.
0
 

Author Comment

by:balabommala
ID: 17109220
Yes.

Here is the code:

aspx.cs:
BLL.Import bllImport = new BLL.Import(uploadStream);
int recordsUploaded = bllImport.UploadCSVFile(filename);
int totalRecords = bllImport.TotalCSVFile(filename);
DataTable errorData = bllImport.ValidateCSVFile(filename);

bll:
public class Import
{
        private Stream St;
        public Import()
        { }
        public Import(Stream uploadStream)
        {
            St = uploadStream;
        }

   .......
}


Thanks.
0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 17109313
Ok you should have told me that you are working in C# :) I had to convert the example code to C# earlier.

Can you please post the complete code?

-Nauman.
0
 

Author Comment

by:balabommala
ID: 17109455
Here it is:
aspx.cs:
System.IO.Stream uploadStream =UploadFile.PostedFile.InputStream;
string file_client = UploadFile.PostedFile.FileName;
string filename = System.IO.Path.GetFileName(file_client);
 BLL.Import bllImport = new BLL.Import(uploadStream);
int recordsUploaded = bllImport.UploadCSVFile(filename);
int totalRecords = bllImport.TotalCSVFile(filename);
DataTable errorData = bllImport.ValidateCSVFile(filename);

bll:
public class Import
{
        private Stream St;
        public Import()
        { }
        public Import(Stream uploadStream)
        {
            St = uploadStream;
        }

................ Those 3 methods here.
}
 

Thanks.
0
 

Author Comment

by:balabommala
ID: 17110479
I am assuming that the code I posted in my previous post is enough or do you need the complete one?

Thanks.
0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 17111741
balabommala,

Please post complete code.

Thanks,
Nauman.
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

Author Comment

by:balabommala
ID: 17122369
Here is the complete code:

Code-behind page:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;


public partial class ImportERVMail : System.Web.UI.Page
{
   
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
   
    protected void Button2_Click(object sender, EventArgs e)
    {
        try
        {
            string file_client = UploadFile.PostedFile.FileName;
            string filename = System.IO.Path.GetFileName(file_client);
            if ( filename.EndsWith(".csv") && (filename.StartsWith("T")||filename.StartsWith("H")) )
            {
               
                Stream uploadStream =UploadFile.PostedFile.InputStream;
                Label4.Visible = false;
                Label5.Visible = false;
                BLL.Import bllImport = new BLL.Import(uploadStream);
                int recordsUploaded = bllImport.UploadCSVFile(filename);
                int totalRecords = bllImport.TotalCSVFile(filename);
                DataTable errorData = bllImport.ValidateCSVFile(filename);
                DataView dv = new DataView(errorData);
                Label1.Text = recordsUploaded + " record(s) uploaded successfully";
                if (errorData.Rows.Count != 0)
                {
                    dgErrors.Enabled = true;
                    dgErrors.Visible = true;
                    dgErrors.DataSource = dv;
                    dgErrors.DataBind();
                }
                else
                {
                    dgErrors.Visible = false;
                    dgErrors.Enabled = false;
                }
                int dupRecords = totalRecords - recordsUploaded - errorData.Rows.Count;
                Label2.Text = " Error record(s): " + errorData.Rows.Count + "        Duplicate Record(s): " + dupRecords + "        Total Record(s): " + totalRecords;
               
               
            }
            else
            {
                displayError("Data is not imported", "Please select a capital T or H .csv file");
               
            }
        }
        catch (Exception e1)
        {
            Label1.Text = e1.ToString();
        }
        finally
        {
            dgErrors.Dispose();
            UploadFile.PostedFile.InputStream.Flush();
        }
    }

    private void displayError(string errorName, string errorDescription)
    {
        dgErrors.Visible = false;
        dgErrors.Enabled = false;
        Label1.Visible = true;
        Label2.Visible = true;
        Label1.Text = errorName;
        Label2.Text = errorDescription;
    }
       
}


Business Layer:


using System;
using System.IO;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using netma21.Model;
using netma21.IDAL;

namespace BLL
{
      /// <summary>
      /// Summary description
      /// </summary>
      public class Import
      {
        private Stream St;
        public Import()
        {
           
        }
        public Import(Stream uploadStream)
        {
            St = uploadStream;
        }
      public int UploadCSVFile( string csvFile )
      {      
            // Get an instance of the Disposition DAL using the DALFactory
            IImport dal = netma21.DALFactory.Import.Create();                  
            return dal.UploadCSVFile(csvFile);
      }

        /// <summary>
        /// Total Records
        /// </summary>
        /// <param name="csvFile"></param>
        /// <returns></returns>
       
        int totalRecords = 0;
        public int TotalCSVFile(string csvFile)
        {
            //File Validations
            if (!IsCsvFileValid(csvFile))
            {
                totalRecords = 0;
                return totalRecords;
            }
            int total = 0;
            if (St == null)
            {
            }
            System.IO.StreamReader Sr = new StreamReader(St);
            string CurrentLine = string.Empty;
            string[] values = null;
            try
            {
                while (Sr.Peek() >= 0)
                {
                    CurrentLine = Sr.ReadLine();
                    values = CurrentLine.Split(',');
                              if (values[0] != "MEC" &&
                            (values[0] != string.Empty && values[1] != string.Empty && values[2] != string.Empty))
                    {
                        total++;
                    }                                    
                }
            }
            catch(Exception ex)
                  {
                        throw ex;
                  }
                  finally
                  {
                        
                  }
            return total;
        }
            
        /// <summary>
            /// Records with invalid values
            /// </summary>
            /// <param name="csvFile"></param>
            /// <returns></returns>
        DataTable dt = new DataTable();
        public DataTable ValidateCSVFile(string csvFile)
            {

            if (!IsCsvFileValid(csvFile))
                  {      
                      return null;
                  }
                                                      
                  dt.Columns.Add(new DataColumn("Error", typeof(string)));
                  dt.Columns.Add(new DataColumn("MEC", typeof(string)));
                  dt.Columns.Add(new DataColumn("CAT", typeof(string)));
                  dt.Columns.Add(new DataColumn("SSN", typeof(string)));
                  dt.Columns.Add(new DataColumn("WKR1", typeof(string)));
                  dt.Columns.Add(new DataColumn("STA", typeof(string)));
                  dt.Columns.Add(new DataColumn("AR", typeof(string)));
                  dt.Columns.Add(new DataColumn("GRP", typeof(string)));
                  //dt.Columns.Add(new DataColumn("LastName", typeof(string)));
                  //dt.Columns.Add(new DataColumn("FirstName", typeof(string)));
                  //dt.Columns.Add(new DataColumn("Address", typeof(string)));
                  //dt.Columns.Add(new DataColumn("City", typeof(string)));
                  //dt.Columns.Add(new DataColumn("State", typeof(string)));
                  //dt.Columns.Add(new DataColumn("Zip", typeof(string)));
                  dt.Columns.Add(new DataColumn("DOB", typeof(string)));
                  dt.Columns.Add(new DataColumn("Sent&nbsp;Date", typeof(string)));
                  DataTable errorData = ShowError(csvFile);
                  return errorData;
            }
            
            /// <summary>
            /// Validations for CSV File
            /// </summary>
            /// <param name="csvFile"></param>
            /// <returns></returns>
        private DataTable ShowError(string csvFile)
            {
                  int k=1;
                  bool IsTfile = false;
            System.IO.StreamReader Sr = new StreamReader(St);
                  string CurrentLine      = string.Empty;
                  string[] values            = null;
                  CsvFileRecordInfoCollection CsvFileRecordInfoColl = new CsvFileRecordInfoCollection();
                  //FileInfo CsvFi = new FileInfo(csvFile);
                  if(csvFile.StartsWith ("T"))
                        IsTfile = true;

                  try
                  {
                        while (Sr.Peek() >= 0  )
                        {
                              CurrentLine      = Sr.ReadLine();
                              int d;
                              values=CurrentLine.Split(',');
                              for(d=values.Length;d<27;d++)
                              {
                                    CurrentLine = CurrentLine.Insert(CurrentLine.Length,",");
                              }
                              values      = CurrentLine.Split(',');

                              DateTime tom = new DateTime(1900,1,1);
                              if(IsTfile)      //T File Sequence
                              {
                       
                                    if ( values[0] != "MEC" &&
                                          (values[0] != "" && values[1] != string.Empty && values[2] != string.Empty) )
                                          
                                    {
                                    
                                          if(values[2].Length !=9 ||
                                                !IsDate(values[13])||
                                                !IsDate(values[17]))
                                          {
                                                
                                                DataRow drow;
                                                drow =dt.NewRow();
                                                drow[0] = "Line&nbsp"+k.ToString();
                                                drow[1] = values[0];
                                                drow[2] = values[1];
                                                drow[3] = values[2].ToString();
                                                drow[4] = values[3];
                                                drow[5] = values[4];
                                                drow[6] = values[5];                                                            
                                                drow[7] = values[6];
                                                //drow[8] = values[7];
                                                //drow[9] = values[8];
                                                //drow[10] = values[9];
                                                //drow[10] = values[10];
                                                //drow[11] = values[11];
                                                //drow[12] = values[12];
                                                drow[8] = values[13];
                                                drow[9] = values[17];                                                            
                                                dt.Rows.Add(drow);
                                                
                                          }
                                          k++;
                                    }
                              }
                              else      // H File
                              {
                                    
                                    if ( values[0] != "MEC" &&
                                          (values[0] != "" && values[1] != string.Empty && values[2] != string.Empty) )
                                          
                                    {
                                    
                                          if(values[2].Length !=9 ||
                                                !IsDate(values[14])||
                                                !IsDate(values[17]))
                                          {
                                                
                                                DataRow drow;
                                                drow =dt.NewRow();
                                                drow[0] = "Line&nbsp"+k.ToString();
                                                drow[1] = values[0];
                                                drow[2] = values[1];
                                                drow[3] = values[2].ToString();
                                                drow[4] = values[3];
                                                drow[5] = values[4];
                                                drow[6] = values[5];                                                            
                                                drow[7] = values[6];
                                                //drow[8] = values[7];
                                                //drow[9] = values[8];
                                                //drow[10] = values[9];
                                                //drow[10] = values[10];
                                                //drow[11] = values[11];
                                                //drow[12] = values[12];
                                                drow[8] = values[14];
                                                drow[9] = values[17];                                                            
                                                dt.Rows.Add(drow);
                                                
                                          }
                                          k++;
                                    }
                              }
                              
                        }
                        
                  }
                  catch(Exception ex)
                  {
                        throw ex;
                  }
                  finally
                  {
                Sr.Close();
                Sr = null;
           
                  }
                  return dt;                        
            }

        /// <summary>
        /// Iterate through CSV file and create csvobj for each line.
        /// </summary>
        /// <param name="csvFile"></param>
        //CsvFileRecordInfoCollection ErrorRecords = new CsvFileRecordInfoCollection();
        public netma21.Model.CsvFileRecordInfoCollection ProcessFile(string csvFile)
        {
            int j = 1;
            bool IsTfile = false;
            System.IO.StreamReader Sr = new StreamReader(St);
            string CurrentLine = string.Empty;
            string[] values = null;
            CsvFileRecordInfoCollection CsvFileRecordInfoColl = new CsvFileRecordInfoCollection();
            //FileInfo CsvFi = new FileInfo(csvFile);

            if (csvFile.StartsWith("T"))
                IsTfile = true;

            try
            {
                while (Sr.Peek() >= 0)
                {
                    CurrentLine = Sr.ReadLine();
                    values = CurrentLine.Split(',');
                    DateTime tom = new DateTime(1900, 1, 1);
                    if (IsTfile)      //T File Sequence
                    {

                        if (values[0] != "MEC" &&
                            (values[0] != string.Empty && values[1] != string.Empty && values[2] != string.Empty))
                        {
                            CsvFileRecordInfo Source = new CsvFileRecordInfo();
                            if (values[2].Length == 9 &&
                                IsDate(values[13]) &&
                                IsDate(values[17]))
                            {

                                Source.ErvId = j;
                                Source.ActionId = (values[(int)TFileSequence.AR] == string.Empty) ? 0 : int.Parse(values[(int)TFileSequence.AR]);
                                Source.Amount = (values[(int)TFileSequence.AMOUNT] == string.Empty) ? 0.0 : double.Parse(values[(int)TFileSequence.AMOUNT]);
                                Source.CatId = (values[(int)TFileSequence.CAT] == string.Empty) ? 0 : int.Parse(values[(int)TFileSequence.CAT]);
                                Source.City = (string)(values[(int)TFileSequence.CITY]);
                                Source.Street = (string)(values[(int)TFileSequence.ADDRESS]);
                                Source.FirstName = (string)(values[(int)TFileSequence.FIRSTNAME]);
                                Source.LastName = (string)(values[(int)TFileSequence.LASTNAME]);
                                Source.GroupId = (string)(values[(int)TFileSequence.GRP]); //Accomodated special code for this in Stored Proc.
                                Source.Zip = (string)(values[(int)TFileSequence.ZIP]);
                                Source.State = (string)(values[(int)TFileSequence.ST]);
                                Source.LastRevDt = (values[(int)TFileSequence.REV_DT1] == string.Empty) ? tom : DateTime.Parse(values[(int)TFileSequence.REV_DT1]);
                                Source.Dob = (values[(int)TFileSequence.DOB] == string.Empty) ? tom : DateTime.Parse(values[(int)TFileSequence.DOB]);
                                Source.Phone = (string)(values[(int)TFileSequence.PHONE]);
                                Source.SendDt = (values[(int)TFileSequence.SENT_DT1] == string.Empty) ? tom : DateTime.Parse(values[(int)TFileSequence.SENT_DT1]);
                                Source.MecCode = (values[(int)TFileSequence.MEC] == string.Empty) ? 0 : int.Parse(values[(int)TFileSequence.MEC]); ;
                                Source.Ssn = (values[(int)TFileSequence.SSN] == string.Empty) ? 0 : int.Parse(values[(int)TFileSequence.SSN]);
                                Source.Field1 = (values[(int)TFileSequence.WKR1] == string.Empty) ? 0 : int.Parse(values[(int)TFileSequence.WKR1]);
                                Source.StatusId = (values[(int)TFileSequence.STA] == string.Empty) ? 0 : int.Parse(values[(int)TFileSequence.STA]);
                                Source.ManualEntry = 0;
                                Source.Type = "TRAD";
                                //add object to csvfile collection.
                                CsvFileRecordInfoColl.Add(Source);

                            }
                            j++;
                        }

                    }            //T File end if
                    else      // H File
                    {
                        if (values[0] != "MEC" &&
                            (values[0] != string.Empty && values[1] != string.Empty && values[2] != string.Empty))
                        {
                            CsvFileRecordInfo Source = new CsvFileRecordInfo();
                            if (values[2].Length == 9 &&
                                IsDate(values[14]) &&
                                IsDate(values[17]))
                            {

                                Source.ErvId = j;
                                Source.ActionId = (values[(int)HFileSequence.AR] == string.Empty) ? 0 : int.Parse(values[(int)HFileSequence.AR]);
                                Source.Amount = (values[(int)HFileSequence.AMOUNT] == string.Empty) ? 0.0 : double.Parse(values[(int)HFileSequence.AMOUNT]);
                                Source.CatId = (values[(int)HFileSequence.CAT] == string.Empty) ? 0 : int.Parse(values[(int)HFileSequence.CAT]);
                                Source.City = (string)(values[(int)HFileSequence.CITY]);
                                Source.Street = (string)(values[(int)HFileSequence.STREET]);
                                Source.FirstName = (string)(values[(int)HFileSequence.FIRST_NAME]);
                                Source.LastName = (string)(values[(int)HFileSequence.LAST_NAME]);
                                Source.GroupId = (string)(values[(int)HFileSequence.GC]); //Accomodated special code for this in Stored Proc.
                                Source.Zip = (string)(values[(int)HFileSequence.ZIP]);
                                Source.State = (string)(values[(int)HFileSequence.STATE]);
                                Source.LastRevDt = (values[(int)HFileSequence.LST_REV] == string.Empty) ? tom : DateTime.Parse(values[(int)HFileSequence.LST_REV]);
                                Source.Dob = (values[(int)HFileSequence.DOB] == string.Empty) ? tom : DateTime.Parse(values[(int)HFileSequence.DOB]);
                                Source.Phone = (string)(values[(int)HFileSequence.PHONE]);
                                Source.SendDt = (values[(int)HFileSequence.SEND_DATE] == string.Empty) ? tom : DateTime.Parse(values[(int)HFileSequence.SEND_DATE]);
                                Source.MecCode = (values[(int)HFileSequence.MEC] == string.Empty) ? 0 : int.Parse(values[(int)HFileSequence.MEC]); ;
                                Source.Ssn = (values[(int)HFileSequence.SSN] == string.Empty) ? 0 : int.Parse(values[(int)HFileSequence.SSN]);
                                Source.Field1 = (values[(int)HFileSequence.CAN] == string.Empty) ? 0 : int.Parse(values[(int)HFileSequence.CAN]);
                                Source.StatusId = (values[(int)HFileSequence.STATUS] == string.Empty) ? 0 : int.Parse(values[(int)HFileSequence.STATUS]);
                                Source.ManualEntry = 0;
                                Source.Type = "HCR";
                                //add object to csvfile collection.
                                CsvFileRecordInfoColl.Add(Source);

                            }
                            j++;
                        }

                    }            //H File end if


                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
               
            }

            return CsvFileRecordInfoColl;
        }

        /// <summary>
        /// Validate Csv file.
        /// </summary>
        /// <param name="csvFile"></param>
        /// <returns></returns>
        private bool IsCsvFileValid(string csvFile)
        {


            if ((!csvFile.EndsWith(".csv")) ||
                (!csvFile.StartsWith("H") && !csvFile.StartsWith("T")))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// Check Date
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        private bool IsDate(string sdate)
        {
            DateTime dt;
            bool isDate = true;
            try
            {
                if (sdate != "")
                {
                    dt = DateTime.Parse(sdate);
                }
                else
                    sdate = "";
            }
            catch
            {
                isDate = false;
            }
            return isDate;
        }

      }
}


0
 

Author Comment

by:balabommala
ID: 17122376
The code I posted is in VS2005. It was recently updated from VS2002 to VS2005.

Thanks.
0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 17122516
balabommala,

Where are you actually populating the value for csvFile in the code?

-Nauman.
0
 

Author Comment

by:balabommala
ID: 17122601
Stream uploadStream =UploadFile.PostedFile.InputStream;

This is where I am getting the csvfile  stream into 'uploadStream' variable.
0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 17122656
Yes but this is your method that is accepting a string variable csvFile :

public int UploadCSVFile( string csvFile )
     {    
          // Get an instance of the Disposition DAL using the DALFactory
          IImport dal = netma21.DALFactory.Import.Create();              
          return dal.UploadCSVFile(csvFile);
     }


How you are getting this? Where are you reading the stream and actually forming the CSV file?

-Nauman.
0
 

Author Comment

by:balabommala
ID: 17122717
Infact I modified it according to what you told me to do.
I created a constructor in BLL:
private Stream St;
        public Import()
        {
           
        }
        public Import(Stream uploadStream)
        {
            St = uploadStream;
        }
so that I can create an instance of BLL.Import(uploadStream)



Thanks.
0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 17122813
Yes thats true but after initializing the stream, you need to have something in the code that read the content of the stream and then call the upload method to upload the stream, or call the Validate method to validate the stream. Where is that happening in your code?

-Nauman.
0
 

Author Comment

by:balabommala
ID: 17122937
I am using a StreamReader to read the stream:
 System.IO.StreamReader Sr = new StreamReader(St);
where St is the stream.

Thanks.
0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 17123569
Sorry I am still kinda confused :$

public int UploadCSVFile( string csvFile )
     {    
          // Get an instance of the Disposition DAL using the DALFactory
          IImport dal = netma21.DALFactory.Import.Create();              
          return dal.UploadCSVFile(csvFile);
     }


This refer to a different class, right?

IImport dal = netma21.DALFactory.Import.Create();

UploadCSVFile(cvsFile) accept a string or stream?

--Nauman.
0
 

Author Comment

by:balabommala
ID: 17124069
Yes that refers to a different class in DAL. But then since my problem is to initialize the stream for every method in BLL, I only posted the code in BLL and code-behind.

UploadCSVFile(cvsFile) accepts a string.

Thanks.

0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 17124489
I need some more explanation balabommala. Its correct that you have initialized the stream object in the constructor. But wgat does dal.UploadCSVFile(csvFile) expect as a parameter? dal.UploadCSVFile() is the method where the error is coming right?

-Nauman.
0
 

Author Comment

by:balabommala
ID: 17124554
This is what is there in DAL:
namespace DAL
{
public class Import:IImport
      {
public int UploadCSVFile(string csvFile)
{
      //File Validations
      if(!IsCsvFileValid(csvFile))
      {      
            recordsUploaded = 0;
            return recordsUploaded;
      }
            BLL.Import bllImport = new BLL.Import();
            //if valid file
           CsvFileRecordInfoCollection ObjectsToUpload = bllImport.ProcessFile(csvFile);
}
}
0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 17124722
I do not see the declaration for ProcessFile in BLL class :$. Without that it will not be possible to identify what is going on.

-Nauman.
0
 

Author Comment

by:balabommala
ID: 17124865
Nauman,
I just need to pass a stream from code-behind to BLL where I could use it in 3 methods. Please don't take the pain of debugging my code.
Give me  a small example in vb.net where we can pass a stream from one layer and use it in another layer. But the clause is that we must be able to read the stream in all the three methods.

Thanks.
0
 
LVL 25

Accepted Solution

by:
nauman_ahmed earned 300 total points
ID: 17125226
balabommala:

Thanks for your patience but in the start I really did not know that you are using two different classes. You can of course easily call the Import method in the DAL in the same way you did in BAL import method i.e. Initialize the class using the stream object. The benefit is the Stream object will be available globally and you will not have to pass it to the methods again and again.

NameSpace Bll
Public Class Import
   
    'Global Variables
    Private _fileStream As Stream
   
    'Default constructor
    Public Sub New()
        MyBase.New
       
    End Sub
   
    Public Sub New(ByVal fileStream As Stream)
        MyBase.New
        Me._fileStream = fileStream
    End Sub
   
    Public Function ValidateStream() As Boolean
        Dim isFileValid As Boolean = false
        If (Me._fileStream = Nothing) Then
            Throw New Exception("Stream is not valid")
        Else
            'Validate file
        End If
        Return isFileValid
    End Function
   
    Public Function GetRecordCount() As Integer
        Dim recordCount As Integer = 0
        If (Me.ValidateStream = true) Then
            ' get record count
        End If
        Return recordCount
    End Function
   
    Public Function UploadFile() As Boolean
        Dim fileUploaded As Boolean = false
        If (Me.ValidateStream = true) Then
            'upload file
            Dim dalimp As New DAL.Import(St)
            dslImp.UploadCSVFile()
            fileUploaded = true
        End If
        Return fileUploaded
    End Function
End Class
End NameSpace

=============================

NameSpace DAL
Public Class Import
 private _fileStream As Stream
 Public Sub New()
    MyBase.New
       
 End Sub
   
 Public Sub New(ByVal fileStream As Stream)
     MyBase.New
     Me._fileStream = fileStream
 End Sub

Public Function UploadCSVFile() As Integer
        ' Get an instance of the Disposition DAL using the DALFactory
        Dim dal As IImport = netma21.DALFactory.Import.Create
        Return dal.UploadCSVFile(_fileStream)
    End Function
End Class

End NameSpace


Let me know if it helped.
0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 17133914
balabommala:

Any luck?

--Nauman.
0
 

Author Comment

by:balabommala
ID: 17177554
That somehow didn't work.
But I used the postedfile.inputstream property of the htmlinputfile control and set the stream.position to 0 and it worked.

Thanks for your help.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now