Automatically generating JSON script files from file name - json

I'd like to use a JSON file as a template to create new JSON files with a couple of words in the script that change according to the file name.
For example, say I have a JSON file called word1.json, with a script looking like this:
filename: word1.json
script:
{
"name": "word1",
"annotates": "word1.wav",
"sampleRate": 44100
}
I want to automatically generate a new JSON script for every file name I enter, for example:
filename: word2.json
script:
{
"name": "word2",
"annotates": "word2.wav",
"sampleRate": 44100
}
filename: newword.json
script:
{
"name": "newword",
"annotates": "newword.wav",
"sampleRate": 44100
}
and so on.
Is there some software that allows me to do it? I'm currently editing the JSON files with TextEdit - I'm not a programmer as you can probably tell, but I can use R and can do a little bit of programming there.
EDIT: I'm on MacOS
Many thanks.

I'll probably get some hate here, but since you are new, you are not a programmer, and it's a simple request I say 'Everybody gets one'.
This is a C# program that can be run in any compatible IDE. If you do not have one installed, you can run using LinqPad. It's a quick and simple installation. Open LinqPad and run as C# Program. Press the Play button start the program.
You will need to add the NuGet "Newtonsoft.Json".
This program will create a new directory on your hard drive at C:\jsonfiles. It will repeatedly ask you to enter in a file name until you enter in 'exit' at which point the program will exit. Rerun as needed.
void Main()
{
Console.WriteLine("JSON Creator");
Console.WriteLine("For each entered file name a JSON file will be created. The files will be created at C:/jsonfiles. If the file already exists it will be overwritten.");
Console.WriteLine("Enter 'exit' to end the program");
string jsonDirectory = #"C:\jsonfiles";
CreateBaseDirectory(jsonDirectory);
string jsonFileName = GetUserInput();
while (QuitProgram(jsonFileName) == false)
{
string fullJsonPath = System.IO.Path.Combine(jsonDirectory, jsonFileName + ".json");
try
{
DeleteExistingFile(fullJsonPath);
}
catch (IOException ioException)
{
Console.WriteLine("Unable to delete file. The file may be in use. Please close the file or manually delete the file before continuing on.");
jsonFileName = GetUserInput();
continue;
}
try
{
SaveToFile(jsonFileName, fullJsonPath);
}
catch (Exception ex)
{
Console.WriteLine("There was an issue creating the file. Verify the file does not already exist, the file name is valid, the file is not open, and you have privileges to write to the file system");
jsonFileName = GetUserInput();
continue;
}
jsonFileName = GetUserInput();
}
}
private void CreateBaseDirectory(string jsonDirectory)
{
if (System.IO.Directory.Exists(jsonDirectory) == false)
{
System.IO.Directory.CreateDirectory(jsonDirectory);
}
}
private bool InputIsValid(string input)
{
return string.IsNullOrWhiteSpace(input) == false;
}
private bool QuitProgram(string input)
{
string modifiedInput = input?.Trim()?.ToLower();
return modifiedInput == "quit" || modifiedInput == "q" || modifiedInput == "exit";
}
private string GetUserInput()
{
Console.WriteLine("Please enter in the JSON file name");
string input = Console.ReadLine();
while (InputIsValid(input) == false)
{
Console.WriteLine("Please enter valid JSON file name. An empty or space-only file name is not valid.");
}
return input.Trim().Replace(".json", "");
}
private void DeleteExistingFile(string fullJsonPath)
{
if (System.IO.File.Exists(fullJsonPath))
{
File.Delete(fullJsonPath);
}
}
private void SaveToFile(string jsonFileName, string fullJsonPath)
{
StringBuilder builder = new StringBuilder();
JsonTemplate template = new JsonTemplate();
template.name = jsonFileName;
template.annotates = jsonFileName + ".wav";
System.IO.File.WriteAllText(fullJsonPath, Newtonsoft.Json.JsonConvert.SerializeObject(template));
Console.WriteLine(jsonFileName + " has been created");
}
private class JsonTemplate
{
public string name { get; set; }
public string annotates { get; set; }
public int sampleRate { get; set; } = 44100;
}
Edit
I just noticed that you are on MacOS. I do not have access nor much knowledge on programming through MacOS. At minimum, you will need to update the location as to where the directory is saved.

