How to generate C# code from a SyntaxFactory CompilationUnitSyntax? - roslyn

I am building a simple AST using the code below.
output = SF
.CompilationUnit()
.WithMembers(SF.SingletonList<MemberDeclarationSyntax>(SF.ClassDeclaration("Class1")))
.ToFullString();
Console.WriteLine(output);
The output is this:
classClass1{}
How can I get the output to look like C# code?
class Class1 {
}
ANSWSER: Call NormalizeWhitespace():
output = SF
.CompilationUnit()
.WithMembers(SF.SingletonList<MemberDeclarationSyntax>(SF.ClassDeclaration("Class1")))
.NormalizeWhitespace()
.ToFullString();
Console.WriteLine(output);

Call NormalizeWhitespace():
output = SF
.CompilationUnit()
.WithMembers(SF.SingletonList<MemberDeclarationSyntax>(SF.ClassDeclaration("Class1")))
.NormalizeWhitespace()
.ToFullString();
Console.WriteLine(output);

Related

Saving the output from Lua in C++ with SOL3 to an std::string

I'm trying to implement a lua interpreter to my C++ code. I have implemented a small editor for my project using ImGui and I'm saving the output from the editor to an std::vector.
My attempted implementation of my lua interpeter looks like so;
// header
std::string ExecuteLua();
std::vector<char> m_luaEditorData;
// cpp
std::string Proxy::ExecuteLua()
{
// Load the Lua code from the string
std::string luaCode(m_luaEditorData.data());
// Create a Lua state
sol::state lua;
// Load standard Lua libraries
lua.open_libraries(sol::lib::base, sol::lib::package, sol::lib::string, sol::lib::table);
// Execute the Lua code and store the result
sol::protected_function_result result = lua.script(luaCode);
// Check for errors
if (!result.valid())
{
sol::error error = result;
std::string errorMsg = error.what();
return "Lua error: " + errorMsg;
}
// Get the result as a string
std::string output = lua["tostring"](result.get<sol::object>());
// Return the output
return output;
}
...
if (m_luaEditorData.empty())
m_luaEditorData.push_back('\0');
auto luaEditorFlags = ImGuiInputTextFlags_AllowTabInput | ImGuiInputTextFlags_CallbackResize;
ImGui::InputTextMultiline("##LuaEditor", m_luaEditorData.data(), m_luaEditorData.size(), ImVec2(ImGui::GetWindowContentRegionWidth(), ImGui::GetWindowHeight() - (ImGui::GetTextLineHeight() * 16)), luaEditorFlags, ResizeInputTextCallback, &m_luaEditorData);
...
When I run this code, I only get nil in my output, the correct output to stdout (don't really want it to output here, but to my std::string and when I put in bad code, it throws an exception in sol.hpp. I didn't really find any examples on how I can do this and I'm therefore am trying to figure this out on my own.

How to pass structures into re-integrated autogenerated C++ code in Matlab

I am trying to test some code that has been generated from Matlab into C++.
To do this I am attempting to integrate and run the generated C++ code back into Matlab.
Here's the function I am trying to use (in Matlab pre-autogen)
function out = getRotationMatrix(aStruct)
out = aStruct.bank_rad*aStruct.heading_rad+aStruct.pitch_rad;
end
I autogenerate it using this ...
function varargout = AutoGenCode(varargin)
% Here we are attempting to generate a C++ class from a matlab function via a
% hosting function
% initialise
varargout = {};
% create instance of config object
cfg = coder.config('LIB');
% config options
cfg.MaxIdLength = int32(64);
cfg.TargetLang = 'C++';
cfg.CppPreserveClasses = 1;
cfg.EnableCustomReplacementTypes = true;
cfg.ReplacementTypes.uint32 = 'uint32_t';
cfg.CppInterfaceStyle = 'Methods';
cfg.CppInterfaceClassName = 'FrameTransformation';
cfg.FilePartitionMethod = 'MapMFileToCFile'; % or 'MapMFileToCFile' SingleFile
cfg.EnableVariableSizing = false;
%cfg.PreserveVariableNames = 'UserNames'; % Worse
%cfg.IncludeInitializeFcn = true;
cfg.PassStructByReference = true;
thisStruct.bank_rad = 2.1;
thisStruct.heading_rad = 3.1;
thisStruct.pitch_rad = 3.1;
codegen -config cfg getRotationMatrix -args {thisStruct} -report -preservearraydims -std:c++11
end
To move to another area (\unzipped) I use packNGo
load([pwd,'\codegen\lib\getRotationMatrix\buildInfo.mat'])
packNGo(buildInfo,'packType', 'hierarchical','fileName','portzingbit')
Now when i try to re-integrate it i am using clib
cd 'D:\thoros\Components\Frame Transformation Service\FT_V2\unzippedCode'
clibgen.generateLibraryDefinition('FrameTransformation.h','Libraries',{'getRotationMatrix.lib'})
build(defineFrameTransformation)
addpath('D:\thoros\Components\Frame Transformation Service\FT_V2\unzippedCode\FrameTransformation')
Where I had to define the < SHAPE > parameter in the defineFrameTransformation.mlx manually to be 1
When i try and use the function I cant pass a structure without an error
A = clib.FrameTransformation.FrameTransformation()
thisStruct.bank_rad = 2.1;
thisStruct.heading_rad = 3.1;
thisStruct.pitch_rad = 3.1;
>> A.getRotationMatrix(thisStruct)
I get the following error
Unrecognized method, property, or field 'getRotationMatrix' for class 'clib.FrameTransformation.FrameTransformation'.
The problem disappears if rewrite and regenerate the function to accept non-structure input e.g. double.
By using the summary function i can see that the call to getRotationMatrix should be of type clib.FrameTransformation.struct0_T
However i can't seem to create a variable of this type.
summary(defineFrameTransformation)
MATLAB Interface to FrameTransformation Library
Class clib.FrameTransformation.struct0_T
No Constructors defined
No Methods defined
No Properties defined
Class clib.FrameTransformation.FrameTransformation
Constructors:
clib.FrameTransformation.FrameTransformation()
clib.FrameTransformation.FrameTransformation(clib.FrameTransformation.FrameTransformation)
Methods:
double getRotationMatrix(clib.FrameTransformation.struct0_T)
No Properties defined
So how is one supposed to pass structures to C++ libraries in Matlab ??? what am i doing wrong.
Note Matlab 2020B, windows, Visual studio 2019
Ah, you were so close to the solution :)
There was a small catch there.
When you are using clibgen.generateLibraryDefinition() you have to make sure that all the type definition are included in the header file. In your case the definition of struct0_T was presnet inside getRotationMatrix_types.h file.
So you will have to include both the headers using below command :
clibgen.generateLibraryDefinition(["FrameTransformation.h","getRotationMatrix_types.h"],"PackageName","mylib",'Libraries',{'getRotationMatrix.lib'})
Now you will have to fill the additional details required in the definition file.
Once you finish that step, you can use below commands to successfully use the interface
build(definemylib)
addpath('\\mathworks\home\dramakan\MLAnswers\CLIB_With_Codegen\ToPort\portzingbit\mylib')
A = clib.mylib.FrameTransformation
s = clib.mylib.struct0_T
s.bank_rad =2.1;
s.heading_rad =3.1;
s.pitch_rad=3.1;
A.getRotationMatrix(s)
I could get below output in R2021b
>> A.getRotationMatrix(s)
ans =
9.6100
Additionally check if you can use MATLAB Coder MEX instead of doing all these circus. You can call the generated code directly in MATLAB using MEX. You can refer below documentation :
https://www.mathworks.com/help/coder/gs/generating-mex-functions-from-matlab-code-at-the-command-line.html
If you have Embedded Coder (the line cfg.ReplacementTypes.uint32 = 'uint32_t' suggests you do), then you can use SIL to do what you're proposing with just a few lines of code:
cfg.VerificationMode = 'SIL';
thisStruct.bank_rad = 2.1;
thisStruct.heading_rad = 3.1;
thisStruct.pitch_rad = 3.1;
codegen ...
% Now test the generated code. This calls your actual generated code
% and automatically does all of the necessary data conversion. The code
% is run in a separate process and outputs are returned back
% to MATLAB
getRotationMatrix_sil(thisStruct)
More info is in the doc. If you have tests / scripts already exercising your MATLAB code, you can reuse those with SIL by checking out coder.runTest and the codegen -test option.

