Avatar of ntd1
ntd1
 asked on

Insert then select and then insert again Stored Procedure

Hi

I am developing a video uploading website. One of the upload criteria is to associate a video with as many courses or as many modules as the user chooses.

I relise that I need multiple tables to achieve this and have the tables as follows:

Video: VideoNo, VideoName, UserNo. UploadDate, VideoUrl etc
Module: ModuleNo, ModuleName
Course: CourseNo, CourseName
VideoAssociation: VideoAssociationNo, CourseNo, ModuleNo, VideoNo

I have two drop downs that users can select from and add them to list (Both Course and Module). The user then adds all other details about the video and uploads it.
I would like every course and module that is added to those lists to be added as an entry to the database table (VideoAssociation).
All of the other details would be wriiten to the video table.
The trouble is to write to the VideoAssociation table I would need a VideoNo as the identifier and that is not assigned until the video is added to the video table.

I need help how to write a query or multiple queries in a stored procedure to add all entries to the VideoAssociation Table after inserting the video details.
I think aloop would have to be used to get entries from the courses and modules lists, but I don't know where to start?
I have included an image of the interface and the stored procedure I have written so far.
Thanks

ALTER PROCEDURE dbo.sprocUploadVideo
         @UserNo                         INT                      ,
       @VideoName                      VARCHAR(50)      = NULL  ,
       @ModuleNo                       INT                  ,
       @CourseNo                       INT              = NULL  ,
       @DateUploaded                   DATETIME         = NULL  ,
       @VideoUrl                       VARCHAR(50)      = NULL  ,
       @ThumbUrl                       VARCHAR(50)              ,
         @Description                    VARCHAR(500)             ,
         @Keywords                                 VARCHAR(50)                        ,
         @Visible                                 VARCHAR(10)
AS


     INSERT INTO dbo.Video
          (
            UserNo                  ,
            VideoName                     ,
            CourseNo                   ,
            ModuleNo                    ,
            DateUploaded                   ,
            VideoUrl                          ,
            ThumbUrl                          ,
                  Description                      ,
                  Keywords                          ,
                  Visible          
          )
     VALUES
          (
            @UserNo                  ,
            @VideoName                     ,
            @CourseNo                   ,
            @ModuleNo                     ,
            @DateUploaded                   ,
            @VideoUrl                         ,
            @ThumbUrl                        ,
                  @Description               ,
            @Keywords                              ,
                  @Visible
          )
upload.jpg
ASP.NET

Avatar of undefined
Last Comment
winston33

8/22/2022 - Mon
JAruchamy

Hi,

1. First Insert into the video table.

2. Get the VideoNo using SCOPE_IDENTITY ......   http://msdn.microsoft.com/en-us/library/ks9f57t0.aspx

3. Then get the items from your CourseNo "something" separated string as follows

SELECT RowNum = ROW_NUMBER() OVER(ORDER BY splitvalue) FROM dbo.Split('test1,test2,test3',',')

now loop as in the following example....

http://sqlserverplanet.com/tsql/sql-server-for-each-row-next

Note: Do everything in one DB call or in one SP
winston33

I would recommend passing the CourseNo and ModuleNo lists as XML parameters to avoid looping. Build the XML in code so it looks something like:

<Courses>
   <CourseNo>1</CourseNo>
   <CourseNo>2</CourseNo>
</Courses>

DECLARE @course TABLE (CourseNo INT)

DECLARE @module TABLE(ModuleNo INT)

INSERT INTO @course
 SELECT      ParamLabel.ID.value('.', 'VARCHAR(20)')      
 FROM      @courseXML.nodes('/Course/CourseNo') AS ParamLabel (ID)      

INSERT INTO @module
 SELECT      ParamLabel.ID.value('.', 'VARCHAR(20)')      
 FROM      @courseXML.nodes('/Module/ModuleNo') AS ParamLabel (ID)      

Then your insert can simply select the identity from the new video row and the CourseNo/ModuleNo field from the table parameters.

SELECT VideoID,
             CourseNo
FROM @course
ntd1

ASKER
Would I loop through the list box then insert?

This is really hard for me to get my head around.

 Dim sqlInsert As String = String.Empty
                                                Dim sb As New StringBuilder(String.Empty)
                                                For i As Integer = 0 To lstCourses.Items.Count - 1
                                                    If lstCourses.Items(i).Selected = True Then
                                                        sb.AppendFormat("'{0}'", lstCourses.Items(i).Text)
                                                        sqlInsert += String.Format("INSERT INTO TABLE1 (Field1)VALUES ({0});", sb.ToString())
                                                    End If
                                                Next
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
winston33

Which method are you attempting?
JAruchamy

Get the SelectedValues from the listbox and then either form a comma separated string or a xml string as told by winston33 and pass it as a parameter to the SP. Then you can do the looping in the SP.

I guess U should do a join instead of looping.