Related

Problem Saving and Loading Json file in Unity

I'm currently trying to use gestures recognizers in Unity3D. For this I need a library of gestures to be compared with the gesture I'm making.
I'm using a script to save and load from another Unity user since I have no idea how to do it myself.
The problem I'm facing is:
If I save the gestures as json file during gameplay, I can compare them in the same run. But if I restart the run, it stops being able to read the json file and returns NULL or no match as if there were nothing in the json file.
[Serializable]
public class GestureTemplates
{
public List<DrawnGesture> templates;
public GestureTemplates()
{
templates = new List<DrawnGesture>();
}
}
private string gestureFileName = "gestures.json";
void Start () {
LoadTemplates();
}
private void SaveTemplates()
{
string filePath = Application.dataPath + "/streamingAssets/" + gestureFileName;
string saveData = JsonUtility.ToJson(templates);
File.WriteAllText(filePath, saveData);
Debug.Log("Template Saved");
}
private void LoadTemplates()
{
templates = new GestureTemplates();
string filePath = Path.Combine(Application.streamingAssetsPath, gestureFileName);
if (File.Exists(filePath))
{
string data = File.ReadAllText(filePath);
templates = JsonUtility.FromJson<GestureTemplates>(data);
}
}
What I've noticed is it takes a while to save, but it does in fact save since it calls the debug.Log line and the save file can be used in the same run.
Any help would be highly appreciated.
Edit: Nevermind. It's not saving either. It's saving as a Json file with an empty list. The variable is working on the run, but it's not saving nor loading.

How to direct an EDI file down a certain path in Control flow task