Get Returned text from ScriptManager(javascript) - INDESIGN SDK Plugin

I am using javascript inside my Plugin for Indesign CS6.
It is working fine.
But I need the return value from my javascript code now inside my c++ code.
I am using this site as reference:
https://blogs.adobe.com/indesignsdk/running-a-script-from-an-indesign- plug-in/
I need something like that:
scriptRunner->RunScript("function xpto(){return 'Hello World';};xpto()", params);
// fake method
const char *string_return = scriptRunner->getReturnCode();
are there something like that on scriptManager?
ps: it is not a indesign server. I put this tag because this site do not let me create a new tag...
Best Regards,
Use RunScriptParams::QueryScriptRequestData() .
From the SDK documents:
Query the IScriptRequestData that is used to pass arguments and return
the result.
The key is to get the iScript object from the 'RunScriptParams' object after the script has run. Then is it straight forward. Here is some sample code:
RunScriptParams params(scriptRunner);
IScriptRequestData* requestData = params.QueryScriptRequestData();
params.SetUndoMode(RunScriptParams::kFastUndoEntireScript);
if (scriptRunner->RunScript(script,params) != kSuccess) return NULL;
IScript *iScript = params.QueryTarget();
int resultsCount = requestData->GetNumReturnData(iScript);
PMString resultString;
if (resultsCount > 0) {
ScriptReturnData resultOne = requestData->GetNthReturnData(iScript,0);
ScriptData scriptReturnOne = resultOne.GetReturnValue();
scriptReturnOne.GetPMString(resultString);
}
The return value is in resultString.

