This commit is contained in:
Karan Singh 2021-04-11 19:21:11 +05:30
Коммит 38632279c9
35 изменённых файлов: 3891 добавлений и 0 удалений

350
.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,350 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/

481
AutoMapper/AutoMapper.cs Normal file
Просмотреть файл

@ -0,0 +1,481 @@
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
namespace JsonToJsonMapper
{
public class AutoMapper : IDisposable
{
public MappingRule Mapping { get; set; }
JsonSerializerSettings JsonConvertSettings { get; set; }
readonly TransformationFactory handler;
public AutoMapper(string autoMapperConfig)
{
JsonConvertSettings = new JsonSerializerSettings();
JsonConvertSettings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
JsonConvertSettings.DateParseHandling = DateParseHandling.None;
handler = new TransformationFactory();
var config = JsonConvert.DeserializeObject<AutoMapperConfig>(autoMapperConfig);
Mapping = config.MappingRuleConfig;
if (Mapping == null || !Mapping.TruthTable.Any())
throw new Exception("Invalid mapping json");
var scripts = new Dictionary<string, Script>();
// Compile and Load all the scripts in memory
if (config.Scripts != null)
{
foreach (var script in config.Scripts)
{
if (script.Reference != null)
{
// With assembly import
ScriptOptions options = ScriptOptions.Default.AddReferences(script.Reference.Assembly).WithImports(script.Reference.NameSpace);
scripts.Add(script.Name, CSharpScript.Create<string>(script.Code, options, globalsType: typeof(ScriptHost)));
}
else
scripts.Add(script.Name, CSharpScript.Create<string>(script.Code, globalsType: typeof(ScriptHost)));
}
}
// Load all the handlers
handler.AddHandlers(new TransposeHandler());
handler.AddHandlers(new TypeConverterHandler());
handler.AddHandlers(new ValueMappingHandler());
handler.AddHandlers(new RoslynScriptHandler(scripts));
handler.AddHandlers(new FunctionHandler());
}
/// <summary>
/// Transforms into a type
/// </summary>
/// <param name="inputJson"></param>
/// <returns></returns>
public object Transform(string inputJson)
{
if (Mapping.DestinationType == null)
throw new Exception("Invalid mapping json");
return Execute((JObject)JsonConvert.DeserializeObject(inputJson, JsonConvertSettings), Mapping);
}
public object Transform(JObject jObj)
{
if (Mapping.DestinationType == null)
throw new Exception("Invalid mapping json");
return Execute(jObj, Mapping);
}
/// <summary>
/// Creates an intance of destination type and sets the properties
/// </summary>
/// <param name="jsonObject"></param>
/// <param name="mapping"></param>
/// <returns></returns>
private object Execute(JObject jsonObject, MappingRule mapping)
{
Type type = Type.GetType(mapping.DestinationType, true);
var entity = Activator.CreateInstance(type);
// Set the value for each item in destinationType
foreach (var rule in mapping.TruthTable)
{
var propertyInfo = entity.GetType().GetProperty(rule.DestinationColumn);
if (propertyInfo != null)
{
if (rule.ComplexType == null)
{
string valueType;
var value = GetValue(jsonObject, rule.SourceColumn, rule.TransformValue, out valueType);
if (value != null)
{
if (rule.DataType == null)
rule.DataType = valueType;
var finalValue = handler.GetHandler<TypeConverterHandler>()
.Run(JObject.FromObject(rule), JObject.FromObject(new { value = value }));
propertyInfo.SetValue(entity, finalValue, null);
}
else
propertyInfo.SetValue(entity, value, null);
}
else
{
propertyInfo.SetValue(entity, Execute(jsonObject, rule.ComplexType), null);
}
}
}
return entity;
}
/// <summary>
/// Transforms into Json
/// </summary>
/// <param name="inputJson"></param>
/// <param name="ignoreNullVaue"></param>
/// <returns></returns>
public string TransformIntoJson(string inputJson, bool ignoreNullValue)
{
Mapping.IgnoreNullValue = ignoreNullValue;
return JsonConvert.SerializeObject(ExecuteToJson((JObject)JsonConvert.DeserializeObject(inputJson, JsonConvertSettings), Mapping));
}
public JObject TransformIntoJson(JObject jObj, bool ignoreNullValue)
{
Mapping.IgnoreNullValue = ignoreNullValue;
return ExecuteToJson(jObj, Mapping);
}
/// <summary>
/// Transforms into json. Uses the IgnoreNullValue from the config, default is true.
/// </summary>
/// <param name="inputJson"></param>
/// <returns></returns>
public string TransformIntoJson(string inputJson)
{
return JsonConvert.SerializeObject(ExecuteToJson((JObject)JsonConvert.DeserializeObject(inputJson, JsonConvertSettings), Mapping));
}
public string TransformIntoJson(JObject jObj)
{
return JsonConvert.SerializeObject(ExecuteToJson(jObj, Mapping));
}
protected JObject ExecuteToJson(JObject jsonObject, MappingRule mapping)
{
var jsonString = new JsonTransform();
foreach (var rule in mapping.TruthTable)
{
// handle transpose
if (rule.TransformValue != null && rule.TransformValue.Type != null && string.Equals(rule.TransformValue.Type, "promoteArrayToProperty", StringComparison.OrdinalIgnoreCase))
{
Dictionary<string, object> transposeResponse = handler.GetHandler<TransposeHandler>()
.Run(JObject.FromObject(rule), jsonObject);
if (transposeResponse != null)
jsonString.Json.AddRange(transposeResponse);
}
else if (!string.IsNullOrEmpty(rule.DestinationColumn))
{
if (rule.ComplexType == null)
{
// Handle Jvalue
string valueType;
string destinationValue = rule.DestinationColumn.StartsWith("$") ? jsonObject.SelectToken(rule.DestinationColumn).ToString() : rule.DestinationColumn;
var value = GetValue(jsonObject, rule.SourceColumn, rule.TransformValue,out valueType);
if (rule.DataType == null)
rule.DataType = valueType;
var finalValue = handler.GetHandler<TypeConverterHandler>()
.Run(JObject.FromObject(rule), JObject.FromObject(new { value = value }));
if (finalValue != null || finalValue.Type != JTokenType.Null || (finalValue == null && !mapping.IgnoreNullValue) || (finalValue.Type == JTokenType.Null && !mapping.IgnoreNullValue))
jsonString.Json.Add(destinationValue, finalValue);
}
else if (rule.ComplexType.DataType != null && rule.ComplexType.DataType.ToUpperInvariant().Equals("JARRAY"))
{
var result = TransformJArray(jsonObject, rule.ComplexType, mapping.IgnoreNullValue);
if (result != null)
jsonString.Json.Add(rule.DestinationColumn, result);
}
else
{
// Recursive call to handle complex type
var result = ExecuteToJson(jsonObject, rule.ComplexType);
if (result != null)
{
if (!string.IsNullOrWhiteSpace(rule.DataType))
jsonString.Json.Add(rule.DestinationColumn, handler.GetHandler<TypeConverterHandler>()
.Run(JObject.FromObject(rule), JObject.FromObject(new { value = result })));
else
jsonString.Json.Add(rule.DestinationColumn, result);
}
}
}
}
return JObject.FromObject(jsonString);
}
private dynamic TransformJArray(JObject jsonObject, MappingRule mapping, bool ignoreNullVaue)
{
var tokens = jsonObject.SelectTokens(mapping.Node);
JArray array = new JArray();
bool hasToken = false;
foreach (var item in tokens)
{
hasToken = true;
if (string.Equals(item.GetType().Name, "jarray", StringComparison.OrdinalIgnoreCase))
{
JArray itemJArray = (JArray)item;
if (itemJArray.Any())
{
foreach (var a in itemJArray)
{
var o = (JToken)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(ExecuteToJson((JObject)a, mapping)), JsonConvertSettings);
array.Add(o);
}
}
else
{
itemJArray.Add(new JObject(new JProperty("temp", "")));
array.Add((JToken)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(ExecuteToJson((JObject)item.FirstOrDefault(), mapping))));
}
}
else
{
array.Add((JToken)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(ExecuteToJson((JObject)item, mapping)), JsonConvertSettings));
}
}
if (!hasToken && mapping.IgnoreEmptyArray)
return null;
return array;
}
private string GetValue(JObject jsonObject, string key, Transform transform, out string valueType)
{
string value = null;
valueType = "string";
if (transform != null && transform.Type != null && transform.Type.Equals("SCRIPT", StringComparison.OrdinalIgnoreCase))
{
return handler.GetHandler<RoslynScriptHandler>().Run(JObject.FromObject(transform), jsonObject);
}
else if (transform != null && transform.Type != null && transform.Type.Equals("FUNCTION", StringComparison.OrdinalIgnoreCase))
{
return handler.GetHandler<FunctionHandler>().Run(JObject.FromObject(transform), jsonObject);
}
else if (!string.IsNullOrEmpty(key) && key.StartsWith("$"))
{
if (!key.ToUpperInvariant().Contains("[{PARENT}]"))
{
JToken token = jsonObject.SelectToken(key);
if (token != null && token.Value<dynamic>() != null)
{
valueType = token.Type.ToString();
string tokenValue = token.ToString();
if (token.GetType().Name.Equals("JVALUE", StringComparison.OrdinalIgnoreCase) && token.Type == JTokenType.Null)
value = null;
else if (valueType.Equals("Date", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(tokenValue))
{
string val = (token.Parent.ToString().Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries).Length > 1)? token.Parent.ToString().Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries)[1] : tokenValue;
value = val.Replace("\"", "").Trim();
}
else if (valueType.Equals("Boolean", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(tokenValue))
{
value = tokenValue.ToLowerInvariant();
}
else
{
value = tokenValue;
}
}
else
value = null;
}
else
{
JContainer json;
json = jsonObject.Parent;
for (int i = 2; i < key.Split(new string[] { "[{parent}]" }, System.StringSplitOptions.None).Length; i++)
{
json = json.Parent;
}
JToken valueToken = json.SelectToken(key.Replace("[{parent}].", "").Replace("$.", ""));
if (valueToken != null)
{
valueType = valueToken.Type.ToString();
if (valueToken.Type == JTokenType.Array || valueToken.Type == JTokenType.Object)
value = valueToken.ToString().Replace("\r", "").Replace("\n", "").Replace("\t", "");
else if (valueToken.Value<string>() != null)
{
value = valueToken.ToString();
}
else
value = null;
}
else
value = null;
}
}
else
{
var jsonobjectvalue = jsonObject.GetValue(key, StringComparison.OrdinalIgnoreCase);
if (jsonobjectvalue == null || jsonobjectvalue.Type == JTokenType.Null)
value = null;
else
{
valueType = jsonobjectvalue.Type.ToString();
value = jsonobjectvalue.ToString();
if (value.StartsWith("\""))
value = value.Substring(1);
if (value.EndsWith("\""))
value = value.Substring(0, value.Length - 1);
}
}
if (transform != null)
value = handler.GetHandler<ValueMappingHandler>()
.Run(JObject.FromObject(transform), JObject.FromObject(new { value = value }));
return value;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
Mapping = null;
}
}
public class AutoMapperConfig
{
public List<ScriptDefinitions> Scripts { get; set; }
public MappingRule MappingRuleConfig { get; set; }
}
public class MappingRule
{
public string DestinationType { get; set; }
public string DataType { get; set; }
public string Node { get; set; }
public bool IgnoreEmptyArray { get; set; }
public bool IgnoreNullValue { get; set; } = true;
public List<Rule> TruthTable { get; set; }
public MappingRule()
{
TruthTable = new List<Rule>();
}
}
public class Rule
{
public string SourceColumn { get; set; }
public string DestinationColumn { get; set; }
public string DataType { get; set; }
public string Format { get; set; }
public MappingRule ComplexType { get; set; }
public Transform TransformValue { get; set; }
public Rule(string sourceColumn, string destinationColumn, string dataType)
{
SourceColumn = sourceColumn;
DestinationColumn = destinationColumn;
DataType = dataType;
}
public Rule(string sourceColumn, string destinationColumn, string dataType, string format)
{
SourceColumn = sourceColumn;
DestinationColumn = destinationColumn;
DataType = dataType;
Format = format;
}
public Rule(string sourceColumn, string destinationColumn, string dataType, MappingRule mappingRule)
{
SourceColumn = sourceColumn;
DestinationColumn = destinationColumn;
DataType = dataType;
ComplexType = mappingRule;
}
public Rule(string sourceColumn, string destinationColumn, string dataType, MappingRule mappingRule, Transform transform)
{
SourceColumn = sourceColumn;
DestinationColumn = destinationColumn;
DataType = dataType;
ComplexType = mappingRule;
TransformValue = transform;
}
public Rule(string sourceColumn, string destinationColumn, string dataType, Transform transform)
{
SourceColumn = sourceColumn;
DestinationColumn = destinationColumn;
DataType = dataType;
TransformValue = transform;
}
public Rule(string sourceColumn, string destinationColumn, string dataType, string format, Transform transform)
{
SourceColumn = sourceColumn;
DestinationColumn = destinationColumn;
DataType = dataType;
Format = format;
TransformValue = transform;
}
public Rule()
{
SourceColumn = string.Empty;
DestinationColumn = string.Empty;
DataType = string.Empty;
}
}
public class Transform
{
public string Type { get; set; }
public string PrependKeyText { get; set; }
public List<ConvertValue> ValueMapping { get; set; }
public string DefaultValue { get; set; }
public string ScriptName { get; set; }
public List<dynamic> Params { get; set; }
public string KeyLookupField { get; set; }
public string ValueLookupField { get; set; }
public string Function { get; set; }
public string Delimeter { get; set; }
public string CompareToValue { get; set; }
public string ReturnValue { get; set; }
public string IgnoreEmptyParams { get; set; }
public int Index { get; set; }
}
public class ConvertValue
{
public string ExistingValue { get; set; }
public string NewValue { get; set; }
public ConvertValue(string existingValue, string newValue)
{
ExistingValue = existingValue;
NewValue = newValue;
}
}
public class JsonTransform
{
[JsonExtensionData]
public Dictionary<string, object> Json { get; set; }
public JsonTransform()
{
Json = new Dictionary<string, object>();
}
}
public class ScriptDefinitions
{
public string Name { get; set; }
public string Code { get; set; }
public Script ScriptIL { get; set; }
public Reference Reference { get; set; }
}
public class Reference
{
public string Assembly { get; set; }
public string NameSpace { get; set; }
}
public class ScriptHost
{
public string Args { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,20 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JsonToJsonMapper
{
public static class ExtensionMethods
{
public static void AddRange(this Dictionary<string, object> dictA, Dictionary<string, object> dictB)
{
foreach (KeyValuePair<string, object> pair in dictB)
{
dictA[pair.Key] = pair.Value;
}
}
}
}

Просмотреть файл

@ -0,0 +1,291 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
namespace JsonToJsonMapper
{
public class FunctionHandler : ITransformationHandler
{
public dynamic Run(JObject transform, JObject input)
{
var inputParam = new List<string>();
string nullString = null;
var parameters = transform["Params"].ToObject<List<dynamic>>();
var function = transform["Function"].Value<string>();
string ignoreEmptyValue = transform["IgnoreEmptyParams"] != null ? transform["IgnoreEmptyParams"].Value<string>() : string.Empty;
if (!string.IsNullOrWhiteSpace(function) && function.Equals("URIESCAPEDATASTRING",StringComparison.OrdinalIgnoreCase) == false)
{
if (parameters != null)
{
foreach (var item in parameters)
{
if (!(item is JToken))
if (item.StartsWith("$"))
{
if (!item.ToUpperInvariant().Contains("[{PARENT}]"))
{
var tokens = input.SelectTokens((string)item);
if (tokens != null && tokens.Any())
{
foreach (var i in tokens)
{
if (i.Type == JTokenType.Null)
{
inputParam.Add(nullString);
}
else if (string.IsNullOrWhiteSpace(i.ToString()))
{
if (Convert.ToBoolean(ignoreEmptyValue))
inputParam.Add(nullString);
else
inputParam.Add(i.ToString());
}
else
{
inputParam.Add(i.ToString());
}
}
}
else
{
inputParam.Add(nullString);
}
}
else
{
JContainer json;
json = input.Parent;
for (int i = 2; i < item.Split(new string[] { "[{parent}]" }, System.StringSplitOptions.None).Length; i++)
{
json = json.Parent;
}
JToken valueToken = json.SelectToken(item.Replace("[{parent}].", "").Replace("$.", ""));
if (valueToken != null)
{
if (valueToken.Type == JTokenType.Array || valueToken.Type == JTokenType.Object)
inputParam.Add(valueToken.ToString().Replace("\r", "").Replace("\n", "").Replace("\t", ""));
else if (valueToken.Value<string>() != null)
{
if (string.IsNullOrWhiteSpace(valueToken.ToString()))
{
if (Convert.ToBoolean(ignoreEmptyValue))
inputParam.Add(nullString);
else
inputParam.Add(valueToken.ToString());
}
else
{
inputParam.Add(valueToken.ToString());
}
}
else
inputParam.Add(nullString);
}
else
inputParam.Add(nullString);
}
}
else
inputParam.Add(item);
}
}
}
switch (function.ToUpperInvariant())
{
case "CONCAT":
return ConCat(inputParam, transform["Delimeter"].Value<string>());
case "REPLACEVALUE":
{
string compareToValue = transform["CompareToValue"].Value<string>();
string returnValue = transform["ReturnValue"].Value<string>();
string defaultValue = transform["DefaultValue"].Value<string>();
compareToValue = GetCompareValue(input, nullString, compareToValue);
returnValue = GetTokenValue(input, nullString, returnValue);
defaultValue = GetTokenValue(input, nullString, defaultValue);
return ReplaceValue(inputParam, compareToValue, returnValue, defaultValue);
}
case "REPLACEVALUEWITHREGEXCOMPARISON":
{
string compareToValue = transform["CompareToValue"].Value<string>();
string returnValue = transform["ReturnValue"].Value<string>();
string defaultValue = transform["DefaultValue"].Value<string>();
compareToValue = GetCompareValue(input, nullString, compareToValue);
returnValue = GetTokenValue(input, nullString, returnValue);
defaultValue = GetTokenValue(input, nullString, defaultValue);
return ReplaceValueWithRegexComparison(inputParam, compareToValue, returnValue, defaultValue);
}
case "SPLIT":
{
char delimeter = transform["Delimeter"].Value<char>();
int index = transform["Index"].Value<int>();
var positionToken = transform["Position"];
string position = positionToken != null ? positionToken.ToString() : string.Empty;
return Split(inputParam, delimeter, index, position);
}
case "TOUPPERCASE":
{
return inputParam[0] != null ? inputParam[0].ToUpperInvariant() : string.Empty;
}
case "TOLOWERCASE":
{
return inputParam[0] != null ? inputParam[0].ToLowerInvariant() : string.Empty;
}
case "RANGEMAPPING":
{
return mapRange((JArray)transform.SelectToken("$.Params"), (string)input.SelectToken(transform.SelectToken("$.DefaultValue").ToString()));
}
case "ONETOONEMAPPING":
{
return mapOneToOne((JArray)transform.SelectToken("$.Params"), (string)input.SelectToken(transform.SelectToken("$.DefaultValue").ToString()));
}
case "URIESCAPEDATASTRING":
{
UriEscapeDataString(input, parameters);
break;
}
}
return null;
}
private string GetTokenValue(JObject input, string nullString, string Value)
{
if (Value != null && Value.StartsWith("$."))
{
var returnValueToken = input.SelectToken(Value);
if (returnValueToken == null)
{
Value = nullString;
}
else
{
if (returnValueToken.Type == JTokenType.Null)
{
Value = nullString;
}
else
{
Value = returnValueToken.ToString();
}
}
}
return Value;
}
private string GetCompareValue(JObject input, string nullString, string compareToValue)
{
if (compareToValue != null && compareToValue.StartsWith("$."))
{
var compareToValueToken = input.SelectToken(compareToValue);
if (compareToValueToken == null)
{
compareToValue = nullString;
}
else
{
compareToValue = compareToValueToken.ToString();
}
}
return compareToValue;
}
private void UriEscapeDataString(JObject input, IList<dynamic> parameters)
{
if (parameters != null)
{
foreach (var parameter in parameters)
{
if (parameter != null)
{
string theParameter = parameter.ToString();
if (theParameter.StartsWith("$"))
{
var parameterToken = input.SelectTokens(theParameter);
if (parameterToken != null && parameterToken.Any())
{
foreach (var token in parameterToken)
{
if (token.Type != JTokenType.Null)
{
string data = token.ToString();
string uriEscapedData = Uri.EscapeDataString(data);
token.Replace(uriEscapedData);
}
}
}
}
}
}
}
}
private string ConCat(List<string> args, string delimeter)
{
return string.Join(delimeter, args.Where(value => value != null).ToList());
}
private string ReplaceValue(List<string> args, string compareToValue, string returnValue, string defaultValue)
{
if (args[0] == null && compareToValue == null)
return returnValue;
if (args[0] != null && args[0].Equals(compareToValue, StringComparison.OrdinalIgnoreCase))
return returnValue;
return defaultValue;
}
private string ReplaceValueWithRegexComparison(List<string> args, string compareToValue, string returnValue, string defaultValue)
{
if (args[0] == null && compareToValue == null)
return returnValue;
if (args[0] != null && compareToValue != null && Regex.IsMatch(args[0], compareToValue, RegexOptions.IgnoreCase))
return returnValue;
return defaultValue;
}
private string Split(List<string> args, char delimeter, int index, string position = "")
{
if (string.IsNullOrEmpty(position))
{
char[] delimiters = new char[] { delimeter };
return args[0].Split(delimiters, StringSplitOptions.RemoveEmptyEntries)[index];
}
else
{
if (position.Equals("FIRST",StringComparison.OrdinalIgnoreCase))
{
char[] delimiters = new char[] { delimeter };
return args[0].Split(delimiters, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
}
else if (position.Equals("LAST", StringComparison.OrdinalIgnoreCase))
{
char[] delimiters = new char[] { delimeter };
return args[0].Split(delimiters, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
}
else
return string.Empty;
}
}
private string mapRange(JArray truthTable, string value)
{
return Convert.ToString(truthTable.SelectToken($"$.[?(@.min<'{Convert.ToInt64(value)}' && @.max>'{Convert.ToInt64(value)}')].value"));
}
private string mapOneToOne(JArray truthTable, string value)
{
return Convert.ToString(truthTable.SelectToken($"$.[?(@.key=='{value}')].value"));
}
}
}

Просмотреть файл

@ -0,0 +1,9 @@
using Newtonsoft.Json.Linq;
namespace JsonToJsonMapper
{
public interface ITransformationHandler
{
dynamic Run(JObject config, JObject input);
}
}

Просмотреть файл

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JsonToJsonMapper;
using Newtonsoft.Json.Linq;
using Microsoft.CodeAnalysis.Scripting;
using Newtonsoft.Json;
namespace JsonToJsonMapper
{
class RoslynScriptHandler : ITransformationHandler
{
public Dictionary<string, Script> Scripts { get; set; }
public RoslynScriptHandler(Dictionary<string, Script> scripts)
{
Scripts = scripts;
}
/// <summary>
/// Executes the script using Roslyn and returns the value.
/// </summary>
/// <param name="transform"></param>
/// <param name="input"></param>
/// <returns></returns>
public dynamic Run(JObject transform, JObject input)
{
StringBuilder inputParam = new StringBuilder();
List<string> parameters = transform["Params"].ToObject<List<string>>();
string scriptName = transform["ScriptName"].Value<string>();
foreach (var item in parameters)
{
if (item.StartsWith("$"))
{
if (input.SelectTokens(item) != null)
{
var tokens = input.SelectTokens(item);
foreach (var i in tokens)
{
inputParam.Append(i.ToString());
if (tokens.Count() > 1)
inputParam.Append("[tokenDelimiter]");
}
}
if (parameters.Count > 1)
inputParam.Append(string.Empty + "[delimiter]");
}
else
inputParam.Append(item + "[delimiter]");
}
var result = Scripts[scriptName].RunAsync(new ScriptHost { Args = inputParam.ToString() });
return result.Result.ReturnValue.ToString();
}
}
}

Просмотреть файл

@ -0,0 +1,35 @@
using JsonToJsonMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JsonToJsonMapper
{
class TransformationFactory
{
readonly Dictionary<string, ITransformationHandler> registeredHandlers = new Dictionary<string, ITransformationHandler>();
/// <summary>
/// Add handler to the dictionary
/// </summary>
/// <param name="handler"></param>
public void AddHandlers(ITransformationHandler handler)
{
registeredHandlers[handler.GetType().Name] = handler;
}
/// <summary>
/// Returns a handler based on the type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public ITransformationHandler GetHandler<T>()
{
if (!registeredHandlers.ContainsKey(typeof(T).Name))
return null;
return registeredHandlers[typeof(T).Name];
}
}
}

Просмотреть файл

@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JsonToJsonMapper;
using Newtonsoft.Json.Linq;
namespace JsonToJsonMapper
{
public class TransposeHandler : ITransformationHandler
{
/// <summary>
/// Transposes an array into properties
/// </summary>
/// <param name="rule"></param>
/// <param name="input"></param>
/// <returns></returns>
public dynamic Run(JObject rule, JObject input)
{
string sourceColumn = rule["SourceColumn"].Value<string>();
string transformValueKey = rule["TransformValue"]["KeyLookupField"].Value<string>();
string transformValuePrependText = rule["TransformValue"]["PrependKeyText"].Value<string>();
string transformValue = rule["TransformValue"]["ValueLookupField"].Value<string>();
var tokens = input.SelectTokens(sourceColumn);
Dictionary<string, object> array = new Dictionary<string, object>();
foreach (var i in tokens)
{
string key = string.Empty;
var token = i.SelectToken(transformValueKey);
if (token != null)
key = transformValuePrependText + token.ToString().Replace(" ", string.Empty);
if (!string.IsNullOrWhiteSpace(key))
{
var valueToken = i.SelectToken(transformValue);
if (valueToken != null)
{
if (valueToken.Type == JTokenType.Array || valueToken.Type == JTokenType.Object)
array.Add(key, valueToken.ToString().Replace("\r", "").Replace("\n", "").Replace("\t", ""));
else if (valueToken.Value<string>() != null)
array.Add(key, valueToken);
}
}
}
return array;
}
}
}

Просмотреть файл

@ -0,0 +1,204 @@
using JsonToJsonMapper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace JsonToJsonMapper
{
class TypeConverterHandler : ITransformationHandler
{
/// <summary>
/// Converts value from one type to another
/// </summary>
/// <param name="config"></param>
/// <param name="input"></param>
/// <returns></returns>
public dynamic Run(JObject config, JObject input)
{
object value = input["value"].Value<object>();
string dataType = config["DataType"].Value<string>();
string format = config["Format"].Value<string>();
if (value==null || ((JToken)value).Type == JTokenType.Null)
return value;
try
{
if (!string.IsNullOrWhiteSpace(dataType))
{
switch (dataType.ToUpperInvariant())
{
case "LONG":
return Convert.ToInt64(value);
case "JOBJECT":
{
JToken Jtokenvalue = (JToken)value;
if (Jtokenvalue.Type == JTokenType.Object)
return (JObject)Jtokenvalue;
else
return JsonConvert.DeserializeObject(Jtokenvalue.ToString());
}
case "JARRAY":
{
JToken Jtokenvalue = (JToken)value;
if (Jtokenvalue.Type == JTokenType.Array)
{
if (Jtokenvalue.Any())
return (JArray)Jtokenvalue;
else
return null;
}
else if (Jtokenvalue.Type == JTokenType.Object)
{
return new JArray(Jtokenvalue);
}
else
{
if (Jtokenvalue.ToString().StartsWith("[") && Jtokenvalue.ToString().EndsWith("]"))
{
return JArray.Parse(Jtokenvalue.ToString());
}
else
return new JArray(Jtokenvalue);
}
}
case "SHORT":
return Convert.ToInt16(value);
case "INT":
case "INTEGER":
return Convert.ToInt32(value);
case "GUID":
return new Guid(value.ToString());
case "DATETIME":
{
string valueType = value.ToString();
Regex x = new Regex(@".*[+-][0-9][0-9][:]");
if (x.IsMatch(valueType))
return DateTimeOffset.Parse(valueType, CultureInfo.InvariantCulture);
else
return DateTime.Parse(valueType, CultureInfo.InvariantCulture);
}
case "CUSTOMDATETIME":
{
string valueType = value.ToString();
Regex x = new Regex(@".[+-][0-9]{4}");
if (x.IsMatch(valueType))
{
int pos = valueType.IndexOf("Z", StringComparison.OrdinalIgnoreCase);
String datetime = valueType.Substring(0, pos);
return datetime;
}
else
{
return null;
}
}
case "BOOL":
case "BOOLEAN":
return Convert.ToBoolean(value);
case "DECIMAL":
return Convert.ToDecimal(value);
case "DECIMAL?":
{
decimal decimalValue;
if (decimal.TryParse(value.ToString(), out decimalValue))
return decimalValue;
return null;
}
case "INT?":
{
decimal dval = Convert.ToDecimal(value.ToString());
return Decimal.ToInt32(dval);
}
case "GUID?":
{
Guid guid;
if (Guid.TryParse(value.ToString(), out guid))
return guid;
return null;
}
case "DATETIME?":
{
DateTime datetime;
if (DateTime.TryParse(value.ToString(), out datetime))
return datetime;
return null;
}
case "UTCDATETIME":
{
DateTime dateTime;
if (DateTime.TryParse(value.ToString(), out dateTime))
{
string utcDateTime = dateTime.ToString("s");
var zone = TimeZoneInfo.FindSystemTimeZoneById("UTC");
utcDateTime = utcDateTime + "+" + zone.BaseUtcOffset.ToString();
return utcDateTime;
}
return null;
}
case "STRINGTOUTCDATEFORMAT":
{
//This block converts the given date into UTC formatted string, it will not change the TimeZone offset
//compared to previous block.
DateTime dateTime;
if (DateTime.TryParse(value.ToString(), out dateTime))
{
string timeInUTCFormat = dateTime.ToString("yyyy-MM-ddTHH:mm:sszzz");
return timeInUTCFormat;
}
return null;
}
case "REMOVEDATETIMEOFFSET":
{
string valueType = value.ToString();
if (valueType.Contains("Z"))
{
int pos = valueType.IndexOf("Z", StringComparison.OrdinalIgnoreCase);
string datetime = valueType.Substring(0, pos+1); //including 'Z' in the output
return datetime;
}
return valueType;
}
case "FORMATTEDDATETIME":
{
DateTime dateTime;
if (DateTime.TryParse(value.ToString(), out dateTime))
{
string timeInUTCFormat;
if (!string.IsNullOrWhiteSpace(format))
timeInUTCFormat = dateTime.ToString(format);
else
timeInUTCFormat = dateTime.ToString(null, CultureInfo.InvariantCulture);
return timeInUTCFormat;
}
return null;
}
case "STRING":
{
if (value.GetType().Equals("JValue"))
return ((JValue)value).Value<string>();
else
return value.ToString();
}
}
}
}
catch (Exception ex)
{
throw new Exception("Failed while trying to cast value into " + dataType + ". " + ex.ToString());
}
return value;
}
}
}

Просмотреть файл

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JsonToJsonMapper;
using Newtonsoft.Json.Linq;
namespace JsonToJsonMapper
{
public class ValueMappingHandler : ITransformationHandler
{
/// <summary>
/// Returns value if matches the rule else returns default value.
/// </summary>
/// <param name="transform"></param>
/// <param name="input"></param>
/// <returns></returns>
public dynamic Run(JObject transform, JObject input)
{
var valueMapping = transform["ValueMapping"].ToObject<List<ConvertValue>>();
var defaultValue = transform["DefaultValue"].Value<string>();
var value = input["value"].Value<string>();
if (transform != null && valueMapping != null && value != null)
value = (from item in valueMapping where item.ExistingValue.Equals(value, StringComparison.OrdinalIgnoreCase) select item.NewValue).FirstOrDefault();
if (transform != null && string.IsNullOrWhiteSpace(value) && defaultValue != null)
{
if (defaultValue.Equals("UTCNOW", StringComparison.OrdinalIgnoreCase))
return DateTime.UtcNow.ToString();
else if (defaultValue.Equals("NEWGUID",StringComparison.OrdinalIgnoreCase))
return Guid.NewGuid().ToString();
else
return defaultValue;
}
return value;
}
}
}

Просмотреть файл

@ -0,0 +1,110 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<PackageReleaseNotes>https://github.com/microsoft/dynamic-odata/blob/main/CHANGELOG.md</PackageReleaseNotes>
<RepositoryUrl>https://github.com/microsoft/JsonToJsonMapper</RepositoryUrl>
<PackageProjectUrl>https://github.com/microsoft/JsonToJsonMapper</PackageProjectUrl>
<Copyright>Copyright (c) Microsoft Corporation.</Copyright>
<Authors>Karan Singh, Akash Khandelwal</Authors>
<Company>Microsoft Corporation</Company>
<PackageTags>JSON Mapper, JSonToJSon, AutoMapper </PackageTags>
<PackageLicenseExpression>
</PackageLicenseExpression>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<Version>1.0.0-preview</Version>
<Description>JSonToJSonMapper works on JSON format to exchange information between systems. MIP. It enables transformation of data from one canonical schema to another and allows integration of different SaaS applications through orchestration.</Description>
</PropertyGroup>
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{27E353D4-B88D-49AF-A072-7C19A47A2465}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>JsonToJsonMapper</RootNamespace>
<AssemblyName>JsonToJsonMapper</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
<Version>1.0.0-preview</Version>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<Version>1.0.0-preview</Version>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<Version>1.0.0-preview</Version>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Core" />
<Reference Include="System.Numerics" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AutoMapper.cs" />
<Compile Include="ExtensionMethods.cs" />
<Compile Include="Handlers\FunctionHandler.cs" />
<Compile Include="Handlers\ITransformationHandler.cs" />
<Compile Include="Handlers\TransformationHandlersFactory.cs" />
<Compile Include="Handlers\TypeConverterHandler.cs" />
<Compile Include="Handlers\ValueMappingHandler.cs" />
<Compile Include="Handlers\RoslynScriptHandler.cs" />
<Compile Include="Handlers\TransposeHandler.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config">
<SubType>Designer</SubType>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Scripting">
<Version>2.8.2</Version>
</PackageReference>
<PackageReference Include="Microsoft.CSharp">
<Version>4.3.0</Version>
</PackageReference>
<PackageReference Include="Newtonsoft.Json">
<Version>10.0.1</Version>
</PackageReference>
<PackageReference Include="System.Reflection.Primitives">
<Version>4.3.0</Version>
</PackageReference>
<PackageReference Include="System.Runtime.Handles">
<Version>4.3.0</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
<Target Name="Pack">
</Target>
</Project>

Просмотреть файл

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<package >
<metadata>
<id>$id$</id>
<version>1.0.0.1</version>
<title>JSonToJsonMapper</title>
<authors>Karan Singh, Akash Khandelwal</authors>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<projectUrl>https://github.com/microsoft/JsonToJsonMapper</projectUrl>
<description>JSonToJSonMapper works on JSON format to exchange information between systems. MIP. It enables transformation of data from one canonical schema to another and allows integration of different SaaS applications through orchestration.</description>
<releaseNotes>https://github.com/microsoft/dynamic-odata/blob/main/CHANGELOG.md</releaseNotes>
<copyright>Copyright (c) Microsoft Corporation.</copyright>
<tags>JSON Mapper JSonToJSon AutoMapper</tags>
<dependencies>
<group targetFramework="net461" />
</dependencies>
</metadata>
</package>

Просмотреть файл

@ -0,0 +1,38 @@
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("JsonToJsonMapper")]
[assembly: AssemblyDescription("JsonToJsonMapper")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("JsonToJsonMapper")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("27e353d4-b88d-49af-a072-7c19a47a2465")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("4.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: NeutralResourcesLanguage("")]

50
AutoMapper/app.config Normal file
Просмотреть файл

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Reflection.Metadata" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-1.2.0.0" newVersion="1.2.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Collections.Immutable" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-1.2.1.0" newVersion="1.2.1.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.IO.Compression" publicKeyToken="b77a5c561934e089" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.IO.FileSystem" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.IO.FileSystem.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Security.Cryptography.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Xml.XPath.XDocument" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Diagnostics.FileVersionInfo" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Diagnostics.StackTrace" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Console" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/>
</startup>
</configuration>

Двоичные данные
AutoMapper/nuget.exe Normal file

Двоичный файл не отображается.

8
CHANGELOG.md Normal file
Просмотреть файл

@ -0,0 +1,8 @@
# CHANGELOG
All notable changes to this project will be documented in this file.
## [1.0.0] - 05-April-2021
### Added
- The first version of the NuGet

9
CODE_OF_CONDUCT.md Normal file
Просмотреть файл

@ -0,0 +1,9 @@
# Microsoft Open Source Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
Resources:
- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns

38
Json2JsonMapper.sln Normal file
Просмотреть файл

@ -0,0 +1,38 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31112.23
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JsonToJsonMapper", "AutoMapper\JsonToJsonMapper.csproj", "{27E353D4-B88D-49AF-A072-7C19A47A2465}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{3B55A638-964C-4F13-865A-24C6E1CD0937}"
ProjectSection(SolutionItems) = preProject
.gitignore = .gitignore
JsonToJsonMapper.md = JsonToJsonMapper.md
JsonToJsonMapper.png = JsonToJsonMapper.png
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JsonToJsonMapper.Tests", "JsonToJsonMapper.Tests\JsonToJsonMapper.Tests.csproj", "{CF0531C0-8948-4506-BB42-BAF457D47508}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{27E353D4-B88D-49AF-A072-7C19A47A2465}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{27E353D4-B88D-49AF-A072-7C19A47A2465}.Debug|Any CPU.Build.0 = Debug|Any CPU
{27E353D4-B88D-49AF-A072-7C19A47A2465}.Release|Any CPU.ActiveCfg = Release|Any CPU
{27E353D4-B88D-49AF-A072-7C19A47A2465}.Release|Any CPU.Build.0 = Release|Any CPU
{CF0531C0-8948-4506-BB42-BAF457D47508}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CF0531C0-8948-4506-BB42-BAF457D47508}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CF0531C0-8948-4506-BB42-BAF457D47508}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CF0531C0-8948-4506-BB42-BAF457D47508}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1E6565CC-9567-443D-A2EC-F63B555FA4F7}
EndGlobalSection
EndGlobal

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

Просмотреть файл

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{CF0531C0-8948-4506-BB42-BAF457D47508}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>JsonToJsonMapper.Tests</RootNamespace>
<AssemblyName>JsonToJsonMapper.Tests</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.10.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Numerics" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<Choose>
<When Condition="('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'">
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
</ItemGroup>
</When>
<Otherwise>
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework" />
</ItemGroup>
</Otherwise>
</Choose>
<ItemGroup>
<Compile Include="AutoMapperTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AutoMapper\JsonToJsonMapper.csproj">
<Project>{27e353d4-b88d-49af-a072-7c19a47a2465}</Project>
<Name>JsonToJsonMapper</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="Jsons\OneToOneMapping\OneToOneMappingRules.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Jsons\OneToOneMapping\Transformation_Input.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Jsons\RangeMapping\RangeMappingRules.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Jsons\RangeMapping\Transformation_Input.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Jsons\ToUpper\Upper_Mapping.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Jsons\ToUpper\Transformation_Input.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="packages.config" />
</ItemGroup>
<Choose>
<When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
</ItemGroup>
</When>
</Choose>
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,63 @@
{
"MappingRuleConfig": {
"TruthTable": [
{
"SourceColumn": "",
"DestinationColumn": "Industry",
"DataType": "string",
"ComplexType": null,
"TransformValue": {
"Type": "function",
"Function": "ONETOONEMAPPING",
"DefaultValue": "$.Industry",
"Params": [
{
"key": "Agriculture & Mining",
"value": "Agriculture, Forestry, & Fishing"
},
{
"key": "Business Services",
"value": "Services"
},
{
"key": "Computers & Electronics",
"value": "Communications & Media"
},
{
"key": "Consumer Services",
"value": "Services"
},
{
"key": "Education",
"value": "Education"
},
{
"key": "Energy & Utilities",
"value": "Power & Utilities"
},
{
"key": "Financial Services",
"value": "Financial Services"
},
{
"key": "Government",
"value": "Government"
}
]
}
}
]
}
}

Просмотреть файл

@ -0,0 +1,4 @@
{
"Industry": "Financial Services"
}

Просмотреть файл

@ -0,0 +1,67 @@
{
"MappingRuleConfig": {
"TruthTable": [
{
"SourceColumn": "",
"DestinationColumn": "CompanySize",
"DataType": "string",
"ComplexType": null,
"TransformValue": {
"Type": "function",
"Function": "RANGEMAPPING",
"DefaultValue": "$.CompanySize",
"Params": [
{
"min": 1,
"max": 9,
"value": "1to9employees"
},
{
"min": 10,
"max": 50,
"value": "10to50employees"
},
{
"min": 51,
"max": 250,
"value": "51to250employees"
},
{
"min": 251,
"max": 1000,
"value": "251to1000employees"
},
{
"min": 1001,
"max": 5000,
"value": "1001to5000employees"
},
{
"min": 5001,
"max": 10000,
"value": "5001to10000employees"
},
{
"min": 10001,
"max": 20000,
"value": "10001to20000employees"
},
{
"min": 20001,
"value": "Morethan20000employees"
}
]
}
}
]
}
}

Просмотреть файл

@ -0,0 +1,4 @@
{
"CompanySize": 57
}

Просмотреть файл

@ -0,0 +1,11 @@
{
"LeadId": "2353",
"EmailAddress": "Windows 10",
"Key": "12121212333_AKJKKAJDKAKJKKKDKSKAK",
"LeadInfo": [
{
"FirstName": "AP - Azure",
"LastName": "C - and - E"
}
]
}

Просмотреть файл

@ -0,0 +1,46 @@
{
"MappingRuleConfig": {
"TruthTable": [
{
"SourceColumn": "",
"DestinationColumn": "Data",
"DataType": "string",
"ComplexType": {
"DataType": "jArray",
"Node": "$.LeadInfo[*]",
"TruthTable": [
{
"SourceColumn": "",
"DestinationColumn": "EmailAddress",
"DataType": "string",
"TransformValue": {
"Type": "function",
"Function": "TOUPPERCASE",
"Params": [
"$.[{parent}].[{parent}].[{parent}].EmailAddress"
]
}
},
{
"SourceColumn": "$.FirstName",
"DestinationColumn": "FirstName",
"DataType": "string"
},
{
"SourceColumn": "",
"DestinationColumn": "LastName",
"DataType": "string",
"TransformValue": {
"Type": "function",
"Function": "TOUPPERCASE",
"Params": [
"$.LastName"
]
}
}
]
}
}
]
}
}

Просмотреть файл

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("JsonToJsonMapper.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("JsonToJsonMapper.Tests")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cf0531c0-8948-4506-bb42-baf457d47508")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- File name extension must be .runsettings -->
<RunSettings>
<DataCollectionRunSettings>
<DataCollectors>
<DataCollector friendlyName="Code Coverage" uri="datacollector://Microsoft/CodeCoverage/2.0" assemblyQualifiedName="Microsoft.VisualStudio.Coverage.DynamicCoverageDataCollector, Microsoft.VisualStudio.TraceCollector, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<Configuration>
<CodeCoverage>
<!--
About include/exclude lists:
Empty "Include" clauses imply all; empty "Exclude" clauses imply none.
Each element in the list is a regular expression (ECMAScript syntax). See http://msdn.microsoft.com/library/2k3te2cs.aspx.
An item must first match at least one entry in the include list to be included.
Included items must then not match any entries in the exclude list to remain included.
-->
<!-- Match assembly file paths: -->
<ModulePaths>
<Include>
<ModulePath>.*\.dll$</ModulePath>
</Include>
<Exclude>
<ModulePath>.*jsontojsonmapper.tests.dll*</ModulePath>
</Exclude>
</ModulePaths>
<!-- Match attributes on any code element: -->
<Attributes>
<Exclude>
<Attribute>^System\.Diagnostics\.DebuggerHiddenAttribute$</Attribute>
<Attribute>^System\.Diagnostics\.DebuggerNonUserCodeAttribute$</Attribute>
<Attribute>^System\.Runtime\.CompilerServices.CompilerGeneratedAttribute$</Attribute>
<Attribute>^System\.CodeDom\.Compiler.GeneratedCodeAttribute$</Attribute>
<Attribute>^System\.Diagnostics\.CodeAnalysis.ExcludeFromCodeCoverageAttribute$</Attribute>
</Exclude>
</Attributes>
<!-- We recommend you do not change the following values: -->
<UseVerifiableInstrumentation>True</UseVerifiableInstrumentation>
<AllowLowIntegrityProcesses>True</AllowLowIntegrityProcesses>
<CollectFromChildProcesses>True</CollectFromChildProcesses>
<CollectAspDotNet>False</CollectAspDotNet>
</CodeCoverage>
</Configuration>
</DataCollector>
</DataCollectors>
</DataCollectionRunSettings>
</RunSettings>

Просмотреть файл

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Collections.Immutable" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-1.2.1.0" newVersion="1.2.1.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.IO.Compression" publicKeyToken="b77a5c561934e089" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.IO.FileSystem" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.IO.FileSystem.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Security.Cryptography.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Xml.XPath.XDocument" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Diagnostics.FileVersionInfo" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Diagnostics.StackTrace" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Console" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/></startup></configuration>

Просмотреть файл

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="10.0.1" targetFramework="net46" />
</packages>

Двоичные данные
JsonToJsonMapper.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 175 KiB

21
LICENSE Normal file
Просмотреть файл

@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

133
README.md Normal file
Просмотреть файл

@ -0,0 +1,133 @@
# JsonToJsonMapper
AutoMapper works on JSON format to exchange information between systems. MIP. It enables transformation of data from one canonical schema to another and allows integration of different SaaS applications through orchestration.
Following are some of the capabilities that Automapper currently supports:
1. Transformation from a flat type to flat/complex type.
2. Transformation from a complex type to flat/complex type.
3. Allows execution of CSharp script through Roslyn for complex transformation.
4. Supports JArray
5. Supports transformation of values from one datatype to another.
6. Data type validation
![GitHub Logo](JsonToJsonMapper.png)
## Following are the handlers currently supported by the tool
**Transpose**
1. Key
2. Value
3. PrependText
**Type converter**
1. Primitive data types
2. JObject
3. Jarray
4. DateTime Formatting and Timezone
5. Nullable int, guid and decimal
**Roslyn Script**
1. Script
2. Params
3. Execution
**Value Mapping**
1. Params
**Function Handler**
1. Concatenation
2. Replace value
3. Split
4. ToUpper
5. ToLower
### Example
Source Json
```json
{
"result": [
{
"id": 2,
"leadId": 6,
"activityDate": "2013-09-26T06:56:35+0000",
"activityTypeId": 12,
"attributes": [
{
"name": "Source Type",
"value": "Web page visit"
},
{
"name": "Source Info",
"value": "http://search.yahoo.com"
}
]
}
]
}
```
Expeced output
```javascript
{
"Content": [
{
"leadId": 6,
"Source Type": "Web page visit",
"Source Info": "http://search.yahoo.com"
}
]
}
```
Mapping config
```javascript
{
"MappingRuleConfig": {
"TruthTable": [
{
"DestinationColumn": "ContentJSON",
"ComplexType": {
"DataType": "JArray",
"Node": "$.result[*]",
"TruthTable": [
{
"SourceColumn": "$.leadId",
"DestinationColumn": "leadId",
"DataType": "long"
},
{
"SourceColumn": "$.attributes[*]",
"DataType": "JArray",
"TransformValue": {
"Type": "PromoteArrayToProperty",
"KeyLookupField": "$.name",
"ValueLookupField": "$.value"
}
}
]
}
]
}
}
```
## Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.
When you submit a pull request, a CLA bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
## Trademarks
This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft
trademarks or logos is subject to and must follow
[Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general).
Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship.
Any use of third-party trademarks or logos are subject to those third-party's policies.

41
SECURITY.md Normal file
Просмотреть файл

@ -0,0 +1,41 @@
<!-- BEGIN MICROSOFT SECURITY.MD V0.0.5 BLOCK -->
## Security
Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/).
If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)), please report it to us as described below.
## Reporting Security Issues
**Please do not report security vulnerabilities through public GitHub issues.**
Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report).
If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc).
You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc).
Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
* Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
* Full paths of source file(s) related to the manifestation of the issue
* The location of the affected source code (tag/branch/commit or direct URL)
* Any special configuration required to reproduce the issue
* Step-by-step instructions to reproduce the issue
* Proof-of-concept or exploit code (if possible)
* Impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly.
If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs.
## Preferred Languages
We prefer all communications to be in English.
## Policy
Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd).
<!-- END MICROSOFT SECURITY.MD BLOCK -->

13
SUPPORT.md Normal file
Просмотреть файл

@ -0,0 +1,13 @@
# Support
## How to file issues and get help
This project uses GitHub Issues to track bugs and feature requests. Please search the existing
issues before filing new issues to avoid duplicates. For new issues, file your bug or
feature request as a new Issue.
For help and questions about using this project, please create your issues in issue tracker here https://github.com/microsoft/JsonToJsonMapper/issues
## Microsoft Support Policy
Support for this **PROJECT or PRODUCT** is limited to the resources listed above.