Replacing an existing fuploaded video (C#)

Hi,
I hope someone might be able to help or point me in the right direction.

I have some code written using the C# API for uploading videos and this is working fine. We now have a requirement to allow the user to upload a replacement/updated video in place of the original one.

I’ve tried running the import having set the ID of the media entry to that of the existing entry but I get an error then saying the ID cannot be set in code.

If I leave the ID but set the reference ID for the new video to that of the existing video then the upload works but a new entry is created on the KMC.

I feel I am close and am probably missing something obvious but if someone could point me in the right direction that would be great.

Many thanks,
Steve

Hi Steve,

What you need is:
client.BaseEntryService.Updatecontent(entryId, resource, conversionProfileId, advancedOptions);

You can take a look at http://www.kaltura.com/api_v3/testme, select baseEntry as service and updateContent as action and take a look at the other required params.
Click on “Show code example” and select C# for a rough code generation which you can then refine to actual working code.

Thanks for your help on this and apologies for not getting back to you sooner, the weekend got in the way.

There are a couple of further questions though I’m afraid:

1 - On the test page what value should I be entering in the entryID field?
2 - The generated code contains references to objects which I don’t seem to be able to find. Particularly KalturaUploadedFileResource which won’t resolve no matter where I try and reference it at.

I hope that makes sense?
Thanks,

Steve

Hi Steve,

The entry ID should be your existing entry ID, the one’s content you wish to replace.
As per the next question:

KalturaUploadedFileResource resource = new KalturaUploadedFileResource();
File resource.fileData = "C:\fakepath\file";

Hi,

Thanks for those prompts they have helped. I am now getting a strange error message. When I make the call KalturaBaseEntry result = baseService.UpdateContent(entryId, resource, conversionProfileId, advancedOptions); to do the update I get the following error message:

“The property “KalturaServerFileResource::localFilePath” cannot be null”

Earlier in the code I’ve set the LocalFilePath attribute of the KaltureServerFileResource object thus:

KalturaServerFileResource resource = new KalturaServerFileResource();
string path = context.Server.MapPath("~") + fileName;
resource.LocalFilePath = path;

There isn’t, as far as I can see a method called “localFilePath” with the lower case l. I am sure I must be missing something obvious but I am rather confused as to where to go with this now.

Any help gratefully received.

Thanks,
Steve

Hi Steve,

Can you print the value for path to ensure it looks valid?
Also, if you are using Kaltura CE look at the server log at /opt/kaltura/log/kaltura_api_v3.log to see what the server side think it got.
Finally, can you share the entire code snippet? minus the secrets, of course:)

Thanks for the pointers. I’m still having the same problem though I’m afraid so below is a snippet from the log file and the code the I am running.

The log file snippet may not necessarily be from the correct place but it does mention the property i am having problems with so I’ve included it. If you need a different part of the file please let me know.

Log file section

2015-10-23 12:57:00 [0.002290] [82.35.202.10] [1181352838] [3] [API] [KalturaFrontController->run] DEBUG: Params [Array
(
[advancedOptions:objectType] => KalturaEntryReplacementOptions
[apiVersion] => 3.2.0
[clientTag] => dotnet:15-05-14
[conversionProfileId] => 0
[entryId] => 0_vrb2bwsa
[format] => 2
[kalsig] => b8908ce2f038315de01966a7a385b71b
[ks] => Njc0NDljZjhmMWU3ZDRjYjQ5M2IwYWE3MWM0YmY5NDY0Y2NhODliMnwxMDQ7MTA0OzE0NDU2ODQyMTI7Mjs2MzU4MTE5ODIxMjM4NDMwODg7dGVzdFVzZXI7Ow==
[partnerId] => 104
[resource:localFilePath] => F:\Work\Code\Visual Studio 2013\Projects\TWMKaltura\TWMKaltura\SampleVideo.mp4
[resource:objectType] => KalturaServerFileResource
[service] => baseentry
[action] => updateContent
)
]
2015-10-23 12:57:00 [0.010892] [82.35.202.10] [1181352838] [4] [API] [KalturaDispatcher->dispatch] DEBUG: Dispatching service [baseentry], action [updatecontent], reqIndex [1] with params Array
(
[0] => 0_vrb2bwsa
[1] => KalturaServerFileResource Object
(
[localFilePath] => F:\Work\Code\Visual Studio 2013\Projects\TWMKaltura\TWMKaltura\SampleVideo.mp4
[relatedObjects] =>
)

[2] => 0
[3] => KalturaEntryReplacementOptions Object
    (
        [keepManualThumbnails] => 
        [relatedObjects] => 
    )

)

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