So I have an SSIS package that I am working on right now that requires something that I have yet to do. The package currently just has a For Each Loop container that stores the value of the file name it finds in the User::WatchFolder to a variable and then moves that file to another folder for a process to pick up. What I have been tasked with is augmenting this so that the process remains unchanged for .837 file that does not contain a certain set of character but redirecting the files that come through with the word 'RELAY' in them. From there I also need to open up this EDI file and replace the string '5010' with '5010R', save it and move to a separate folder.
I have moved data in a Data flow task based on certain criteria using a Conditional Split, but this is not data from a table or database, so I'm not sure if this can be accomplished in a Control Flow task. Also, I'm assuming that the string can be replaced via a Script Task, but I'm not sure (again) if this is something that would live in the Control flow or in some sort of Data Flow task.
This is what the package looks like thus far.
SSIS Package so far
EDIT: So far I have created a script task using C# to find and replace the values using ReadFile(FilePath) into a variable called FileContent and then doing a FileContent.Replace("someText","someOtherText")
and then writing the contents back to the file using StreamReader and StreamWriter. That part seems to work fine, but I'm not sure now how to move the file depending on whether it contains a certain value in the FileName.
public void Main()
{
String ErrInfo = "";
String FilePath = Dts.Variables["User::FileName"].Value.ToString();
try
{
String FileContent; //Variable to store File Contents
FileContent = ReadFile(FilePath, ErrInfo);
if (ErrInfo.Length > 0)
{
Dts.Log("Error while reading File " + FilePath, 0, null);
Dts.Log(ErrInfo, 0, null);
Dts.TaskResult = (int)ScriptResults.Failure;
return;
}
//FileContent Before Replace;
MessageBox.Show(FileContent);
//Find and Replace --> Modify WHERE clause
FileContent = FileContent.Replace(
"Relay5010 ",
"Relay5010R"
);
//FileContent After Replace;
MessageBox.Show(FileContent);
Dts.Variables["User::FileContent"].Value = FileContent;
//Write the contents back to File
WriteToFile(FilePath, FileContent, ErrInfo);
if (ErrInfo.Length > 0)
{
Dts.Log("Error while writing File " + FilePath, 0, null);
Dts.Log(ErrInfo, 0, null);
Dts.TaskResult = (int)ScriptResults.Failure;
return;
}
}
catch (Exception e)
{
Dts.Log(e.Message, 0, null);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
public String ReadFile(String FilePath, String ErrInfo)
{
String strContents;
StreamReader sReader;
try
{
sReader = File.OpenText(FilePath);
strContents = sReader.ReadToEnd();
sReader.Close();
return strContents;
}
catch (Exception e)
{
MessageBox.Show(ErrInfo);
ErrInfo = e.Message;
return "";
}
}
public void WriteToFile(String FilePath, String strContents, String ErrInfo)
{
StreamWriter sWriter;
try
{
sWriter = new StreamWriter(FilePath);
sWriter.Write(strContents);
sWriter.Close();
}
catch (Exception e)
{
MessageBox.Show(ErrInfo);
ErrInfo = e.Message;
}
}
#region ScriptResults declaration
/// <summary>
/// This enum provides a convenient shorthand within the scope of this class for setting the
/// result of the script.
///
/// This code was generated automatically.
/// </summary>
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}
Truth is, I'd love to leave the existing files alone and let them run down their normal path and just divert the ones containing the "R" value and those can have the script task applied to them. Is there possibly a way other than another script task? I am just trying to see if SSIS lends me another tool so that this can be done in the most straight forward way possible
This is my first question posted as well so if there is something else I missed here, I won't be offended if it is pointed out!

Writing JSON file in Xamarin PCL

As System.IO.File is not available in Xamarin PCL, I have heard that the only way out of the problem of writing JSON file is to use Streams. However, I haven't found a good link as in how to use them easily. Moreover, is this the only way out or is there anyother method available that can help me in writing output in a JSON format.
As #Jason says, you can use PclStorage.
Otherwise you can use DependencyService and write your code in Platform specific projects.
You can take a look to this repo
TestReadFile
This is something for Android
[assembly: Xamarin.Forms.Dependency(typeof(FilesImplementation))]
namespace TestReadFile.Droid
{
public class FilesImplementation : IFiles
{
public FilesImplementation()
{
}
public string ReadTextFile(string path, string fileName)
{
//throw new NotImplementedException();
using (System.IO.StreamReader sr = new System.IO.StreamReader(System.IO.Path.Combine(path, fileName))){
string line = sr.ReadToEnd();
sr.Close();
return line;
}
}
private string creaFileName(string directory, string fileName) {
string path = RootDirectory();
string file = System.IO.Path.Combine(path, fileName);
return file;
}
public void WriteTextFile(string path, string fileName, string stringToWrite)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(System.IO.Path.Combine(path, fileName),false))
{
sw.WriteLine(stringToWrite);
sw.Close();
}
}
public string RootDirectory()
{
File path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);
return path.AbsolutePath;
}
}
}
And this is PCL interface
public interface IFiles
{
string ReadTextFile(string path, string fileName);
void WriteTextFile(string path, string filename, string stringToWrite);
string RootDirectory();
}

Change VS reload files behaviour