FYI...
SELECT splitvalue FROM dbo.Split('test1,test2,test3',',') --- this way you can read from a comma seperated string as reading from a table.
ntd1

ASKER
I'm not very experienced with sql, but I have wriiten the insert procedure in the original post. In that statement it adds the course and module single value to the video table.
I have since removed the courseNo and ModuleNo columns from the video table.

The original sql was only taking one value from the drop down of each (cboCourse and cboModule) now I want the user to select as many as they want from the drop down and populate two lists (lstCourses and lstModules) from these lists I would like to insert every value into the video association table.
I know I would need to loop through each list and assign the value to a parameter in stored procedure:
cmd.Parameters.AddWithValue("@CourseNo", lstCourses.SelectedValue())

I want to add this to to statement simular to the original one.
It must obviously insert the video details first then use a scope_identity to pass the video number to the insert of the video association table.
I know what I want to do, but I just don't know how to write the srored procedure and the code that goes with it.
Thanks
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
winston33

OK. Here is what I would do (although the comma-separated list will work as well):

In the code-behind where the listbox resides, created two XML strings:

            Dim xmlCourse as String
            Dim xmlModule as String
            Dim pNode As XmlNode = oXml.CreateElement("Courses")
            oXml.AppendChild(pNode)

            oNode = oXml.SelectSingleNode("Courses")

            For i As Integer = 0 To lstCourses.Items.Count - 1
                  If lstCourses.Items(i).Selected = True Then
                          oElement = oXml.CreateElement("CourseNo")
                          oElement.InnerText = lstCourse.Items(i).Text
                          oNode.AppendChild(oElement)
                  End If
            Next

            xmlCourse = oXml.InnerXml

            ****NOTE: Repeat this code to build xmlModule

Pass these two strings as XML into stored procedure and process them as I mentioned earlier. From my nderstanding, there will be no need to join anything. You will simply need to select the VideoID (created by the insert) and the CourseNo or ModuleNo (depending on which table you are inserting into) from the table created from the XML parameters.

For reference, here is the SQL from earlier:

DECLARE @course TABLE (CourseNo INT)

DECLARE @module TABLE(ModuleNo INT)

INSERT INTO @course
 SELECT      ParamLabel.ID.value('.', 'VARCHAR(20)')      
 FROM      @courseXML.nodes('/Course/CourseNo') AS ParamLabel (ID)      

INSERT INTO @module
 SELECT      ParamLabel.ID.value('.', 'VARCHAR(20)')      
 FROM      @courseXML.nodes('/Module/ModuleNo') AS ParamLabel (ID)      

Then your insert can simply select the identity from the new video row and the CourseNo/ModuleNo field from the table parameters.

SELECT VideoID,
             CourseNo
FROM @course
ntd1

ASKER
Hi

that is giving syntax errors.

I have included:

Imports System.Xml
winston33

Could you post all the relevant code here so I can take a look in its entirety?
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ntd1

ASKER
Hi

