So basically I wanted to do:
json code,
statement,
when statement is true,some other json text
continuation of previous json code
This is currently my code and I'm looking a way to shorten it, any solutions?
if (textBox1.Text != "Enter Address")
{
if (textBox2.Text != "Enter Address")
{
//1+2+3 OK
if (textBox3.Text != "Enter Address")
{
var item = new Item
{
version = 1,
schema_version = 2,
id = textBox14.Text,
title = textBox7.Text,
title_localized = textBox18.Text,
artist = textBox6.Text,
artist_localized = textBox8.Text,
artist_source = textBox9.Text,
illustrator = textBox10.Text,
illustrator_source = textBox11.Text,
charter = textBox13.Text,
music = new ItemMusic {
path = textBox4.Text
},
music_preview = new ItemMusicPreview
{
path = textBox5.Text
},
background = new ItemBackground
{
path = open3.SafeFileName
},
charts = new List<ItemChart>
{
new ItemChart
{
type = "easy",
name = textBox15.Text,
difficulty = Convert.ToInt32(numericUpDown1.Value),
path = textBox1.Text
},
new ItemChart
{
type = "hard",
name = textBox16.Text,
difficulty = Convert.ToInt32(numericUpDown2.Value),
path = textBox2.Text
},
new ItemChart
{
type = "extreme",
name = textBox17.Text,
difficulty = Convert.ToInt32(numericUpDown3.Value),
path = textBox3.Text
}
}
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
};
var json = JsonConvert.SerializeObject(item, settings);
if (File.Exists(#"C:\Users\Public\Desktop\level files\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory(#"C:\Users\Public\Desktop\level files\");
}
if (File.Exists($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\");
}
File.WriteAllText($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", json, new UTF8Encoding(false));
}
//1+2 (3) OK
else
{
var item = new Item
{
version = 1,
schema_version = 2,
id = textBox14.Text,
title = textBox7.Text,
title_localized = textBox18.Text,
artist = textBox6.Text,
artist_localized = textBox8.Text,
artist_source = textBox9.Text,
illustrator = textBox10.Text,
illustrator_source = textBox11.Text,
charter = textBox13.Text,
music = new ItemMusic
{
path = textBox4.Text
},
music_preview = new ItemMusicPreview
{
path = textBox5.Text
},
background = new ItemBackground
{
path = open3.SafeFileName
},
charts = new List<ItemChart>
{
new ItemChart
{
type = "easy",
name = textBox15.Text,
difficulty = Convert.ToInt32(numericUpDown1.Value),
path = textBox1.Text
},
new ItemChart
{
type = "hard",
name = textBox16.Text,
difficulty = Convert.ToInt32(numericUpDown2.Value),
path = textBox2.Text
}
}
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
};
var json = JsonConvert.SerializeObject(item, settings);
if (File.Exists(#"C:\Users\Public\Desktop\level files\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory(#"C:\Users\Public\Desktop\level files\");
}
if (File.Exists($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\");
}
File.WriteAllText($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", json, new UTF8Encoding(false));
}
}
else
{
//1+3 (2) OK
if (textBox3.Text != "Enter Address")
{
var item = new Item
{
version = 1,
schema_version = 2,
id = textBox14.Text,
title = textBox7.Text,
title_localized = textBox18.Text,
artist = textBox6.Text,
artist_localized = textBox8.Text,
artist_source = textBox9.Text,
illustrator = textBox10.Text,
illustrator_source = textBox11.Text,
charter = textBox13.Text,
music = new ItemMusic
{
path = textBox4.Text
},
music_preview = new ItemMusicPreview
{
path = textBox5.Text
},
background = new ItemBackground
{
path = open3.SafeFileName
},
charts = new List<ItemChart>
{
new ItemChart
{
type = "easy",
name = textBox15.Text,
difficulty = Convert.ToInt32(numericUpDown1.Value),
path = textBox1.Text
},
new ItemChart
{
type = "extreme",
name = textBox17.Text,
difficulty = Convert.ToInt32(numericUpDown3.Value),
path = textBox3.Text
}
}
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
};
var json = JsonConvert.SerializeObject(item, settings);
if (File.Exists(#"C:\Users\Public\Desktop\level files\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory(#"C:\Users\Public\Desktop\level files\");
}
if (File.Exists($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\");
}
File.WriteAllText($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", json, new UTF8Encoding(false));
}
//1 (2)(3) OK
else
{
var item = new Item
{
version = 1,
schema_version = 2,
id = textBox14.Text,
title = textBox7.Text,
title_localized = textBox18.Text,
artist = textBox6.Text,
artist_localized = textBox8.Text,
artist_source = textBox9.Text,
illustrator = textBox10.Text,
illustrator_source = textBox11.Text,
charter = textBox13.Text,
music = new ItemMusic
{
path = textBox4.Text
},
music_preview = new ItemMusicPreview
{
path = textBox5.Text
},
background = new ItemBackground
{
path = open3.SafeFileName
},
charts = new List<ItemChart>
{
new ItemChart
{
type = "easy",
name = textBox15.Text,
difficulty = Convert.ToInt32(numericUpDown1.Value),
path = textBox1.Text
}
}
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
};
var json = JsonConvert.SerializeObject(item, settings);
if (File.Exists(#"C:\Users\Public\Desktop\level files\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory(#"C:\Users\Public\Desktop\level files\");
}
if (File.Exists($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\");
}
File.WriteAllText($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", json, new UTF8Encoding(false));
}
}
}
else
if (textBox2.Text != "Enter Address")
{
//2+3 (1) OK
if (textBox3.Text != "Enter Address")
{
var item = new Item
{
version = 1,
schema_version = 2,
id = textBox14.Text,
title = textBox7.Text,
title_localized = textBox18.Text,
artist = textBox6.Text,
artist_localized = textBox8.Text,
artist_source = textBox9.Text,
illustrator = textBox10.Text,
illustrator_source = textBox11.Text,
charter = textBox13.Text,
music = new ItemMusic
{
path = textBox4.Text
},
music_preview = new ItemMusicPreview
{
path = textBox5.Text
},
background = new ItemBackground
{
path = open3.SafeFileName
},
charts = new List<ItemChart>
{
new ItemChart
{
type = "hard",
name = textBox16.Text,
difficulty = Convert.ToInt32(numericUpDown2.Value),
path = textBox2.Text
},
new ItemChart
{
type = "extreme",
name = textBox17.Text,
difficulty = Convert.ToInt32(numericUpDown3.Value),
path = textBox3.Text
}
}
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
};
var json = JsonConvert.SerializeObject(item, settings);
if (File.Exists(#"C:\Users\Public\Desktop\level files\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory(#"C:\Users\Public\Desktop\level files\");
}
if (File.Exists($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\");
}
File.WriteAllText($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", json, new UTF8Encoding(false));
}
//2 (1)(3)
else
{
var item = new Item
{
version = 1,
schema_version = 2,
id = textBox14.Text,
title = textBox7.Text,
title_localized = textBox18.Text,
artist = textBox6.Text,
artist_localized = textBox8.Text,
artist_source = textBox9.Text,
illustrator = textBox10.Text,
illustrator_source = textBox11.Text,
charter = textBox13.Text,
music = new ItemMusic
{
path = textBox4.Text
},
music_preview = new ItemMusicPreview
{
path = textBox5.Text
},
background = new ItemBackground
{
path = open3.SafeFileName
},
charts = new List<ItemChart>
{
new ItemChart
{
type = "hard",
name = textBox16.Text,
difficulty = Convert.ToInt32(numericUpDown2.Value),
path = textBox2.Text
}
}
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
};
var json = JsonConvert.SerializeObject(item, settings);
if (File.Exists(#"C:\Users\Public\Desktop\level files\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory(#"C:\Users\Public\Desktop\level files\");
}
if (File.Exists($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\");
}
File.WriteAllText($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", json, new UTF8Encoding(false));
}
}
else
{
var item = new Item
{
version = 1,
schema_version = 2,
id = textBox14.Text,
title = textBox7.Text,
title_localized = textBox18.Text,
artist = textBox6.Text,
artist_localized = textBox8.Text,
artist_source = textBox9.Text,
illustrator = textBox10.Text,
illustrator_source = textBox11.Text,
charter = textBox13.Text,
music = new ItemMusic
{
path = textBox4.Text
},
music_preview = new ItemMusicPreview
{
path = textBox5.Text
},
background = new ItemBackground
{
path = open3.SafeFileName
},
charts = new List<ItemChart>
{
new ItemChart
{
type = "extreme",
name = textBox17.Text,
difficulty = Convert.ToInt32(numericUpDown3.Value),
path = textBox3.Text
},
}
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
};
var json = JsonConvert.SerializeObject(item, settings);
if (File.Exists(#"C:\Users\Public\Desktop\level files\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory(#"C:\Users\Public\Desktop\level files\");
}
if (File.Exists($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\");
}
File.WriteAllText($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", json, new UTF8Encoding(false));
}
I was going to add "storyboard = open9.FileName" to "new ItemChart"s but not add the storyboard line when the file address is not imported.
Related
I am using Autodesk Forge DesignAutomatin V3 in C# and am getting an error when creating an Activity.
this is the error i receive: System.IO.InvalidDataException: 'CommandLine is a required property for Activity and cannot be null'
Here is how i am setting up the activity.
var activity = new Activity()
{
CommandLine = new List<string>() { $"$(engine.path)\\accoreconsole.exe /i $(args[InputModel].path) /al $(appbundles[{_bundleId}].path) /s $(settings[script].path)" },
Parameters = new Dictionary<string, ModelParameter>()
{
{ "HostDwg", new ModelParameter() { Verb = ModelParameter.VerbEnum.Get, LocalName = "$(HostDwg)", Required = true } },
{ "InputModel", new ModelParameter() { Verb = ModelParameter.VerbEnum.Get, LocalName = "3DBuild.dxf", Required = true, } },
{ "Result", new ModelParameter() { Verb = ModelParameter.VerbEnum.Put, Zip = true, LocalName = _outPutFileName, Required = true } }
},
Engine = _engineVersion,
Appbundles = new List<string>() { myApp },
Settings = new Dictionary<string, dynamic>()
{
{ "script", new StringSetting() { Value = string.Format("DXFIN\n\"3DBuild.dxf\"\nExplodeModel\n-view sw\nDXFOUT\n{0}\n16\n", _outPutFileName) } }
},
Description = "DXF processor",
Version = 1,
Id = _activityName
};
Please use exclusive Design Automation .NET core SDK for v3, it appears that you are referring Design Automation namespace from autodesk.forge.
When you add new SDK, make sure you remove this - using Autodesk.Forge.Model.DesignAutomation.v3; from your code.
var activity = new Activity() {
CommandLine = new List < string > () {
$ "$(engine.path)\\accoreconsole.exe /i $(args[InputModel].path) /al $(appbundles[{PackageName}].path) /s $(settings[script].path)"
}, Parameters = new Dictionary < string, Parameter > () {
{
"HostDwg",
new Parameter() {
Verb = Verb.Get, LocalName = "$(HostDwg)", Required = true
}
}, {
"InputModel",
new Parameter() {
Verb = Verb.Get, LocalName = "3DBuild.dxf", Required = true,
}
}, {
"Result",
new Parameter() {
Verb = Verb.Put, Zip = true, LocalName = outputFile, Required = true
}
}
}, Engine = TargetEngine, Appbundles = new List < string > () {
myApp
}, Settings = new Dictionary < string, ISetting > () {
{
"script",
new StringSetting() {
Value = string.Format("DXFIN\n\"3DBuild.dxf\"\nExplodeModel\n-view sw\nDXFOUT\n{0}\n16\n", outputFile)
}
}
}, Description = "DXF processor", Version = 1, Id = ActivityName
};
I have a list lstCollectionInstances which has 4 collection instance,
var lstCollectionInstances = new List<CollectionInstance>
{
new CollectionInstance
{
Name = "A",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "P1", Value = 10, DataType = "D"}
}
},
new CollectionInstance
{
Name = "A",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "P2", Value = "H1", DataType = "S"}
}
},
new CollectionInstance
{
Name = "B",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "P1", Value = 20, DataType = "D"}
}
},
new CollectionInstance
{
Name = "B",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "P2", Value = "H2", DataType = "S"}
}
},
};
Now when I filter it based on CollectionProperty data types D it's should give me 2 records, but below code giving me all 4 records, what is missing here?
var X = lstCollectionInstances.Select(x => new CollectionInstance
{
Name = x.Name,
CollectionProperties = x.CollectionProperties.Where(cp => cp.DataType == "D").ToList()
}).ToList();
This one selects all instances with a property of type D.
var result= lstCollectionInstances
.Where(x => x.CollectionProperties.Any(y => y.DataType == "D"))
.ToList();
It is because you're executing Select in each item of lstCollectionInstances and Where in CollectionProperties. It will return 4 items which 2 of them have empty CollectionProperties. You should execute Where first like:
var X = lstCollectionInstances.Where(a => a.CollectionProperties.Any(cp => cp.DataType == "D")).Select(x => new CollectionInstance
{
Name = x.Name,
CollectionProperties = x.CollectionProperties
}).ToList();
Trying to add unit test for the below controller.
public HttpResponseMessage pldindexingSummary()
{
try
{
Logger.log.Info("Begin GET api/capturestats/pldindexingsummary request from " + HttpContext.Current.User.Identity.Name);
using (Utilities.CreateTransactionScope())
{
if (!PLDGlobals.isPopulated) _repository.PopulatePLDGlobals();
return Request.CreateResponse(HttpStatusCode.OK, _repository.GetIndexingSummary());
}
}
catch (EntityException enEx)
{
Logger.log.Error("Entity Error in GET api/capturestats/pldindexingsummary", enEx);
Utilities.SendEmail("GET api/capturestats/pldindexingsummary", Utilities.EntityError + enEx.Message, enEx.StackTrace.ToString(), string.Empty);
HttpError error = new HttpError(Utilities.EntityError + enEx.Message);
return Request.CreateResponse(HttpStatusCode.InternalServerError, error);
}
catch (Exception ex)
{
Logger.log.Error("General Error in GET api/capturestats/pldindexingsummary", ex);
Utilities.SendEmail("GET api/capturestats/pldindexingsummary", Utilities.ExceptionError + ex.Message, ex.StackTrace.ToString(), string.Empty);
HttpError error = new HttpError(Utilities.ExceptionError + ex.Message);
return Request.CreateResponse(HttpStatusCode.InternalServerError, error);
}
}
public static TransactionScope CreateTransactionScope()
{
var transactionOptions = new TransactionOptions();
transactionOptions.IsolationLevel = IsolationLevel.ReadUncommitted;
transactionOptions.Timeout = TransactionManager.MaximumTimeout;
return new TransactionScope(TransactionScopeOption.Required, transactionOptions);
}
This is what i have done so far.
[TestMethod]
public void GetAllIndexingSummary()
{
// Arrange
var mockRepository = new Mock<IPLDRepository>();
mockRepository.Setup(x => x.GetIndexingSummary())
.Returns(new List<IndexingSummaryResponseDTO>
{
new IndexingSummaryResponseDTO {DocumentQueueId =1, DocumentQueueName = "Sales Upload", DepartmentName = "PLD_SalesUpload", DocumentCount= 10, OldestDocumentDate = "09/01/2016 09:25:50", UserLocation = "Dover" , IsChecked = false, Usernames = "Gupta_A_N0182727, Ansara_E_N0000391, Aronson_D_N0175509" },
new IndexingSummaryResponseDTO {DocumentQueueId =2, DocumentQueueName = "Inbound Fax Manual", DepartmentName = "PLD_InboundFaxManual", DocumentCount= 20, OldestDocumentDate = "09/02/2016 12:55:04", UserLocation = "Dover" , IsChecked = false, Usernames = "Bent_E_N0156485, Herron_E_N0175690" },
new IndexingSummaryResponseDTO {DocumentQueueId =3, DocumentQueueName = "Rating Scan", DepartmentName = "PLD_RatingScan", DocumentCount= 30, OldestDocumentDate = "09/03/2016 04:45:08", UserLocation = "Dover" , IsChecked = false, Usernames = "Gupta_A_N0182727, Jinkens_M_N0178324" },
new IndexingSummaryResponseDTO {DocumentQueueId =4, DocumentQueueName = "Indexing/Loading Error", DepartmentName = "PLD_IndexingLoadingError", DocumentCount= 50, OldestDocumentDate = "09/04/2016 05:10:28", UserLocation = "Dover" , IsChecked = false, Usernames = "Gupta_A_N0182727, Keshavarz_M_N0070514" },
new IndexingSummaryResponseDTO {DocumentQueueId =5, DocumentQueueName = "Prod Center Scan", DepartmentName = "PLD_ProdCenterScan", DocumentCount= 60, OldestDocumentDate = "09/05/2016 16:12:12", UserLocation = "Dover" , IsChecked = false, Usernames = "Libby_S_N0145549, Long_S_N0236534, Miller_K_N0177119" },
new IndexingSummaryResponseDTO {DocumentQueueId =6, DocumentQueueName = "Prod Center Inbound Fax", DepartmentName = "PLD_ProdCenterInboundFax", DocumentCount= 70, OldestDocumentDate = "09/06/2016 15:25:03", UserLocation = "Dover" , IsChecked = false, Usernames = "Parmer_N_N0290328, Porter_S_N0074020" },
new IndexingSummaryResponseDTO {DocumentQueueId =7, DocumentQueueName = "Research Dover", DepartmentName = "PLD_ResearchDover", DocumentCount= 0, OldestDocumentDate = "N/A", UserLocation = "Dover" , IsChecked = false, Usernames = "Porter_S_N0074020" },
new IndexingSummaryResponseDTO {DocumentQueueId =8, DocumentQueueName = "Orlando Fax/Scan", DepartmentName = "PLD_OrlandoFaxScan", DocumentCount= 80, OldestDocumentDate = "09/08/2016 21:25:03", UserLocation = "Orlando" , IsChecked = false, Usernames = "Putnam_S_N0199165" },
new IndexingSummaryResponseDTO {DocumentQueueId =9, DocumentQueueName = "Research Orlando Fax/Scan", DepartmentName = "PLD_ResearchOrlandoFaxScan ", DocumentCount= 10, OldestDocumentDate = "09/09/2016 18:25:03", UserLocation = "Orlando" , IsChecked = false, Usernames = "Seefeld_J_N0030634" },
});
var controller = new CaptureStatsController(mockRepository.Object);
controller.Request = new HttpRequestMessage();
controller.Configuration = new HttpConfiguration();
//Act
var result = controller.pldindexingSummary();
Assert.IsNotNull(result, "Result is null");
IList<IndexingSummaryResponseDTO> product;
Assert.IsTrue(result.TryGetContentValue<IList<IndexingSummaryResponseDTO>>(out product));
Assert.AreEqual(10, product.Count);
}
I am getting NullReference Exception : Object reference not set to an instance of object.
This is my first Unit test.I am not sure where it is going wrong. I have followed the Microsoft article. reference link :
https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/unit-testing-controllers-in-web-api
I want to add a new playlist with songs to an existing json file.
I'm using Newtonsoft Json.NET to create a Json file like this:
dynamic GroupObj = new JObject();
GroupObj.Playlist = new JArray() as dynamic;
dynamic PlayListObj = new JObject();
PlayListObj.UniqueId = "";
PlayListObj.Title = "Playlist name";
GroupObj.Playlist.Add(PlayListObj);
PlayListObj.Songs = new JArray() as dynamic;
dynamic SongObj = new JObject();
SongObj.UniqueId = "";
SongObj.Title = "song name";
PlayListObj.Songs.Add(SongObj);
data = GroupObj.ToString();
That outputs this:
{
"Playlist": [
{
"UniqueId": "",
"Title": "Playlist name",
"Songs": [
{
"UniqueId": "",
"Title": "song name",
}
]
}
]
}
How would I modify the Json.NET to add new Objects to the existing Object to get to something like this:
{
"Playlist": [
{
"UniqueId": "",
"Title": "Playlist name",
"Songs": [
{
"UniqueId": "",
"Title": "song name",
}
]
},
{
"UniqueId": "",
"Title": "Playlist name",
"Songs": [
{
"UniqueId": "",
"Title": "song name",
"Lyrics": "song lyrics",
"Location": "location"
}
]
}
]
}
Nevermind, I made a solution by rewriting the whole file. Probably not very resource friendly but for a school project, it works. Thanks
string data;
JsonValue val = JsonValue.Parse("{\"some json data\": some value,}");
JsonArray Pl = val.GetObject().GetNamedArray("Playlist");
for (uint x = 0; x != Pl.Count; x++)//go through each playlist
{
var Pl_title = Pl.GetObjectAt(x).GetNamedString("Title"); //get playlist name
if (Pl_title != txtPlaylistName.Text)//dont do anything if playlist exists
{
var Pl_id = Pl.GetObjectAt(x).GetNamedString("UniqueId");
var Pl_loc = Pl.GetObjectAt(x).GetNamedString("Location");
var Pl_img = Pl.GetObjectAt(x).GetNamedString("ImagePath");
//re-create the playlist
dynamic PlayListObj = new JObject();
PlayListObj.UniqueId = Pl_id;
PlayListObj.Title = Pl_title;
PlayListObj.Location = Pl_loc;
PlayListObj.ImagePath = Pl_img;
GroupObj.Playlist.Add(PlayListObj);
PlayListObj.Songs = new JArray() as dynamic;
JsonArray Sng = Pl.GetObjectAt(x).GetNamedArray("Songs");
for (uint y = 0; y != Sng.Count; y++)
{
var Sng_id = Sng.GetObjectAt(y).GetNamedString("UniqueId");
var Sng_title = Sng.GetObjectAt(y).GetNamedString("Title");
var Sng_lyr = Sng.GetObjectAt(y).GetNamedString("Lyrics");
var Sng_loc = Sng.GetObjectAt(y).GetNamedString("Location");
//re-create the songs in the playlist
dynamic SongObj = new JObject();
SongObj.UniqueId = Sng_id;
SongObj.Title = Sng_title;
SongObj.Lyrics = Sng_lyr;
SongObj.Location = Sng_loc;
PlayListObj.Songs.Add(SongObj);
}
}
else
txtBerror.Text = "The name: " + txtPlaylistName.Text + " already exists.";
}
if (txtPlaylistName.Text != string.Empty)
{
//re-create the playlist
dynamic newPlayListObj = new JObject();
newPlayListObj.UniqueId = "PL " + txtPlaylistName.Text;
newPlayListObj.Title = txtPlaylistName.Text;
newPlayListObj.Location = "";
newPlayListObj.ImagePath = "";
GroupObj.Playlist.Add(newPlayListObj);
newPlayListObj.Songs = new JArray() as dynamic;
for (int a = 0; a != 3; a++)//number of songs
{
dynamic SongObj = new JObject();
SongObj.UniqueId = "Sng " + "file name";
SongObj.Title = "file name";
SongObj.Lyrics = "";
SongObj.Location = "";
newPlayListObj.Songs.Add(SongObj);
}
}
else
txtBerror.Text = "Enter a playlist name";
data = GroupObj.ToString();
await Windows.Storage.FileIO.WriteTextAsync(newFile, data);//write to the file
I am trying to create power point presentation on the fly (without usage of previuosly created template slide). So far I have results, but experiencing difficulties on adding picture (see code below)
When disable the P.Picture part it is working (means the created pptx file can be opened).
With the P.Picture part PowerPoint proposes repair and removes "found non-readable part" resulting of showing only placeholder of the picture with "Picture can not be shown message". If you expand the pptx in unrepaired state the media folder contains proper picture that can be opened... _rels folder contains file that properly links the existing image file with the image placeholder... I am surely missing sth. but what???
Any help appreciated! Many thanks!
public static void CreatePresentation(string filepath)
{
// Create a presentation at a specified file path. The presentation document type is pptx, by default.
PresentationDocument presentationDoc = PresentationDocument.Create(filepath, PresentationDocumentType.Presentation);
PresentationPart presentationPart = presentationDoc.AddPresentationPart();
presentationPart.Presentation = new Presentation();
SlideMasterIdList sldMasterIdList = new SlideMasterIdList(new SlideMasterId() { Id = (UInt32Value)2147483648U, RelationshipId = "rId1" });
SlideIdList sldIdList = new SlideIdList();
SlideSize sldSize = new SlideSize() { Cx = 2751 * mm / 10, Cy = 1905 * mm / 10, Type = SlideSizeValues.Screen4x3 }; // DIN A4 - Landscape.
NotesSize notesSize = new NotesSize() { Cx = 1905 * mm / 10, Cy = 2751 * mm / 10 }; // DIN A4 - Portrait.
DefaultTextStyle defaultTextStyle = new DefaultTextStyle();
presentationPart.Presentation.Append(sldMasterIdList, sldIdList, sldSize, notesSize, defaultTextStyle);
#region [ SlidePart ]
SlidePart slidePart = presentationPart.AddNewPart<SlidePart>("rId2");
sldIdList.AppendChild<SlideId>(new SlideId() { Id = (UInt32Value)256U, RelationshipId = "rId2" });
slidePart.Slide = new Slide
(
new CommonSlideData
(
new ShapeTree
(
new P.NonVisualGroupShapeProperties
(
new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" },
new P.NonVisualGroupShapeDrawingProperties(),
new ApplicationNonVisualDrawingProperties()
),
new GroupShapeProperties(new DocumentFormat.OpenXml.Drawing.TransformGroup())
)
),
new ColorMapOverride(new MasterColorMapping())
);
ImagePart ip = slidePart.AddImagePart(ImagePartType.Jpeg, "rId2");
MyStream.Position = 0;
ip.FeedData(MyStream);
#endregion
#region [ slideLayoutPart ]
SlideLayoutPart slideLayoutPart = slidePart.AddNewPart<SlideLayoutPart>("rId1");
SlideLayout slideLayout = new SlideLayout
(
new CommonSlideData
(
new ShapeTree
(
new P.NonVisualGroupShapeProperties
(
new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" },
new P.NonVisualGroupShapeDrawingProperties(),
new ApplicationNonVisualDrawingProperties()
),
new GroupShapeProperties
(
new DocumentFormat.OpenXml.Drawing.TransformGroup()
)
)
),
new ColorMapOverride
(
new MasterColorMapping()
)
);
slideLayoutPart.SlideLayout = slideLayout;
#endregion
#region [ slideMasterPart ]
SlideMasterPart slideMasterPart = slideLayoutPart.AddNewPart<SlideMasterPart>("rId1");
SlideMaster slideMaster = new SlideMaster(
new CommonSlideData(new ShapeTree(
new P.NonVisualGroupShapeProperties(
new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" },
new P.NonVisualGroupShapeDrawingProperties(),
new ApplicationNonVisualDrawingProperties()),
new GroupShapeProperties(new DocumentFormat.OpenXml.Drawing.TransformGroup()),
new P.Shape(
new P.NonVisualShapeProperties(
new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Title Placeholder 1" },
new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }),
new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title })),
new P.ShapeProperties(),
new P.TextBody(
new BodyProperties(),
new ListStyle(),
new Paragraph())))),
new P.ColorMap() { Background1 = D.ColorSchemeIndexValues.Light1, Text1 = D.ColorSchemeIndexValues.Dark1, Background2 = D.ColorSchemeIndexValues.Light2, Text2 = D.ColorSchemeIndexValues.Dark2, Accent1 = D.ColorSchemeIndexValues.Accent1, Accent2 = D.ColorSchemeIndexValues.Accent2, Accent3 = D.ColorSchemeIndexValues.Accent3, Accent4 = D.ColorSchemeIndexValues.Accent4, Accent5 = D.ColorSchemeIndexValues.Accent5, Accent6 = D.ColorSchemeIndexValues.Accent6, Hyperlink = D.ColorSchemeIndexValues.Hyperlink, FollowedHyperlink = D.ColorSchemeIndexValues.FollowedHyperlink },
new SlideLayoutIdList(new SlideLayoutId() { Id = (UInt32Value)2147483649U, RelationshipId = "rId1" }),
new TextStyles(new TitleStyle(), new BodyStyle(), new OtherStyle()));
slideMasterPart.SlideMaster = slideMaster;
slideMasterPart.AddPart(slideLayoutPart, "rId1");
presentationPart.AddPart(slideMasterPart, "rId1");
#endregion
#region [ Theme ]
ThemePart themePart = slideMasterPart.AddNewPart<ThemePart>("rId5");
D.Theme theme = new D.Theme() { Name = "Office Theme" };
D.ThemeElements themeElements = new D.ThemeElements(
new D.ColorScheme(
new D.Dark1Color(new D.SystemColor() { Val = D.SystemColorValues.WindowText, LastColor = "000000" }),
new D.Light1Color(new D.SystemColor() { Val = D.SystemColorValues.Window, LastColor = "FFFFFF" }),
new D.Dark2Color(new D.RgbColorModelHex() { Val = "1F497D" }),
new D.Light2Color(new D.RgbColorModelHex() { Val = "EEECE1" }),
new D.Accent1Color(new D.RgbColorModelHex() { Val = "4F81BD" }),
new D.Accent2Color(new D.RgbColorModelHex() { Val = "C0504D" }),
new D.Accent3Color(new D.RgbColorModelHex() { Val = "9BBB59" }),
new D.Accent4Color(new D.RgbColorModelHex() { Val = "8064A2" }),
new D.Accent5Color(new D.RgbColorModelHex() { Val = "4BACC6" }),
new D.Accent6Color(new D.RgbColorModelHex() { Val = "F79646" }),
new D.Hyperlink(new D.RgbColorModelHex() { Val = "0000FF" }),
new D.FollowedHyperlinkColor(new D.RgbColorModelHex() { Val = "800080" })) { Name = "Office" },
new D.FontScheme(
new D.MajorFont(
new D.LatinFont() { Typeface = "Calibri" },
new D.EastAsianFont() { Typeface = "" },
new D.ComplexScriptFont() { Typeface = "" }),
new D.MinorFont(
new D.LatinFont() { Typeface = "Calibri" },
new D.EastAsianFont() { Typeface = "" },
new D.ComplexScriptFont() { Typeface = "" })) { Name = "Office" },
new D.FormatScheme(
new D.FillStyleList(
new D.SolidFill(new D.SchemeColor() { Val = D.SchemeColorValues.PhColor }),
new D.GradientFill(
new D.GradientStopList(
new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 50000 },
new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 },
new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 37000 },
new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 35000 },
new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 15000 },
new D.SaturationModulation() { Val = 350000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 100000 }
),
new D.LinearGradientFill() { Angle = 16200000, Scaled = true }),
new D.NoFill(),
new D.PatternFill(),
new D.GroupFill()),
new D.LineStyleList(
new D.Outline(
new D.SolidFill(
new D.SchemeColor(
new D.Shade() { Val = 95000 },
new D.SaturationModulation() { Val = 105000 }) { Val = D.SchemeColorValues.PhColor }),
new D.PresetDash() { Val = D.PresetLineDashValues.Solid })
{
Width = 9525,
CapType = D.LineCapValues.Flat,
CompoundLineType = D.CompoundLineValues.Single,
Alignment = D.PenAlignmentValues.Center
},
new D.Outline(
new D.SolidFill(
new D.SchemeColor(
new D.Shade() { Val = 95000 },
new D.SaturationModulation() { Val = 105000 }) { Val = D.SchemeColorValues.PhColor }),
new D.PresetDash() { Val = D.PresetLineDashValues.Solid })
{
Width = 9525,
CapType = D.LineCapValues.Flat,
CompoundLineType = D.CompoundLineValues.Single,
Alignment = D.PenAlignmentValues.Center
},
new D.Outline(
new D.SolidFill(
new D.SchemeColor(
new D.Shade() { Val = 95000 },
new D.SaturationModulation() { Val = 105000 }) { Val = D.SchemeColorValues.PhColor }),
new D.PresetDash() { Val = D.PresetLineDashValues.Solid })
{
Width = 9525,
CapType = D.LineCapValues.Flat,
CompoundLineType = D.CompoundLineValues.Single,
Alignment = D.PenAlignmentValues.Center
}),
new D.EffectStyleList(
new D.EffectStyle(
new D.EffectList(
new D.OuterShadow(
new D.RgbColorModelHex(
new D.Alpha() { Val = 38000 }) { Val = "000000" }) { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false })),
new D.EffectStyle(
new D.EffectList(
new D.OuterShadow(
new D.RgbColorModelHex(
new D.Alpha() { Val = 38000 }) { Val = "000000" }) { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false })),
new D.EffectStyle(
new D.EffectList(
new D.OuterShadow(
new D.RgbColorModelHex(
new D.Alpha() { Val = 38000 }) { Val = "000000" }) { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false }))),
new D.BackgroundFillStyleList(
new D.SolidFill(new D.SchemeColor() { Val = D.SchemeColorValues.PhColor }),
new D.GradientFill(
new D.GradientStopList(
new D.GradientStop(
new D.SchemeColor(new D.Tint() { Val = 50000 },
new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 },
new D.GradientStop(
new D.SchemeColor(new D.Tint() { Val = 50000 },
new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 },
new D.GradientStop(
new D.SchemeColor(new D.Tint() { Val = 50000 },
new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 }),
new D.LinearGradientFill() { Angle = 16200000, Scaled = true }),
new D.GradientFill(
new D.GradientStopList(
new D.GradientStop(
new D.SchemeColor(new D.Tint() { Val = 50000 },
new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 },
new D.GradientStop(
new D.SchemeColor(new D.Tint() { Val = 50000 },
new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 }),
new D.LinearGradientFill() { Angle = 16200000, Scaled = true }))) { Name = "Office" });
theme.Append(themeElements);
theme.Append(new D.ObjectDefaults());
theme.Append(new D.ExtraColorSchemeList());
themePart.Theme = theme;
presentationPart.AddPart(themePart, "rId5");
#endregion
P.Picture picture = new P.Picture
(
new P.NonVisualPictureProperties
(
new P.NonVisualDrawingProperties() { Id = (UInt32Value)1026U, Name = "Photo", Description = "" },
new P.NonVisualPictureDrawingProperties
(
new D.PictureLocks() { NoChangeAspect = true }
),
new ApplicationNonVisualDrawingProperties()
),
new D.BlipFill
(
new D.Blip
(
new D.NonVisualPicturePropertiesExtensionList()
) { Embed = "rId2" },
new D.Stretch
(
new D.FillRectangle()
)
),
new P.ShapeProperties
(
new D.Transform2D
(
new D.Offset() { X = 1 * cm, Y = 3 * cm },
new D.Extents() { Cx = 16 * cm, Cy = 14 * cm }
),
new D.PresetGeometry
(
new D.AdjustValueList()
) { Preset = D.ShapeTypeValues.Rectangle }
)
);
slidePart.Slide.CommonSlideData.ShapeTree.AppendChild<P.Picture>(picture);
//Close the presentation handle
presentationDoc.Close();
}
My problem was really very simple - just found it comparing the repaired against genererated version (serialized XML)...
Unrepaired there was in the BlipFill portion the Prefix a: repaired p:...
There are BlipFills both in Presentation and Drawing
So my mistake was in using the D.BlipFill instead of P.BlipFill
Now it works as expected.
Indeed, the author of the post uses the class BlipFill from DocumentFormat.OpenXml.Drawing instead of DocumentFormat.OpenXml.Presentation namespace. The PPTX file is created successfully, but when opening the file in PowerPoint it alerts that the file has to be repaired.
For whose who has a similar problem in other parts of the code, Open XML SDK has a validator that allows to diagnose such issues. This approach is mush simpler than comparing the repaired and unrepaired presentations manually.
The code is below.
OpenXmlValidator validator = new OpenXmlValidator();
var doc = PresentationDocument.Open(pptPath, true);
var errors = validator.Validate(doc);
The errors then contains the issues in the presentation.