I am having one VSIX project, which will made some changes in Project.json file of ASPNET5 project. am using the following to edit .json file.
ProjectJson jsonObj = JsonConvert.DeserializeObject<ProjectJson>(jsonContents);
jsonObj = JsonConvert.DeserializeObject<ProjectJson>(jsonContents);
var resultJson = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
JsonSerializer serializer = new JsonSerializer();
using (StreamWriter sw = new StreamWriter(projectObjects.ProjectJsonPath))
{
var writer = new JsonTextWriter(sw);
serializer.Serialize(writer, resultJson);
}
// File.WriteAllText(projectObjects.ProjectJsonPath, resultJson);
by using both stream writer and writealltext am getting the following message in ASPNET 5 project
The file has unsaved changes inside this editor and has been changed
externally. do you want to reload it?
how to edit .json file without getting the above message?
Its actually the opposite. Since the environment thinks that the file wants to reload with unsaved changes.
You should uncheck the detect file changes. And when you do, it won't detect the external changes and will not warn you, beware though, that if you try to save the file after it has been modified you will lose the external change.(not a problem in your case I guess) and in order to see the changes you will have to close, not save the file and reopen it.
Source : VS2008: Disable asking whether to reload files changed outside the IDE
This is the option you want to check programmatically. I don't know how exactly you can do that but you can find topics about settings at MSDN (Creating an option page and Creating a setting category). Using those topics you can have a sense of how options are created.
Basically what you need to do is to load VS settings file (VS.vssettings) and inject another Xml line. (Have a look at Examining the Settings File section on MSDN)
Update
To be extremely clear the VS settings file is located under
Documents\Your_VS_Version\Settings\CurrentSettings.vssettings
and you need to load the xml and change 'AutoloadExternalChanges' to value 'true'.
You need to tell the environment to ignore file changes. This can be achieved using the IVsFileChangeEx and IVsDocDataFileChangeControl interfaces.
Here is a utility class (derived from the original Visual Studio 2010 SDK Managed Package Framework sample that you can still find here: http://www.getcodesamples.com/src/8641B4F/98B3955E) that should help:
using (SuspendFileChanges suspend = new SuspendFileChanges(site, filePath))
{
// do something with files
suspend.Sync(); // if you optionally want to tell the IDE it has changed
}
The utility class:
public class SuspendFileChanges: IDisposable
{
private readonly IServiceProvider _serviceProvider;
private readonly List<string> _urls;
private readonly IVsDocDataFileChangeControl[] _controls;
public SuspendFileChanges(IServiceProvider serviceProvider, string url)
: this(serviceProvider, new string[] { url })
{
}
public SuspendFileChanges(IServiceProvider serviceProvider, params string[] urls)
{
if (serviceProvider == null)
throw new ArgumentNullException("serviceProvider");
if (urls == null)
throw new ArgumentNullException("urls");
_serviceProvider = serviceProvider;
_urls = new List<string>(urls);
_controls = new IVsDocDataFileChangeControl[_urls.Count];
// or use Package.GetGlobalService ...
IVsRunningDocumentTable rdt = (IVsRunningDocumentTable)serviceProvider.GetService(typeof(SVsRunningDocumentTable));
IVsFileChangeEx fileChange = (IVsFileChangeEx)serviceProvider.GetService(typeof(SVsFileChangeEx));
for(int i = 0; i < _urls.Count; i++)
{
string url = _urls[i];
if (url == null)
continue;
fileChange.IgnoreFile(0, url, 1);
IVsHierarchy hierarchy;
uint itemId;
uint docCookie;
IntPtr docData;
rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, url, out hierarchy, out itemId, out docData, out docCookie);
if (docData != IntPtr.Zero)
{
_controls[i] = Marshal.GetObjectForIUnknown(docData) as IVsDocDataFileChangeControl;
if (_controls[i] != null)
{
_controls[i].IgnoreFileChanges(1);
}
Marshal.Release(docData);
}
}
}
public void Sync()
{
IVsFileChangeEx fileChange = (IVsFileChangeEx)_serviceProvider.GetService(typeof(SVsFileChangeEx));
if (fileChange == null)
throw new InvalidOperationException();
foreach (string url in _urls)
{
if (url == null)
continue;
fileChange.SyncFile(url);
}
}
public void Dispose()
{
IVsFileChangeEx fileChange = (IVsFileChangeEx)_serviceProvider.GetService(typeof(SVsFileChangeEx));
if (fileChange != null)
{
foreach (string url in _urls)
{
if (url == null)
continue;
fileChange.IgnoreFile(0, url, 0);
}
}
foreach (IVsDocDataFileChangeControl control in _controls)
{
if (control != null)
{
control.IgnoreFileChanges(0);
}
}
}
}

