using Chromium; using Chromium.Remote; using Chromium.Remote.Event; using Chromium.WebBrowser; using Client.Config; using Client.Config.SubModels; using Client.Utils; using CMS_Client.Browser_Tools.Models; using CMS_Client.Browser_Tools.Models.Errors; using CMS_Client.Browser_Tools.Models.Metadata; using CMS_Client.View; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.IO.Compression; using System.Linq; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using static Client.Utils.Constants; namespace CMS_Client.Browser_Tools { public class BrowserJSObject : JSObject { //The first letter of All PUBLIC Variables and Methods must be Lower-Case (CEF Settings) private MainForm mainForm; private static readonly string[] _validExtensions = { "",".txt", ".cnc", ".ini", ".mpf", ".spf" }; private static readonly string[] _validImages = { ".jpg", ".jpeg", ".png" }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #region CONSTRUCTOR_METHOD //Constructor Method public BrowserJSObject(MainForm f) { mainForm = f; AddFunction("minimizeForm").Execute += minimizeForm; AddFunction("maximizeForm").Execute += maximizeForm; AddFunction("closeForm").Execute += closeForm; AddFunction("forceStepFocus").Execute += forceStepFocus; AddFunction("reloadBrokenPage").Execute += reloadBrokenPage; AddFunction("setNcWindowState").Execute += setNcWindowState; AddFunction("getNcWindowState").Execute += getNcWindowState; AddFunction("getScreenBase64").Execute += getScreenBase64; AddFunction("getChromiumVersion").Execute += getChromiumVersion; AddFunction("getClientID").Execute += getClientID; AddFunction("getConfiguredProcesses").Execute += getConfiguredProcesses; AddFunction("getConfiguredProcessesInMainMenu").Execute += getConfiguredProcessesInMainMenu; AddFunction("startNewProcess").Execute += startNewProcess; AddFunction("openOrStartProcess").Execute += openOrStartProcess; AddFunction("isVirtualKeybConfigured").Execute += isVirtualKeybConfigured; AddFunction("getOSdriveList").Execute += getOSdriveList; AddFunction("getFileList").Execute += getFileList; AddFunction("getProgramInfo").Execute += getProgramInfo; AddFunction("uploadAndActivateProgram").Execute += uploadAndActivateProgram; AddFunction("uploadAndAddToQueue").Execute += uploadAndAddToQueue; AddFunction("openJob").Execute += openJob; AddFunction("saveJob").Execute += saveJob; AddFunction("addImageToJob").Execute += addImageToJob; AddFunction("delImageFromJob").Execute += delImageFromJob; AddFunction("addPPToJob").Execute += addPPToJob; AddFunction("delPPFromJob").Execute += delPPFromJob; } #endregion /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #region FORM_BEHAVIOUR_METHODS //Minimize Main Window public void minimizeForm(object sender, CfrV8HandlerExecuteEventArgs e) { //Invoke method if is needed or call the method in STD mode if (mainForm.InvokeRequired) mainForm.Invoke((MethodInvoker)delegate () { mainForm.WindowState = FormWindowState.Minimized; }); else { mainForm.WindowState = FormWindowState.Minimized; } } //Maximize Main Window public void maximizeForm(object sender, CfrV8HandlerExecuteEventArgs e) { //Invoke method if is needed or call the method in STD mode if (mainForm.InvokeRequired) mainForm.Invoke((MethodInvoker)delegate () { mainForm.WindowState = FormWindowState.Maximized; }); else { mainForm.WindowState = FormWindowState.Maximized; } } //Close Main Window public void closeForm(object sender, CfrV8HandlerExecuteEventArgs e) { //If the mainform is disposed do nothing if (mainForm.IsDisposed) return; //Invoke method if is needed or call the method in STD mode mainForm.Close(); } //Reload Broken Page private void reloadBrokenPage(object sender, CfrV8HandlerExecuteEventArgs e) { //Invoke method if is needed or call the method in STD mode mainForm.reloadBrokenPage(); } #endregion /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #region NC_BEHAVIOUR_METHODS public void setNcWindowState(object sender, CfrV8HandlerExecuteEventArgs e) { if (e.Arguments.Count() == 0) return; NcWindow.SetState((NcState)e.Arguments[0].IntValue); if (NcWindow.State == NcState.SHOW) mainForm.ShowNCWindow(); else mainForm.HideNCWindow(); } public void getNcWindowState(object sender, CfrV8HandlerExecuteEventArgs e) { e.SetReturnValue((int)NcWindow.State); } public void getScreenBase64(object sender, CfrV8HandlerExecuteEventArgs e) { if (e.Arguments.Count() > 0 && e.Arguments[0].BoolValue) NcWindow.CaptureHMI(); e.SetReturnValue(NcWindow.NcCapture); } #endregion /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #region CHROMIUM_METHODS //Get the Version of Chromium public void getChromiumVersion(object sender, CfrV8HandlerExecuteEventArgs e) { e.SetReturnValue(CfxRuntime.GetChromeVersion()); } #endregion /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #region STEP_METHODS //Get the ID of STEP Client public void getClientID(object sender, CfrV8HandlerExecuteEventArgs e) { e.SetReturnValue((int)Config.ConnectionConfig.Id); } public void forceStepFocus(object sender, CfrV8HandlerExecuteEventArgs e) { NcWindow.ForceStepFocus(); } //Get the option of virtual Keyb configured private void isVirtualKeybConfigured(object sender, CfrV8HandlerExecuteEventArgs e) { e.SetReturnValue((Boolean)Config.ClientConfig.ShowVirtualKeyboard); } #endregion /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #region PROCESSES_METHODS //Read all configured processes public void getConfiguredProcesses(object sender, CfrV8HandlerExecuteEventArgs e) { e.SetReturnValue(JsonConvert.SerializeObject(Config.ExtSoftwaresConfig.Where(X => X.inMainMenuBar==false))); } //Read all configured processes in main menu public void getConfiguredProcessesInMainMenu(object sender, CfrV8HandlerExecuteEventArgs e) { e.SetReturnValue(JsonConvert.SerializeObject(Config.ExtSoftwaresConfig.Where(X => X.inMainMenuBar == true))); } //Start a new process public void startNewProcess(object sender, CfrV8HandlerExecuteEventArgs e) { if (e.Arguments.Count() == 0) return; Thread t = new Thread(new ParameterizedThreadStart(OpenNew)); t.Start(e.Arguments[0].StringValue); } //Open the last window or Start a new process public void openOrStartProcess(object sender, CfrV8HandlerExecuteEventArgs e) { if (e.Arguments.Count() == 0) return; Thread t = new Thread(new ParameterizedThreadStart(OpenStartNew)); t.Start(e.Arguments[0].StringValue); } //Function used in Thread private void OpenStartNew(object id) { Software sft = Config.ExtSoftwaresConfig.FirstOrDefault(X => X.id == (string)id); if (sft != null) { Process[] p = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(sft.path)).OrderByDescending(X => X.StartTime).ToArray(); if (p.Count() > 0 && p[0].MainWindowHandle != IntPtr.Zero) NcWindow.ForceExtFocus(p[0].MainWindowHandle); else Process.Start(sft.path, sft.arguments); } } //Function used in Thread private void OpenNew(object id) { Software sft = Config.ExtSoftwaresConfig.FirstOrDefault(X => X.id == (string)id); if (sft != null) Process.Start(sft.path, sft.arguments); } #endregion /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #region FILESYSTEM_METHODS //Read all drives in Operating System public void getOSdriveList(object sender, CfrV8HandlerExecuteEventArgs e) { List drivelist = new List(); foreach (var drive in DriveInfo.GetDrives()) { if (drive.IsReady) drivelist.Add(new Drive() { Name = ElaborateName(drive.VolumeLabel, drive.DriveType), Path = drive.RootDirectory.ToString(), Type = ElaborateType(drive.DriveType) }); } drivelist.Add(new Drive() { Name = ElaborateName("Desktop", DriveType.Unknown), Path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\", Type = "SPFO" }); e.SetReturnValue(JsonConvert.SerializeObject(drivelist)); } //Read all files in directory public void getFileList(object sender, CfrV8HandlerExecuteEventArgs e) { List filelist = new List(); if (e.Arguments.Count() == 0) { e.SetReturnValue(JsonConvert.SerializeObject(new List())); return; } String p = e.Arguments[0].StringValue; if (!Directory.Exists(p)) { e.SetReturnValue(JsonConvert.SerializeObject(new List())); return; } try { foreach (String item in Directory.GetDirectories(p)) { filelist.Add(new Models.File { Name = Path.GetFileName(item), AbsolutePath = Path.GetFullPath(item), Path = Path.GetFullPath(item), IsDirectory = true }); } } catch (Exception ex) { } try { foreach (String item in Directory.GetFiles(p)) { if (_validExtensions.Contains(Path.GetExtension(item).ToLower())) filelist.Add(new Models.File { Name = Path.GetFileName(item), AbsolutePath = Path.GetFullPath(item), Path = Path.GetFullPath(item), IsDirectory = false }); } } catch (Exception ex) { } e.SetReturnValue(JsonConvert.SerializeObject(filelist)); } //Upload and activate the program public async void uploadAndActivateProgram(object sender, CfrV8HandlerExecuteEventArgs e) { String fileToUpload = ""; Byte[] filecontent = null, imagecontent = null; String fileNameNoExt; String imageName = ""; String fileName; String imageDirectory; //Check the arguments numbers if (e.Arguments.Length < 1 || e.Arguments[0] == null) { e.SetReturnValue(Constants.Uploadpage +"INVALID_ARGUMENTS"); return; } //Check if the file exists fileToUpload = e.Arguments[0].StringValue; if (!System.IO.File.Exists(fileToUpload)) { e.SetReturnValue(Constants.Uploadpage+";FILE_NOT_FOUND"); return; } //Get names and content of the file fileNameNoExt = Path.GetFileNameWithoutExtension(fileToUpload); fileName = Path.GetFileName(fileToUpload); ; filecontent = System.IO.File.ReadAllBytes(fileToUpload); //Get all bytes of the image (if exists) imageDirectory = Path.GetDirectoryName(fileToUpload); foreach (string ext in _validImages) { if (System.IO.File.Exists(imageDirectory + "/" + fileNameNoExt + ext)) { imageName = fileNameNoExt + ext; imagecontent = System.IO.File.ReadAllBytes(imageDirectory + "/" + fileNameNoExt + ext); break; } } //Send all to the server using (HttpClient httpClient = new HttpClient()) { //Create the new FORM MultipartFormDataContent form = new MultipartFormDataContent(); //Add the content to the form form.Add(new ByteArrayContent(filecontent), "file", fileName); if(imagecontent != null) form.Add(new ByteArrayContent(imagecontent), "image", imageName); //Send them HttpResponseMessage response = httpClient.PostAsync( "http://" + Config.ConnectionConfig.ServerUrl + ":" + Config.ConnectionConfig.ServerPort + "/" + Constants.Uploadpage, form).Result; //Wait the answer if(response.StatusCode == System.Net.HttpStatusCode.BadRequest) e.SetReturnValue(Constants.Uploadpage + ";" + await response.Content.ReadAsStringAsync()); else if(response.StatusCode != System.Net.HttpStatusCode.OK) e.SetReturnValue(Constants.Uploadpage + ";" + response.ReasonPhrase); else e.SetReturnValue(""); } } //Upload and add to queue public async void uploadAndAddToQueue(object sender, CfrV8HandlerExecuteEventArgs e) { string fileToUpload = ""; Byte[] filecontent = null, imagecontent = null; string fileNameNoExt; string imageName = ""; string fileName; string imageDirectory; int reps = 0; //Check the arguments numbers if (e.Arguments.Length < 1 || e.Arguments[0] == null) { e.SetReturnValue(Constants.UPLOAD_ADD_QUEUE + "INVALID_ARGUMENTS"); return; } //Check if the file exists fileToUpload = e.Arguments[0].StringValue; reps = e.Arguments[1].IntValue; if (!System.IO.File.Exists(fileToUpload)) { e.SetReturnValue(Constants.UPLOAD_ADD_QUEUE + ";FILE_NOT_FOUND"); return; } //Get names and content of the file fileNameNoExt = Path.GetFileNameWithoutExtension(fileToUpload); fileName = Path.GetFileName(fileToUpload); ; filecontent = System.IO.File.ReadAllBytes(fileToUpload); //Get all bytes of the image (if exists) imageDirectory = Path.GetDirectoryName(fileToUpload); foreach (string ext in _validImages) { if (System.IO.File.Exists(imageDirectory + "/" + fileNameNoExt + ext)) { imageName = fileNameNoExt + ext; imagecontent = System.IO.File.ReadAllBytes(imageDirectory + "/" + fileNameNoExt + ext); break; } } //Send all to the server using (HttpClient httpClient = new HttpClient()) { //Create the new FORM MultipartFormDataContent form = new MultipartFormDataContent(); //Add the content to the form form.Add(new ByteArrayContent(filecontent), "file", fileName); if (imagecontent != null) form.Add(new ByteArrayContent(imagecontent), "image", imageName); form.Add(new StringContent(reps.ToString()), "reps"); //Send them HttpResponseMessage response = httpClient .PostAsync("http://" + Config.ConnectionConfig.ServerUrl + ":" + Config.ConnectionConfig.ServerPort + "/" + Constants.UPLOAD_ADD_QUEUE, form) .Result; //Wait the answer if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) e.SetReturnValue(Constants.UPLOAD_ADD_QUEUE + ";" + await response.Content.ReadAsStringAsync()); else if (response.StatusCode != System.Net.HttpStatusCode.OK) e.SetReturnValue(Constants.UPLOAD_ADD_QUEUE + ";" + response.ReasonPhrase); else e.SetReturnValue(""); } } //Read info of a file public void getProgramInfo(object sender, CfrV8HandlerExecuteEventArgs e) { InfoFile file = new InfoFile(); string line, imagePath, imageDirectory; int counter = 0; if (e.Arguments.Count() == 0) { e.SetReturnValue(JsonConvert.SerializeObject(new InfoFile())); return; } String p = e.Arguments[0].StringValue; if (!System.IO.File.Exists(p)) { e.SetReturnValue(JsonConvert.SerializeObject(new InfoFile())); return; } FileInfo f = new FileInfo(p); file.Name = f.Name; file.CreationDate = f.CreationTime; file.LastModDate = f.LastAccessTime; file.AbsolutePath = p; imagePath = Path.GetFileNameWithoutExtension(p); imageDirectory = Path.GetDirectoryName(p); file.Content = new List(); try { StreamReader fileRead = new StreamReader(p); while ((line = fileRead.ReadLine()) != null && counter < 10) { file.Content.Add(line); counter++; } fileRead.Close(); foreach (string ext in _validImages) { if (System.IO.File.Exists(imageDirectory + "/" + imagePath + ext)) { file.PreviewBase64 = "data:image/" + ext + ";base64," + Convert.ToBase64String(System.IO.File.ReadAllBytes(imageDirectory + "/" + imagePath + ext)); break; } } } catch (Exception ex) { } e.SetReturnValue(JsonConvert.SerializeObject(file)); } //Private functions... private String ElaborateName(String name, DriveType type) { if (!String.IsNullOrWhiteSpace(name)) return name; else { switch (type) { case DriveType.Fixed: return "Hard_Disk"; case DriveType.Removable: return "Usb_Disk"; case DriveType.Network: return "Netword_Disk"; } return "Undefined Drive"; } } private String ElaborateType(DriveType type) { switch (type) { case DriveType.Fixed: return "HD"; case DriveType.Removable: return "USB"; case DriveType.Network: return "NTW"; } return "SPFO"; } #endregion /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #region JOB_METHODS //Read all job public void openJob(object sender, CfrV8HandlerExecuteEventArgs e) { JobToStep job = new JobToStep(); OpenFileDialog jobOpenFileDialog = new OpenFileDialog(); jobOpenFileDialog.Filter = "CMS Job Files(*.JOB,*.ZIP)|*.job;*.zip"; jobOpenFileDialog.Multiselect = false; if (jobOpenFileDialog.ShowDialog() == DialogResult.OK) { if (!Directory.Exists(JOB_OPENING_PATH)) Directory.CreateDirectory(JOB_OPENING_PATH); ClearTempPath(); using (ZipArchive archive = ZipFile.OpenRead(jobOpenFileDialog.FileName)) { //Setup main Fields job.Name = Path.GetFileName(jobOpenFileDialog.FileName); job.LastEditTimestamp = new FileInfo(jobOpenFileDialog.FileName).LastAccessTime; foreach (ZipArchiveEntry entry in archive.Entries) { //Main program if (entry.Name.Equals(JOB_MAIN_FILENAME, StringComparison.OrdinalIgnoreCase)) { using (var reader = new StreamReader(entry.Open())) { job.IsoMainProgram = (reader.ReadToEnd()); } } //Add all images else if (_validImages.Contains(Path.GetExtension(entry.Name).ToLower())) { var bytes = default(byte[]); entry.ExtractToFile(JOB_OPENING_PATH + entry.Name, true); using (var memstream = new MemoryStream()) { entry.Open().CopyTo(memstream); bytes = memstream.ToArray(); job.Metadata.Generics.Images.Add(new Image_param() { Name = Path.GetFileNameWithoutExtension(entry.Name), Base64 = "data:image/" + Path.GetExtension(entry.Name).ToLower().TrimStart('.') + ";base64," + Convert.ToBase64String(bytes) }); } } //Metadata else if(entry.Name.Equals(JOB_METADATA_FILENAME, StringComparison.OrdinalIgnoreCase)) { MetadataToFile metasFromFile = new MetadataToFile(); using (var reader = new StreamReader(entry.Open())) { metasFromFile = JsonConvert.DeserializeObject(reader.ReadToEnd()); if(metasFromFile == null) { e.SetReturnValue(null); return; } else { job.Metadata.Generics.Description = metasFromFile.Description; job.Metadata.Generics.ExecutionTime = metasFromFile.ExecutionTime; job.Metadata.Tools = metasFromFile.Tools; job.Metadata.Customs = metasFromFile.Customs; } } } //All other files else { entry.ExtractToFile(JOB_OPENING_PATH + entry.Name, true); } } } e.SetReturnValue(JsonConvert.SerializeObject(job)); return; } else { e.SetReturnValue(null); return; } } //Save all job public void saveJob(object sender, CfrV8HandlerExecuteEventArgs e) { MetadataToFile metafile = new MetadataToFile(); //check the arguments if (e.Arguments.Count() == 0) return; //Call Save Dialog SaveFileDialog jobSaveFileDialog = new SaveFileDialog(); jobSaveFileDialog.Filter = "CMS Job Files(*.JOB)|*.job|Zip Files(*.ZIP)|*.zip"; if(jobSaveFileDialog.ShowDialog() == DialogResult.OK) { // Job deserialize JobToStep job = JsonConvert.DeserializeObject(e.Arguments[0].StringValue); if (job == null) { e.SetReturnValue(JsonConvert.SerializeObject(new ErrorContainer("corrupted_model"))); return; } //Metadata metafile.Description = job.Metadata.Generics.Description; metafile.ExecutionTime = job.Metadata.Generics.ExecutionTime; metafile.Tools = job.Metadata.Tools; metafile.Customs = job.Metadata.Customs; using (StreamWriter file = System.IO.File.CreateText(JOB_OPENING_PATH + JOB_METADATA_FILENAME)) { JsonSerializer serializer = new JsonSerializer(); serializer.Formatting = Formatting.Indented; serializer.Serialize(file, metafile); } //Main Program System.IO.File.WriteAllText(JOB_OPENING_PATH + JOB_MAIN_FILENAME, job.IsoMainProgram); //delete Zip File if exists if (System.IO.File.Exists(jobSaveFileDialog.FileName)) System.IO.File.Delete(jobSaveFileDialog.FileName); //Create Zip File ZipFile.CreateFromDirectory(JOB_OPENING_PATH, jobSaveFileDialog.FileName); } e.SetReturnValue(null); return; } //Add an image public void addImageToJob(object sender, CfrV8HandlerExecuteEventArgs e) { OpenFileDialog imageOpenFileDialog = new OpenFileDialog(); imageOpenFileDialog.Filter = "Images Files(*.JPG,*.JPEG,*.PNG)|*.jpg;*.jpeg;*.png"; imageOpenFileDialog.Multiselect = false; if (imageOpenFileDialog.ShowDialog() == DialogResult.OK) { String newImagePath = JOB_OPENING_PATH + Path.GetFileName(imageOpenFileDialog.FileName); //If exixts send error if (System.IO.File.Exists(newImagePath)) { e.SetReturnValue(JsonConvert.SerializeObject(new ErrorContainer("file_esists"))); return; } //Copy the file System.IO.File.Copy(imageOpenFileDialog.FileName, newImagePath); //Send to Step e.SetReturnValue(JsonConvert.SerializeObject(new Image_param() { Name = Path.GetFileNameWithoutExtension(imageOpenFileDialog.FileName), Base64 = "data:image/" + Path.GetExtension(newImagePath).ToLower().TrimStart('.') + ";base64," + Convert.ToBase64String(System.IO.File.ReadAllBytes(newImagePath)) })); return; } e.SetReturnValue(null); return; } //Delete an image public void delImageFromJob(object sender, CfrV8HandlerExecuteEventArgs e) { //check the arguments if (e.Arguments.Count() == 0 && e.Arguments[0].IsString) return; //Get the file Path String imagePath = JOB_OPENING_PATH + e.Arguments[0].StringValue; //If not exixts Error! if (!System.IO.File.Exists(imagePath)) { e.SetReturnValue(JsonConvert.SerializeObject(new ErrorContainer("file_not_esists"))); return; } //delete it System.IO.File.Delete(imagePath); e.SetReturnValue(null); return; } //Add a Part-Program public void addPPToJob(object sender, CfrV8HandlerExecuteEventArgs e) { OpenFileDialog PPOpenFileDialog = new OpenFileDialog(); PPOpenFileDialog.Multiselect = false; if (PPOpenFileDialog.ShowDialog() == DialogResult.OK) { //Check the extension if (!_validExtensions.Contains(Path.GetExtension(PPOpenFileDialog.FileName).ToLower())) { e.SetReturnValue(JsonConvert.SerializeObject(new ErrorContainer("extension_not_available"))); return; } String newPPPath = JOB_OPENING_PATH + Path.GetFileName(PPOpenFileDialog.FileName); //If exixts delete old file and save the new one if (System.IO.File.Exists(newPPPath)) { e.SetReturnValue(JsonConvert.SerializeObject(new ErrorContainer("file_esists"))); return; } //Copy the file System.IO.File.Copy(PPOpenFileDialog.FileName, newPPPath); //Send to Step e.SetReturnValue(null); return; } e.SetReturnValue(null); return; } //Delete an image public void delPPFromJob(object sender, CfrV8HandlerExecuteEventArgs e) { //check the arguments if (e.Arguments.Count() == 0 && e.Arguments[0].IsString) return; //Get the file Path String ppPath = JOB_OPENING_PATH + e.Arguments[0].StringValue; //If not exixts Error! if (!System.IO.File.Exists(ppPath)) { e.SetReturnValue(JsonConvert.SerializeObject(new ErrorContainer("file_not_esists"))); return; } //delete it System.IO.File.Delete(ppPath); e.SetReturnValue(null); return; } //Clear the temp folder files private void ClearTempPath() { DirectoryInfo di = new DirectoryInfo(JOB_OPENING_PATH); foreach (FileInfo file in di.GetFiles()) file.Delete(); foreach (DirectoryInfo dir in di.GetDirectories()) dir.Delete(true); } //Clear the temp folder files private string GetExtensionFromBase64(string base64img) { base64img = base64img.Remove(0,"data:image/".Length); return base64img.Substring(0, base64img.IndexOf(";base64,")); } //Clear the temp folder files private string GetContentFromBase64(string base64img) { return base64img.Substring(base64img.IndexOf(";base64,") + ";base64,".Length); } #endregion } }