Code

using System;
using System.Web;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using Kaltura;

namespace TWMKaltura
{
public partial class FileUpload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FileUploader fu = new FileUploader();
fu.ProcessRequest(HttpContext.Current);
}

    //Routine to check filename for invalid chars
    private static readonly Regex InvalidFileRegex = new Regex(string.Format("[{0}]", Regex.Escape(@"<>:""/\|?*")));

    public static string SanitizeFileName(string fileName)
    {
        return InvalidFileRegex.Replace(fileName, string.Empty);
    }


    public class FileUploader : IHttpHandler
    {
        static KalturaConfiguration GetConfig()
        {
            KalturaConfiguration config = new KalturaConfiguration(PARTNER_ID);
            config.ServiceUrl = SERVICE_URL;
            return config;
        }

        //this function checks if a given flavor system name exist in the account.
        static int? CheckIfFlavorExist(String name)
        {
            KalturaClient client = new KalturaClient(GetConfig());
            string ks = client.GenerateSession(ADMIN_SECRET, USER_ID, KalturaSessionType.ADMIN, PARTNER_ID, 86400, "");
            client.KS = ks;

            //verify that the account we're testing has the new iPad flavor enabled on the default conversion profile
            KalturaConversionProfile defaultProfile = client.ConversionProfileService.GetDefault();
            KalturaConversionProfileAssetParamsFilter flavorsListFilter = new KalturaConversionProfileAssetParamsFilter();
            flavorsListFilter.SystemNameEqual = name;
            flavorsListFilter.ConversionProfileIdEqual = defaultProfile.Id;

            KalturaConversionProfileAssetParamsListResponse list = client.ConversionProfileAssetParamsService.List(flavorsListFilter);
            if (list.TotalCount > 0)
                return list.Objects[0].AssetParamsId;
            else
                return null;
        }

        public void ProcessRequest(HttpContext context)
        {
            try
            {

                string fileName = HttpContext.Current.Request.QueryString["FileName"].ToString();
                fileName = SanitizeFileName(fileName);
                
                using (FileStream fs = File.Create(context.Server.MapPath("~")  + @"\" + fileName))
                {
                    Byte[] buffer = new Byte[32 * 1024];
                    int read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length);
                    while (read > 0)
                    {
                        fs.Write(buffer, 0, read);
                        read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length);
                    }
                }


                string objectid = HttpContext.Current.Request.QueryString["objectid"];
                string objectTypeid = HttpContext.Current.Request.QueryString["objectTypeid"];
                string prefix = HttpContext.Current.Request.QueryString["prefix"];

                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString);

                // Get details saved already for this video which are then used
                // when importing the video
                SqlDataAdapter da = new SqlDataAdapter("Select * from tbl_D2_Object where objectid=" + objectid + " and objecttypeid=" + objectTypeid, conn);
                DataSet ds = new DataSet();
                da.Fill(ds);

                if (ds.Tables[0].Rows.Count > 0)
                {

                    FileStream fileStream = new FileStream(context.Server.MapPath("~") + @"\" + fileName, FileMode.Open, FileAccess.Read);


                    KalturaClient client = new KalturaClient(GetConfig());
                    string ks = client.GenerateSession(ADMIN_SECRET, USER_ID, KalturaSessionType.ADMIN, PARTNER_ID, 86400, "");
                    client.KS = ks;
                    KalturaUploadToken uploadToken = client.UploadTokenService.Add();
                    client.UploadTokenService.Upload(uploadToken.Id, fileStream);
                    KalturaUploadedFileTokenResource mediaResource = new KalturaUploadedFileTokenResource();
                    mediaResource.Token = uploadToken.Id;
                    KalturaMediaEntry mediaEntry = new KalturaMediaEntry();
                    mediaEntry.Name = ds.Tables[0].Rows[0]["Synopsis"].ToString();
                    mediaEntry.ReferenceId = prefix + "-" + objectid;
                    mediaEntry.MediaType = KalturaMediaType.VIDEO;
                    mediaEntry = client.MediaService.Add(mediaEntry);
                    mediaEntry = client.MediaService.AddContent(mediaEntry.Id, mediaResource);


                    string videoid = mediaEntry.Id;
                    string thumbnail = mediaEntry.ThumbnailUrl;
                    int duration = mediaEntry.Duration;

                    string status = mediaEntry.Status.ToString();
                    while (status != "1")
                    {
                        context.Response.Write("Converting");
                        status = mediaEntry.Status.ToString();
                    }

                    conn.Open();

                    SqlDataAdapter da2 = new SqlDataAdapter("Select * from tbl_D2_ObjectExtras where objectid=" + objectid + " and objecttypeid=" + objectTypeid, conn);
                    DataSet ds2 = new DataSet();
                    da2.Fill(ds2);


                    if (ds2.Tables[0].Rows.Count > 0)
                    {
                        SqlCommand CMD = new SqlCommand("UPDATE tbl_D2_ObjectExtras SET Prefix='" + prefix + "', ObjectId =" + objectid + ", objectTypeId =" + objectTypeid + ", Filename = '" + videoid + "', Thumbnail = '" + thumbnail + "', Duration = " + duration + " WHERE Prefix = '" + prefix + "' AND ObjectID =" + objectid + " AND objectTypeId =" + objectTypeid, conn);
                        CMD.ExecuteNonQuery();
                    }
                    else
                    {
                        SqlCommand cmd = new SqlCommand("INSERT INTO tbl_D2_ObjectExtras (Prefix, ObjectID, PageNo, ObjectTypeID, Filename, Thumbnail, Duration) VALUES ('" + prefix + "'," + objectid + ",1," + objectTypeid + ",'" + videoid + "','" + thumbnail + "'," + duration + ")", conn);
                        cmd.ExecuteNonQuery();
                    }

                    // Set the status on the object table to offline
                    SqlCommand cmd2 = new SqlCommand("UPDATE tbl_D2_Object SET Status = 1 WHERE ObjectID = " + objectid + " AND ObjectTypeID = 16", conn);
                    cmd2.ExecuteNonQuery();


                    context.Response.Write("Success");
                    
                }
            }
            catch(Exception ex)
            {
                //context.Response.Write(ex.Message);
                context.Response.Write("fail");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

}

}

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

Thanks,
Steve

Hi Steve,

I might be missing something here but I don’t see a call to:
client.BaseEntryService.Updatecontent(entryId, resource, conversionProfileId, advancedOptions);
or:
KalturaUploadedFileResource resource = new KalturaUploadedFileResource();

anywhere in the code you posted?

Hi,

It is ok you aren’t missing anything I am just an idiot and have posted code from the wrong place! The code below is the correct stuff. So sorry about this.

using System;
using System.Web;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using Kaltura;

namespace TWMKaltura
{
public partial class videoUploadUpdate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FileUploader fu = new FileUploader();
fu.ProcessRequest(HttpContext.Current);
}

    //Routine to check filename for invalid chars
    private static readonly Regex InvalidFileRegex = new Regex(string.Format("[{0}]", Regex.Escape(@"<>:""/\|?*")));

    public static string SanitizeFileName(string fileName)
    {
        return InvalidFileRegex.Replace(fileName, string.Empty);
    }

    public class FileUploader : IHttpHandler
    {

        static KalturaConfiguration GetConfig()
        {
            KalturaConfiguration config = new KalturaConfiguration(PARTNER_ID);
            config.ServiceUrl = SERVICE_URL;
            return config;
        }

        //this function checks if a given flavor system name exist in the account.
        static int? CheckIfFlavorExist(String name)
        {
            KalturaClient client = new KalturaClient(GetConfig());
            string ks = client.GenerateSession(ADMIN_SECRET, USER_ID, KalturaSessionType.ADMIN, PARTNER_ID, 86400, "");
            client.KS = ks;

            //verify that the account we're testing has the new iPad flavor enabled on the default conversion profile
            KalturaConversionProfile defaultProfile = client.ConversionProfileService.GetDefault();
            KalturaConversionProfileAssetParamsFilter flavorsListFilter = new KalturaConversionProfileAssetParamsFilter();
            flavorsListFilter.SystemNameEqual = name;
            flavorsListFilter.ConversionProfileIdEqual = defaultProfile.Id;

            KalturaConversionProfileAssetParamsListResponse list = client.ConversionProfileAssetParamsService.List(flavorsListFilter);
            if (list.TotalCount > 0)
                return list.Objects[0].AssetParamsId;
            else
                return null;
        }

        public void ProcessRequest(HttpContext context)
        {
            try
            {

                string fileName = HttpContext.Current.Request.QueryString["FileName"].ToString();
                fileName = SanitizeFileName(fileName);

                using (FileStream fs = File.Create(context.Server.MapPath("~") + @"\" + fileName))
                {
                    Byte[] buffer = new Byte[32 * 1024];
                    int read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length);
                    while (read > 0)
                    {
                        fs.Write(buffer, 0, read);
                        read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length);
                    }
                }


                string refid = HttpContext.Current.Request.QueryString["refid"];
                string prefix = refid.Substring(0, 4);
                string objectid = refid.Substring(5);
                string objecttypeid = "16";

                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString);

                // Get details saved already for this video which are then used
                // when importing the video
                SqlDataAdapter da = new SqlDataAdapter("Select * from tbl_D2_ObjectExtras where objectid=" + objectid + " and objecttypeid=16", conn);
                DataSet ds = new DataSet();
                da.Fill(ds);

                if (ds.Tables[0].Rows.Count > 0)
                {

                    KalturaClient client = new KalturaClient(GetConfig());
                    string ks = client.GenerateSession(ADMIN_SECRET, USER_ID, KalturaSessionType.ADMIN, PARTNER_ID, 86400, "");
                    client.KS = ks;
                    KalturaMediaEntry mediaEntry = new KalturaMediaEntry();
                    mediaEntry.MediaType = KalturaMediaType.VIDEO;
                    String entryId = mediaEntry.Id = ds.Tables[0].Rows[0]["Filename"].ToString();;
                    KalturaServerFileResource resource = new KalturaServerFileResource();
                    string path = fileName;
                    resource.LocalFilePath = path;
                    
                                            
                    if (!File.Exists(path))
                    {                        
                        // Open the file to read from.
                        using (StreamReader sr = File.OpenText(path))
                        {
                            string s = "";
                            while ((s = sr.ReadLine()) != null)
                            {
                                //Console.WriteLine(s);
                            }
                        }

                    }




                    int conversionProfileId = 0;
                    KalturaEntryReplacementOptions advancedOptions = new KalturaEntryReplacementOptions();
                    KalturaBaseEntryService baseService = new KalturaBaseEntryService(client);
                    KalturaBaseEntry result = baseService.UpdateContent(entryId, resource, conversionProfileId, advancedOptions);

                    string videoid = mediaEntry.Id;
                    string thumbnail = mediaEntry.ThumbnailUrl;
                    int duration = mediaEntry.Duration;

                    string status = mediaEntry.Status.ToString();
                    while (status != "1")
                    {
                        context.Response.Write("Converting");
                        status = mediaEntry.Status.ToString();
                    }

                    conn.Open();

                    SqlDataAdapter da2 = new SqlDataAdapter("Select * from tbl_D2_ObjectExtras where objectid=" + objectid + " and objecttypeid=" + objecttypeid, conn);
                    DataSet ds2 = new DataSet();
                    da2.Fill(ds2);


                    if (ds2.Tables[0].Rows.Count > 0)
                    {
                        SqlCommand CMD = new SqlCommand("UPDATE tbl_D2_ObjectExtras SET Prefix='" + prefix + "', ObjectId =" + objectid + ", objectTypeId =" + objecttypeid + ", Filename = '" + videoid + "', Thumbnail = '" + thumbnail + "', Duration = " + duration + " WHERE Prefix = '" + prefix + "' AND ObjectID =" + objectid + " AND objectTypeId =" + objecttypeid, conn);
                        CMD.ExecuteNonQuery();
                    }
                    else
                    {
                        SqlCommand cmd = new SqlCommand("INSERT INTO tbl_D2_ObjectExtras (Prefix, ObjectID, PageNo, ObjectTypeID, Filename, Thumbnail, Duration) VALUES ('" + prefix + "'," + objectid + ",1," + objecttypeid + ",'" + videoid + "','" + thumbnail + "'," + duration + ")", conn);
                        cmd.ExecuteNonQuery();
                    }

                    // Set the status on the object table to offline
                    SqlCommand cmd2 = new SqlCommand("UPDATE tbl_D2_Object SET Status = 0 WHERE ObjectID = " + objectid + " AND ObjectTypeID = 16", conn);
                    cmd2.ExecuteNonQuery();

                    context.Response.Write("Success");
                }
            }
            catch (Exception ex)
            {
                context.Response.Write("fail");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

}

}

Thanks,
Steve

Hi,

Thanks for this reply it has both helped and slightly confused me. I was indeed missing a reference to client.BaseEntryService.Updatecontent which I’ve added. However I cannont find the KalturaUploadedFileResource anywhere in the Object Browser in Visual Studio. The image below shows there is a KalturaUploadedFileTokenResourse but no KalturaUploadedFileResource.

I’m quite baffled where to go next I’m afraid.

Thanks,
Steve