SSIS/C#: Script Task, C# script to look at directory and store the name of 1 file in a variable

Basically I've written a C# script for a Script task in SSIS that looks in a User::Directory for 1 csv, if & only if there is one file, it stores that in the instance variable which then maps to the package variables of SSIS.
When I exicute, it gives me the red filled in box of the Script task. I think it's related to how I'm looking at the directory, but I'm not sure.
Please help!
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
namespace ST_e8b4bbbddb4b4806b79f30644240db19.csproj
{
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
private String fileName = "";
private String RootDirictory;
private String FilePath;
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
public ScriptMain()
{
RootDirictory = Dts.Variables["RootDir"].Value.ToString();
FilePath = RootDirictory + "\\" + "SourceData" + "\\";
}
public void setFileName()
{
DirectoryInfo YDGetDir = new DirectoryInfo(FilePath);
FileInfo[] numberOfFiles = YDGetDir.GetFiles(".csv");
if (numberOfFiles.Length < 2)
{
fileName = numberOfFiles[0].ToString();
}
int fileNameLen = fileName.Length;
String temp = fileName.Substring(0, fileNameLen - 5);
fileName = temp;
}
public void mapStateToPackage()
{
if((fileName!=null)||(fileName!=""))
{
Dts.Variables["ExDFileName"].Value = fileName;
}
}
public void Main()
{
setFileName();
mapStateToPackage();
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}
This could simply be done using Foreach loop container as explained in this Stack Overflow question, which was asked by you. :-)
Anyway, to answer your question with respect to Script Task code that you have provided. Below mentioned reasons could be cause of the issues:
You are looking for .csv. This won't return any results because you are looking for a file with no name but extension .csv. The criteria should be *.csv
If you are looking for exactly one file, then the condition if (numberOfFiles.Length < 2) should be changed to if (numberOfFiles.Length == 1)
The section of code after the if section which extracts the file name should be within the above mentioned if condition and not out side of it. This has to be done to prevent applying substring functionality on an empty string.
Modified code can be found under the Script Task Code section.
Sorry, I took the liberty to simplify the code a little. I am not suggesting this is the best way to do this functionality but this is merely an answer to the question.
Hope that helps.
Script Task Code:
C# code that can be used only in SSIS 2008 and above.
/*
Microsoft SQL Server Integration Services Script Task
Write scripts using Microsoft Visual C# 2008.
The ScriptMain is the entry point class of the script.
*/
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
namespace ST_3effcc4e812041c7a0fea69251bedc25.csproj
{
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
Variables varCollection = null;
String fileName = string.Empty;
String fileNameNoExtension = string.Empty;
String rootDirectory = string.Empty;
String filePath = string.Empty;
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
public void Main()
{
Dts.VariableDispenser.LockForRead("User::RootDir");
Dts.VariableDispenser.LockForWrite("User::ExDFileName");
Dts.VariableDispenser.GetVariables(ref varCollection);
rootDirectory = varCollection["User::RootDir"].Value.ToString();
filePath = rootDirectory + #"\SourceData\";
DirectoryInfo YDGetDir = new DirectoryInfo(filePath);
FileInfo[] numberOfFiles = YDGetDir.GetFiles("*.csv");
if (numberOfFiles.Length == 1)
{
fileName = numberOfFiles[0].ToString();
fileNameNoExtension = fileName.Substring(0, fileName.LastIndexOf("."));
}
if (!String.IsNullOrEmpty(fileNameNoExtension))
{
varCollection["User::ExDFileName"].Value = fileNameNoExtension;
}
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}