Json regex deserialization with JSON.Net

I'm trying to read the following example json from a text file into a string using the JSON.Net parsing library.
Content of C:\temp\regeLib.json
{
"Regular Expressions Library":
{
"SampleRegex":"^(?<FIELD1>\d+)_(?<FIELD2>\d+)_(?<FIELD3>[\w\&-]+)_(?<FIELD4>\w+).txt$"
}
}
Example code to try and parse:
Newtonsoft.Json.Converters.RegexConverter rConv = new Newtonsoft.Json.Converters.RegexConverter();
using (StreamReader reader = File.OpenText(libPath))
{
string foo = reader.ReadToEnd();
JObject jo = JObject.Parse(foo);//<--ERROR
//How to use RegexConverter to parse??
Newtonsoft.Json.JsonTextReader jtr = new Newtonsoft.Json.JsonTextReader(reader);
JObject test = rConv.ReadJson(jtr);//<--Not sure what parameters to provide
string sampleRegex = test.ToString();
}
It seems I need to use the converter, I know the code above is wrong, but I can't find any examples that describe how / if this can be done. Is it possible to read a regular expression token from a text file to a string using JSON.Net? Any help is appreciated.
UPDATE:
Played with it more and figured out I had to escape the character classes, once I made the correction below I was able to parse to a JObject and use LINQ to query for the regex pattern.
Corrected content C:\temp\regeLib.json
{
"Regular Expressions Library":
{
"SampleRegex":"^(?<FIELD1>\\d+)_(?<FIELD2>\\d+)_(?<FIELD3>[\\w\\&-]+)_(?<FIELD4>\\w+).txt$"
}
}
Corrected code
using (StreamReader reader = File.OpenText(libPath))
{
string content = reader.ReadToEnd().Trim();
JObject regexLib = JObject.Parse(content);
string sampleRegex = regexLib["Regular Expressions Library"]["SampleRegex"].ToString();
//Which then lets me do the following...
Regex rSampleRegex = new Regex(sampleRegex);
foreach (string sampleFilePath in Directory.GetFiles(dirSampleFiles, "*"))
{
filename = Path.GetFileName(sampleFilePath);
if (rSampleRegex.IsMatch(filename))
{
//Do stuff...
}
}
}
Not sure if this is the best approach, but it seems to work for my case.
i don't understand why you have to store such a small regex in a json file, are you going to expand the regex in the future?
if so, rather than doing this
JObject regexLib = JObject.Parse(content);
string sampleRegex = regexLib["Regular Expressions Library"]["SampleRegex"].ToString();
Consider using json2csharp to make classes, at least it's strongly-typed and make it more maintainable.
I think a more appropriate json would look like this (assumptions):
{
"Regular Expressions Library": [
{
"SampleRegex": "^(?<FIELD1>\\d+)_(?<FIELD2>\\d+)_(?<FIELD3>[\\w\\&-]+)_(?<FIELD4>\\w+).txt$"
},
{
"SampleRegex2": "^(?<FIELD1>\\d+)_(?<FIELD2>\\d+)_(?<FIELD3>[\\w\\&-]+)_(?<FIELD4>\\w+).txt$"
}
]
}
It would make more sense this way to store a regex in a "settings" file

Capturing Snap from Camera using Win RT

I am Wrting code to capture image from camera.Below is the code I have written.
Here method CapturePhotoToStorageFileAsync doesnot return.
auto MediaCap = ref new Windows::Media::Capture::MediaCapture();
auto ImageProp = ref new Windows::Media::Capture::ImageEncodingProperties ();
ImageProp->Height = 240;
ImageProp->Width = 320;
ImageProp->Subtype = "JPEG";
Windows::Storage::StorageFile^ strFile;
auto res = MediaCap->CapturePhotoToStorageFileAsync(ImageProp,strFile);
res->Completed = ref new AsyncActionCompletedHandler([](IAsyncAction ^action)
{
//action->GetResults();
//action->Start();
///action->Close();
});
res->Start();
Am I missing something here??
Did you want to show UI to the user or just silently capture? The only C++ camera sample I've found uses CameraCaptureUI and CaptureFileAsync - then the operation is getting a StorageFile^ back.
If you're deliberately using CapturePhotoToStorageFileAsync, check your capabiities.
The Issue is resolved
I Added code for
InitializeAsync()
Created file to be used to store image
using
Windows::Storage::StorageFileRetrievalOperation^ CreateFileOp = Windows::Storage::KnownFolders::PicturesLibrary->CreateFileAsync("Test.jpg");
I found Java script article and implemented in c++.
http://code.msdn.microsoft.com/windowsdesktop/Media-Capture-Sample-adf87622/sourcecode?fileId=43837&pathId=1754477665