This is the entire code behind the upload button:

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnConfirm.Click

        If IsPostBack Then
            'declare the file path to store uploads
            Dim path As String = Server.MapPath("~/UploadedVideos/" & UserLogin.UserNo & "/")
            'Dim path As String = HttpRuntime.AppDomainAppPath ("~/UploadedVideos/")

            Dim fileOK As Boolean = False

            'If the file upload control has a file
            If FileUploadVideo.HasFile Then
                'check to see if the number of characters does not exceed 50 and is not empty
                If Len(txtVideoName.Text) <= 50 And txtVideoName.Text IsNot "" Then
                    'clear the error message
                    lblErrorTitle.Text = ""

                    'check to see if a course has been added to the list
                    If lstCourses.SelectedIndex <> -1 Then
                        lblErrorCourse.Text = ""
                        'check to see if a module has been added to the list
                        If lstModules.SelectedIndex <> -1 Then
                            lblErrorModule.Text = ""
                            If Len(txtDescription.Text) <= 500 And txtDescription.Text IsNot "" Then
                                lblDescriptionError.Text = ""

                                'check to see if the number of characters does not exceed 50 and is not empty
                                If Len(txtKeywords.Text) <= 50 And txtKeywords.Text IsNot "" And txtKeywords.Text = Replace(txtKeywords.Text, " ", "") Then

                                    'clear the error message
                                    lblErrorKeywords.Text = ""

                                    'check the file to make sure it is of the required type
                                    Dim fileExtension As String
                                    fileExtension = System.IO.Path. _
                                        GetExtension(FileUploadVideo.FileName).ToLower()
                                    'declare the allowed extentions
                                    Dim allowedExtensions As String() = _
                                        {".mov", ".wmv", ".avi", ".mp4", ".m4v"}
                                    'loop to check the extention type
                                    For i As Integer = 0 To allowedExtensions.Length - 1
                                        If fileExtension = allowedExtensions(i) Then


                                            '//////////////////////////// Convert File


                                            Call encode()


                                            fileOK = True

                                        End If
                                        '////////////////////////////////Upload File path


                                    Next
                                    If fileOK Then
                                        Using Conn As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
                                            Try
                                                'open the database connection
                                                Conn.Open()
                                                Dim FilePath = fileNameWithoutExtention & ".flv"
                                                'Dim FilePath = path & FileUploadVideo.FileName
                                                'insert statement to add the video details to the database
                                                '  SqlCommand(cmd = New SqlCommand("GetAllData", connection))


                                                Const SQL As String = "sprocUploadVideo"
                                                Dim cmd As New SqlCommand(SQL, Conn)
                                                cmd.CommandType = CommandType.StoredProcedure


                                                Dim xmlCourse As String
                                                Dim xmlModule As String
                                                Dim pNode As XmlNode = oXml.CreateElement("Courses")
                                                oXml.AppendChild(pNode)

                                                oNode = oXml.SelectSingleNode("Courses")

                                                For i As Integer = 0 To lstCourses.Items.Count - 1
                                                    If lstCourses.Items(i).Selected = True Then
                                                        oElement = oXml.CreateElement("CourseNo")
                                                        oElement.InnerText = lstCourses.Items(i).Text
                                                        oNode.AppendChild(oElement)
                                                    End If
                                                Next

                                                xmlCourse = oXml.InnerXml





                                                cmd.Parameters.AddWithValue("@UserNo", UserLogin.UserNo())
                                                cmd.Parameters.AddWithValue("@VideoName", txtVideoName.Text.Trim())
                                                cmd.Parameters.AddWithValue("@CourseNo", cboCourse.SelectedValue())
                                                cmd.Parameters.AddWithValue("@ModuleNo", cboModule.SelectedValue())
                                                cmd.Parameters.AddWithValue("@DateUploaded", Date.Now)
                                                cmd.Parameters.AddWithValue("@VideoUrl", UserLogin.UserNo & "/" & fileNameWithoutExtention & ".flv")
                                                cmd.Parameters.AddWithValue("@ThumbUrl", UserLogin.UserNo & "\" & fileNameWithoutExtention & ".jpg")
                                                cmd.Parameters.AddWithValue("@Description", txtDescription.Text.Trim())
                                                cmd.Parameters.AddWithValue("@Keywords", txtKeywords.Text.Trim())
                                                cmd.Parameters.AddWithValue("@Visible", "Yes")
                                                FileUploadVideo.PostedFile.SaveAs(path & _
                                                     FileUploadVideo.FileName)


                                                'MsgBox("File Uploaded Successfully - Thank You", MsgBoxStyle.Information, "Video Upload")
                                                'Successful upload message
                                                lblError.Text = "File Uploaded Successfully - Thank You"

                                                'clear the fields
                                                lblHoldFilePath.Text = ""
                                                lstModules.Items.Clear()
                                                lstCourses.Items.Clear()
                                                txtVideoName.Text = ""
                                                txtKeywords.Text = ""
                                                cboCourse.Text = ""
                                                cboModule.Text = ""
                                                txtDescription.Text = ""
                                                cmd.ExecuteNonQuery()

                                                'close the database connection
                                                Conn.Close()
                                            Catch ex As Exception

                                                'file can't be uploaded error message
                                                lblError.Text = "File could not be uploaded." & ex.Message
                                            End Try
                                        End Using
                                    Else
                                        'error message for incorrect file type
                                        lblError.Text = "Cannot accept files of this type."
                                    End If


                                Else
                                    'error message for too many characters in the video name field
                                    lblErrorKeywords.Text = "This is a required field with a maximum length of 50 characters and no spaces!"
                                End If


                            Else
                                lblDescriptionError.Text = "This is a required field with a maximum length of 500 characters"
                                'insert here

                            End If


                        Else
                            lblErrorModule.Text = "You must add at least 1 Module to the list"
                        End If
                    Else
                        lblErrorCourse.Text = "You must add at least 1 course to the list"
                    End If




                Else
                    'error message for too many characters in the keywords field
                    lblErrorTitle.Text = "This is a required field with a maximum length of 50 characters"
                End If
               


            Else
                'error message for no file selected
                lblHoldFilePath.Text = "Please Choose A File!!"
            End If
        End If


    End Sub
winston33

Sorry - my fault. I forgot to include the declaration of a few variables:

        Dim oXml As New XmlDocument
        Dim oNode As XmlNode
        Dim oElement As XmlElement
ntd1

ASKER
So where the  stored procedure sql above that uses the xml do I just add that in the original stored procedure and use it?

If so, do I pass the videoId using scope identity into an insert after that to the insert into VideoAssociation? Does in need to be built like the below?

ALTER PROCEDURE dbo.sprocUploadVideo
         @UserNo                         INT                      ,
       @VideoName                      VARCHAR(50)      = NULL  ,  
       @DateUploaded                   DATETIME         = NULL  ,
       @VideoUrl                       VARCHAR(50)      = NULL  ,
       @ThumbUrl                       VARCHAR(50)              ,
         @Description                    VARCHAR(500)             ,
         @Keywords                                 VARCHAR(50)                        ,
         @Visible                                 VARCHAR(10)                              ,
         @course TABLE (CourseNo INT)                                                ,
         @module TABLE(ModuleNo INT)



AS


     INSERT INTO dbo.Video
          (
            UserNo                  ,
            VideoName                     ,
            DateUploaded                   ,
            VideoUrl                          ,
            ThumbUrl                          ,
                  Description                      ,
                  Keywords                          ,
                  Visible          
          )
     VALUES
          (
            @UserNo                  ,
            @VideoName                     ,
            @DateUploaded                   ,
            @VideoUrl                         ,
            @ThumbUrl                        ,
                  @Description               ,
            @Keywords                              ,
                  @Visible
          )

INSERT INTO @course
 SELECT      ParamLabel.ID.value('.', 'VARCHAR(20)')      
 FROM      @courseXML.nodes('/Course/CourseNo') AS ParamLabel (ID)      

INSERT INTO @module
 SELECT      ParamLabel.ID.value('.', 'VARCHAR(20)')      
 FROM      @courseXML.nodes('/Module/ModuleNo') AS ParamLabel (ID)      

Then your insert can simply select the identity from the new video row and the CourseNo/ModuleNo field from the table parameters.

SELECT VideoID,
             CourseNo
FROM @course
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
winston33

I have one question about the data here. Is there a relation between the course and module? It does not appear that there is from th code or data structure so this VideoAssociation table will not really work for both course and module (I could be misunderstanding the data here). From my reading of your code, you would need a VideoCourse table and a VideoModule table to store the information you need.

Additionally, in your VB code, you are storing the text of the list item, but you really want the selectedvalue (missed that earlier).

Given that you will store the records in two tables as I suggest above, the proc would look like this:

ALTER PROCEDURE dbo.sprocUploadVideo
      @UserNo                  INT,
      @VideoName            VARCHAR(50) = NULL,  
      @DateUploaded      DATETIME = NULL,
      @VideoUrl            VARCHAR(50) = NULL,
      @ThumbUrl            VARCHAR(50),
      @Description      VARCHAR(500),
      @Keywords            VARCHAR(50),
      @Visible            VARCHAR(10),
      @CourseXML            XML,
      @ModuleXML            XML
      
AS

      DECLARE @course TABLE (CourseNo INT)                                                
      DECLARE @module TABLE(ModuleNo INT)
      DECLARE @VideoID INT
      
      INSERT INTO @course
      SELECT      ParamLabel.ID.value('.', 'VARCHAR(20)')      
      FROM            @CourseXML.nodes('/Course/CourseNo') AS ParamLabel (ID)      

      INSERT INTO @module
      SELECT      ParamLabel.ID.value('.', 'VARCHAR(20)')      
      FROM            @CourseXML.nodes('/Module/ModuleNo') AS ParamLabel (ID)      
 
     INSERT INTO dbo.Video
          (
            UserNo                  ,
            VideoName                     ,
            DateUploaded                   ,
            VideoUrl                          ,
            ThumbUrl                          ,
            Description                      ,
                  Keywords                          ,
                  Visible          
          )
     VALUES
          (
            @UserNo                  ,
            @VideoName                     ,
            @DateUploaded                   ,
            @VideoUrl                         ,
            @ThumbUrl                        ,
                  @Description               ,
            @Keywords                              ,
                  @Visible
          )

      SET      @VideoID = SCOPE_IDENTITY()
      
      INSERT INTO VideoAssociation
      SELECT      @VideoID,
                  CourseNo
      FROM      @course

      
      INSERT INTO VideoModule
      SELECT      @VideoID,
                  ModuleNo
      FROM      @module
ntd1

ASKER
Hi
I have taken your advice and made two tables:

VideoCourse
VideoModule

I have changed the stored procedure and updated my code, but it wont insert anything?

It says on the exit message not set to an instance of an object.
 
I really appreciate all of your help on this.

The stored procedure:

ALTER PROCEDURE dbo.sprocUploadVideo
      @UserNo                  INT,
      @VideoName            VARCHAR(50) = NULL,  
      @DateUploaded      DATETIME = NULL,
      @VideoUrl            VARCHAR(50) = NULL,
      @ThumbUrl            VARCHAR(50),
      @Description      VARCHAR(500),
      @Keywords            VARCHAR(50),
      @Visible            VARCHAR(10),
      @CourseXML            XML,
      @ModuleXML            XML
     
AS

      DECLARE @course TABLE (CourseNo INT)                                                
      DECLARE @module TABLE(ModuleNo INT)
      DECLARE @VideoNo INT
     
      INSERT INTO @course
      SELECT      ParamLabel.ID.value('.', 'VARCHAR(20)')      
      FROM            @CourseXML.nodes('/Course/CourseNo') AS ParamLabel (ID)      

      INSERT INTO @module
      SELECT      ParamLabel.ID.value('.', 'VARCHAR(20)')      
      FROM            @CourseXML.nodes('/Module/ModuleNo') AS ParamLabel (ID)      
 
     INSERT INTO dbo.Video
          (
            UserNo                  ,
            VideoName                     ,
            DateUploaded                   ,
            VideoUrl                          ,
            ThumbUrl                          ,
            Description                      ,
                  Keywords                          ,
                  Visible          
          )
     VALUES
          (
            @UserNo                  ,
            @VideoName                     ,
            @DateUploaded                   ,
            @VideoUrl                         ,
            @ThumbUrl                        ,
            @Description               ,
            @Keywords                              ,
                  @Visible
          )

      SET      @VideoNo = SCOPE_IDENTITY()
     
      INSERT INTO VideoCourse
      SELECT      @VideoNo,
                  CourseNo
      FROM      @course

     
      INSERT INTO VideoModule
      SELECT      @VideoNo,
                  ModuleNo
      FROM      @module



The Code Behind the button:


 Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnConfirm.Click

        If IsPostBack Then
            'declare the file path to store uploads
            Dim path As String = Server.MapPath("~/UploadedVideos/" & UserLogin.UserNo & "/")
            'Dim path As String = HttpRuntime.AppDomainAppPath ("~/UploadedVideos/" & UserLogin.UserNo & "/")

            Dim fileOK As Boolean = False

            'If the file upload control has a file
            If FileUploadVideo.HasFile Then
                'check to see if the number of characters does not exceed 50 and is not empty
                If Len(txtVideoName.Text) <= 50 And txtVideoName.Text IsNot "" Then
                    'clear the error message
                    lblErrorTitle.Text = ""

                    'check to see if a course has been added to the list
                    If lstCourses.SelectedIndex <> -1 Then
                        lblErrorCourse.Text = ""
                        'check to see if a module has been added to the list
                        If lstModules.SelectedIndex <> -1 Then
                            lblErrorModule.Text = ""
                            If Len(txtDescription.Text) <= 500 And txtDescription.Text IsNot "" Then
                                lblDescriptionError.Text = ""

                                'check to see if the number of characters does not exceed 50 and is not empty
                                If Len(txtKeywords.Text) <= 50 And txtKeywords.Text IsNot "" And txtKeywords.Text = Replace(txtKeywords.Text, " ", "") Then

                                    'clear the error message
                                    lblErrorKeywords.Text = ""

                                    'check the file to make sure it is of the required type
                                    Dim fileExtension As String
                                    fileExtension = System.IO.Path. _
                                        GetExtension(FileUploadVideo.FileName).ToLower()
                                    'declare the allowed extentions
                                    Dim allowedExtensions As String() = _
                                        {".mov", ".wmv", ".avi", ".mp4", ".m4v"}
                                    'loop to check the extention type
                                    For i As Integer = 0 To allowedExtensions.Length - 1
                                        If fileExtension = allowedExtensions(i) Then


                                            '//////////////////////////// Convert File


                                            Call encode()


                                            fileOK = True

                                        End If
                                        '////////////////////////////////Upload File path


                                    Next
                                    If fileOK Then
                                        Using Conn As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
                                            Try
                                                'open the database connection
                                                Conn.Open()
                                                Dim FilePath = fileNameWithoutExtention & ".flv"
                                                'Dim FilePath = path & FileUploadVideo.FileName
                                                'insert statement to add the video details to the database
                                                '  SqlCommand(cmd = New SqlCommand("GetAllData", connection))



                                               

                                                Dim oXml As New XmlDocument
                                                Dim oNode As XmlNode
                                                Dim oElement As XmlElement



                                                Dim xmlCourse As String
                                                Dim xmlModule As String
                                                Dim pNode As XmlNode = oXml.CreateElement("Courses")
                                                oXml.AppendChild(pNode)

                                                oNode = oXml.SelectSingleNode("Courses")

                                                For i As Integer = 0 To lstCourses.Items.Count - 1
                                                    If lstCourses.Items(i).Selected = True Then
                                                        oElement = oXml.CreateElement("CourseNo")
                                                        oElement.InnerText = lstCourses.Items(i).Text
                                                        oNode.AppendChild(oElement)
                                                    End If
                                                Next

                                                xmlCourse = oXml.InnerXml


                                                Dim pNode2 As XmlNode = oXml.CreateElement("Modules")
                                                oXml.AppendChild(pNode)

                                                oNode = oXml.SelectSingleNode("Modules")

                                                For i As Integer = 0 To lstCourses.Items.Count - 1
                                                    If lstCourses.Items(i).Selected = True Then
                                                        oElement = oXml.CreateElement("ModuleNo")
                                                        oElement.InnerText = lstCourses.Items(i).Text
                                                        oNode.AppendChild(oElement)
                                                    End If
                                                Next

                                                xmlModule = oXml.InnerXml



                                                Const SQL As String = "sprocUploadVideo"
                                                Dim cmd As New SqlCommand(SQL, Conn)
                                                cmd.CommandType = CommandType.StoredProcedure
                                                cmd.Parameters.AddWithValue("@UserNo", UserLogin.UserNo())
                                                cmd.Parameters.AddWithValue("@VideoName", txtVideoName.Text.Trim())
                                                'cmd.Parameters.AddWithValue("@CourseNo", cboCourse.SelectedValue())
                                                'cmd.Parameters.AddWithValue("@ModuleNo", cboModule.SelectedValue())
                                                cmd.Parameters.AddWithValue("@DateUploaded", Date.Now)
                                                cmd.Parameters.AddWithValue("@VideoUrl", UserLogin.UserNo & "/" & fileNameWithoutExtention & ".flv")
                                                cmd.Parameters.AddWithValue("@ThumbUrl", UserLogin.UserNo & "\" & fileNameWithoutExtention & ".jpg")
                                                cmd.Parameters.AddWithValue("@Description", txtDescription.Text.Trim())
                                                cmd.Parameters.AddWithValue("@Keywords", txtKeywords.Text.Trim())
                                                cmd.Parameters.AddWithValue("@Visible", "Yes")
                                                FileUploadVideo.PostedFile.SaveAs(path & _
                                                     FileUploadVideo.FileName)


                                                'MsgBox("File Uploaded Successfully - Thank You", MsgBoxStyle.Information, "Video Upload")
                                                'Successful upload message
                                                lblError.Text = "File Uploaded Successfully - Thank You"

                                                'clear the fields
                                                lblHoldFilePath.Text = ""
                                                lstModules.Items.Clear()
                                                lstCourses.Items.Clear()
                                                txtVideoName.Text = ""
                                                txtKeywords.Text = ""
                                                cboCourse.Text = ""
                                                cboModule.Text = ""
                                                txtDescription.Text = ""
                                                cmd.ExecuteNonQuery()

                                                'close the database connection
                                                Conn.Close()
                                            Catch ex As Exception

                                                'file can't be uploaded error message
                                                lblError.Text = "File could not be uploaded." & ex.Message
                                            End Try
                                        End Using
                                    Else
                                        'error message for incorrect file type
                                        lblError.Text = "Cannot accept files of this type."
                                    End If


                                Else
                                    'error message for too many characters in the video name field
                                    lblErrorKeywords.Text = "This is a required field with a maximum length of 50 characters and no spaces!"
                                End If


                            Else
                                lblDescriptionError.Text = "This is a required field with a maximum length of 500 characters"
                                'insert here

                            End If


                        Else
                            lblErrorModule.Text = "You must add at least 1 Module to the list"
                        End If
                    Else
                        lblErrorCourse.Text = "You must add at least 1 course to the list"
                    End If




                Else
                    'error message for too many characters in the keywords field
                    lblErrorTitle.Text = "This is a required field with a maximum length of 50 characters"
                End If
               


            Else
                'error message for no file selected
                lblHoldFilePath.Text = "Please Choose A File!!"
            End If
        End If


    End Sub
winston33

I can see one thing:

You need to re-instantiate oXml before the second XML doc is created. Code should look like this:

oXml = New XmlDocument
Dim pNode2 As XmlNode = oXml.CreateElement("Modules")
                                                oXml.AppendChild(pNode)

                                                oNode = oXml.SelectSingleNode("Modules")

                                                For i As Integer = 0 To lstCourses.Items.Count - 1
                                                    If lstCourses.Items(i).Selected = True Then
                                                        oElement = oXml.CreateElement("ModuleNo")
                                                        oElement.InnerText = lstCourses.Items(i).Text
                                                        oNode.AppendChild(oElement)
                                                    End If
                                                Next

                                                xmlModule = oXml.InnerXml

Is this the section where you see the error when you step through the code?
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ntd1

ASKER
Hi

I changed it and now it says:

The node to be inserted is from a different document context.

Also the sub convert is being called but not encoding the file (ffmpeg)

Thanks
winston33

Another copy/paste error...

oXml = New XmlDocument
Dim pNode2 As XmlNode = oXml.CreateElement("Modules")
                                                oXml.AppendChild(pNode2)

                                                oNode = oXml.SelectSingleNode("Modules")

                                                For i As Integer = 0 To lstCourses.Items.Count - 1
                                                    If lstCourses.Items(i).Selected = True Then
                                                        oElement = oXml.CreateElement("ModuleNo")
                                                        oElement.InnerText = lstCourses.Items(i).Text
                                                        oNode.AppendChild(oElement)
                                                    End If
                                                Next

                                                xmlModule = oXml.InnerXml

As for the file, I don't know what the method is doing, so I can't really help with that yet.
ntd1

ASKER
Hi

It not failing at the converting stage now. its not inserting anything though?

I wondered if the parameters are correct?


Conn.Open()
                                               

                                                Dim oXml As New XmlDocument
                                                Dim oNode As XmlNode
                                                Dim oElement As XmlElement



                                                Dim xmlCourse As String
                                                Dim xmlModule As String
                                                Dim pNode As XmlNode = oXml.CreateElement("Courses")
                                                oXml.AppendChild(pNode)

                                                oNode = oXml.SelectSingleNode("Courses")

                                                For i As Integer = 0 To lstCourses.Items.Count - 1
                                                    If lstCourses.Items(i).Selected = True Then
                                                        oElement = oXml.CreateElement("@CourseNo")
                                                        oElement.InnerText = lstCourses.Items(i).Text
                                                        oNode.AppendChild(oElement)
                                                    End If
                                                Next

                                                xmlCourse = oXml.InnerXml






                                                oXml = New XmlDocument
                                                Dim pNode2 As XmlNode = oXml.CreateElement("Modules")
                                                oXml.AppendChild(pNode2)

                                                oNode = oXml.SelectSingleNode("Modules")

                                                For i As Integer = 0 To lstCourses.Items.Count - 1
                                                    If lstModules.Items(i).Selected = True Then
                                                        oElement = oXml.CreateElement("@ModuleNo")
                                                        oElement.InnerText = lstModules.Items(i).Text
                                                        oNode.AppendChild(oElement)
                                                    End If
                                                Next

                                                xmlModule = oXml.InnerXml










                                                Const SQL As String = "sprocUploadVideo"
                                                Dim cmd As New SqlCommand(SQL, Conn)
                                                cmd.CommandType = CommandType.StoredProcedure
                                                cmd.Parameters.AddWithValue("@UserNo", UserLogin.UserNo())
                                                cmd.Parameters.AddWithValue("@VideoName", txtVideoName.Text.Trim())
                                                cmd.Parameters.AddWithValue("@DateUploaded", Date.Now)
                                                cmd.Parameters.AddWithValue("@VideoUrl", UserLogin.UserNo & "/" & fileNameWithoutExtention & ".flv")
                                                cmd.Parameters.AddWithValue("@ThumbUrl", UserLogin.UserNo & "\" & fileNameWithoutExtention & ".jpg")
                                                cmd.Parameters.AddWithValue("@Description", txtDescription.Text.Trim())
                                                cmd.Parameters.AddWithValue("@Keywords", txtKeywords.Text.Trim())
                                                cmd.Parameters.AddWithValue("@Visible", "Yes")
                                                FileUploadVideo.PostedFile.SaveAs(path & _
                                                     FileUploadVideo.FileName)


                                                'MsgBox("File Uploaded Successfully - Thank You", MsgBoxStyle.Information, "Video Upload")
                                                'Successful upload message
                                                lblError.Text = "File Uploaded Successfully - Thank You"

                                                'clear the fields
                                                lblHoldFilePath.Text = ""
                                                lstModules.Items.Clear()
                                                lstCourses.Items.Clear()
                                                txtVideoName.Text = ""
                                                txtKeywords.Text = ""
                                                cboCourse.Text = ""
                                                cboModule.Text = ""
                                                txtDescription.Text = ""
                                                cmd.ExecuteNonQuery()

                                                'close the database connection
                                                Conn.Close()

And also as you said earlier. The drop down lists are databound as

cboModule.DataTextField = "ModuleCode"
cboModule.DataValueField = "ModuleNo"
cboCourse.DataTextField = "CourseName"
cboCourse.DataValueField = "CourseNo"

When they are added to the lists I would like them to display the courses and module names, but I am thinking using the code I have been (below) will only hold the text value and not the course and module numbers?

 'check if an item is selected
        If cboCourse.SelectedIndex <> 0 Then
            'check to see selected item is not already on the list
            If lstCourses.Items.Contains(cboCourse.SelectedItem) = True Then
                'tell user duplicates can't be added
                lblErrorCourse.Text = "This Course is Already on the List!"
            Else
                'clear the error message
                lblErrorCourse.Text = ""
                'if ok add to the list
                lstCourses.Items.Add(cboCourse.SelectedItem)

            End If
        Else
            'error message no course selected
            lblErrorCourse.Text = "Please First Select a Course"
        End If
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
winston33

1) It doesn't look like you are adding the XML strings to the parameter list. Does the proc work when you run it alone in SQL Server (with those variables)?

2) You are safe with the way you are adding items. The SelectedItem is of type ListItem, so it will pass in both the text and the value. Of course, the listbox settings need to be the same (Value and Text fields). Are they?
ntd1

ASKER
If it is copying the item then yes. As the drop box datavalue is the course/module number.

How do I add the xml to the parameter list?
winston33

In VB:

cmd.Parameters.AddWithValue("@CourseXML", xmlCourse)
cmd.Parameters.AddWithValue("@ModuleXML", xmlModule)

In SQL, my version of the proc included the new parameters:

ALTER PROCEDURE dbo.sprocUploadVideo
      @UserNo                  INT,
      @VideoName            VARCHAR(50) = NULL,  
      @DateUploaded      DATETIME = NULL,
      @VideoUrl            VARCHAR(50) = NULL,
      @ThumbUrl            VARCHAR(50),
      @Description      VARCHAR(500),
      @Keywords            VARCHAR(50),
      @Visible            VARCHAR(10),
      @CourseXML            XML,
      @ModuleXML            XML
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
ntd1

ASKER
Hi

I have added the parameters and it is now sucessfully inserting into the video table.

It is not inserting anything into

VideoCourse
VideoModule

The id of Videos is VideoNo

ALTER PROCEDURE dbo.sprocUploadVideo
      @UserNo                  INT,
      @VideoName            VARCHAR(50) = NULL,  
      @DateUploaded      DATETIME = NULL,
      @VideoUrl            VARCHAR(50) = NULL,
      @ThumbUrl            VARCHAR(50),
      @Description      VARCHAR(500),
      @Keywords            VARCHAR(50),
      @Visible            VARCHAR(10),
      @CourseXML            XML,
      @ModuleXML            XML
     
AS

      DECLARE @course TABLE (CourseNo INT)                                                
      DECLARE @module TABLE(ModuleNo INT)
      DECLARE @VideoNo INT
     
      INSERT INTO @course
      SELECT      ParamLabel.ID.value('.', 'VARCHAR(20)')      
      FROM            @CourseXML.nodes('/Course/CourseNo') AS ParamLabel (ID)      

      INSERT INTO @module
      SELECT      ParamLabel.ID.value('.', 'VARCHAR(20)')      
      FROM            @CourseXML.nodes('/Module/ModuleNo') AS ParamLabel (ID)      
 
     INSERT INTO dbo.Video
          (
            UserNo                  ,
            VideoName                     ,
            DateUploaded                   ,
            VideoUrl                          ,
            ThumbUrl                          ,
            Description                      ,
                  Keywords                          ,
                  Visible          
          )
     VALUES
          (
            @UserNo                  ,
            @VideoName                     ,
            @DateUploaded                   ,
            @VideoUrl                         ,
            @ThumbUrl                        ,
            @Description               ,
            @Keywords                              ,
                  @Visible
          )

      SET      @VideoNo = SCOPE_IDENTITY()
     
      INSERT INTO VideoCourse
      SELECT      @VideoNo,
                  CourseNo
      FROM      @course

     
      INSERT INTO VideoModule
      SELECT      @VideoNo,
                  ModuleNo
      FROM      @module
ntd1

ASKER
The two list boxes the the loop is running on are showing the course and module names.

The selection mode of the list boxes are set to multiple else they wont accept more than one item.

Do you think that this could be the problem why it is not inserting correctly? Or is it the stored procedure? I have double checked all of the table names and colomn names.

Thanks again for your continued efforts.
winston33

If you step through the code, are the Xml documents being created? Also, as I reviewed the code, I see the loop through the Modules list is checking courses list:

                                                For i As Integer = 0 To lstCourses.Items.Count - 1
                                                    If lstModules.Items(i).Selected = True Then
                                                        oElement = oXml.CreateElement("@ModuleNo")
                                                        oElement.InnerText = lstModules.Items(i).Text
                                                        oNode.AppendChild(oElement)
                                                    End If
                                                Next

                                                xmlModule = oXml.InnerXml

This should be changed to loop through lstModules instead.
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
ntd1

ASKER
Hi

I have changed that error.

The lists are being created successfully as I skip through the code. The problem is though that the lists contain the module and course names and not their numbers?

Thanks
winston33

OK. I thought I mentioned to use the Value of the listitem instead of the Text, but I keep pasting in code that includes the Text property. Change that and see if it helps.
ntd1

ASKER
Hi

It now picks up the course and module codes.

It runs through both loops with all of the right numbers in them.

It has the right course/module details in the parameter

It writes all of the details into the video table.

It will not write anyting into the videocourse or videomodule tables.

Could it be the stored procedure?
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
ASKER CERTIFIED SOLUTION
winston33

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
ntd1

ASKER
That's IT!!!  It works!!

Unbelievable!

I can't thank you enough for all of your effort.

Now I just have to figure out how to do the edits on the edit video page where a user can add and removes courses as this form does, but the lists will be already populated with ones previously added!

Thank You again.
ntd1

ASKER
Winston33 went above and beyond to solve my problem. Very, Very Helpful! Excellent.
winston33

Glad it worked for you.
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.