Unable to create component using Coreservice - tridion

I am trying to create component using coreservice using the below code, and when i execute the exe, am getting the error "unable to find the uuid:""64c7e56a-161d-4698-a76b-7fd96227948d:Content".
I have opened the schema which am linking to this component, and i seen this UUID over there also.
as of now am just trying to create a component by providing the folder, schema, title as hard corded.
if you can guide me how to add field value also in component, that would be great. (For example assume that i have a field "Text" in my schema which am linking to this component, and i want to add "This is the Text" in this field of my component using the same program.
can you please help me out on this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DctmToSDLMigration.SDLCoreServiceReference;
namespace DctmToSDLMigration
{
class Program
{
static DctmToSDLMigration.SDLCoreServiceReference.SessionAwareCoreService2010Client client = new SessionAwareCoreService2010Client();
static ReadOptions readoptions = new ReadOptions();
static void CreateComponent()
{
try
{
string TargetFolderTcmId = "tcm:148-1263-2";
string LinkSchemaTcmId = "tcm:148-11460-8";
ComponentData CurrentMigrationComponent = client.GetDefaultData(ItemType.Component, TargetFolderTcmId) as ComponentData;
LinkToSchemaData SchemaToUse = new LinkToSchemaData();
SchemaToUse.IdRef = LinkSchemaTcmId.ToString();
CurrentMigrationComponent.Schema = SchemaToUse ;
CurrentMigrationComponent.Title = "Test component";
client.Create(CurrentMigrationComponent, readoptions);
Console.WriteLine(CurrentMigrationComponent.Id);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
static void Main(string[] args)
{
CreateComponent();
}
}
}

You need to set the Content Property of the Component.
XmlDocument doc = new XmlDocument();
doc.LoadXml(string.Format(#"<Content xmlns='{0}'><Test>Hello</Test></Content>", SchemaToUse.NamespaceUri));
CurrentMigrationComponent.Content = doc.DocumentElement;

Related

Why does validation fail in code, but work in Newtonsoft web validator?

This should validate against the schema as verified in the online Newtonsoft validator at https://www.jsonschemavalidator.net/ The schema looks correct (although siblings to $ref are not technically valid in JSON Schema 7.) Instead I get a validation error. To repro:
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using System.Net;
namespace TestValidation
{
class Program
{
static void Main(string[] args)
{
var client = new WebClient();
var schema = JSchema.Parse(client.DownloadString("https://onedrive.live.com/download?cid=B22A8A90BE24B544&resid=B22A8A90BE24B544%211131778&authkey=AMRvXjC2uXSPy3s"));
var file = JObject.Parse(client.DownloadString("https://onedrive.live.com/download?cid=B22A8A90BE24B544&resid=B22A8A90BE24B544%211131779&authkey=AAwVQjelPWA7HZ4"));
file.Validate(schema);
}
}
}

Dotnet core integration test fixture causing a json parsing error

So I am building a template API project and am currently working on adding in some integration tests.
At the moment, when I run my test, for some reason it returns a JSON parsing error:
Newtonsoft.Json.JsonReaderException : Unexpected character encountered
while parsing value: A. Path '', line 0, position 0.
This looks like it's an issue with my endpoint, but it works fine when just running localhost with a normal startup routine, so I think it's because I can't get my fixture just right. especilaly because, when i try another fixture (listed below) it doesn't give me an error anymore and just hangs.
The test itself can be found here.
namespace Foundation.Api.Tests.IntegrationTests
{
using FluentAssertions;
using Foundation.Api.Data;
using Foundation.Api.Models;
using Foundation.Api.Tests.Fakes;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;
public class GetValueToReplaceIntegrationTests : IClassFixture<CustomWebApplicationFactory<Startup>>
{
public GetValueToReplaceIntegrationTests(CustomWebApplicationFactory<Startup> factory)
{
_factory = factory;
}
private readonly CustomWebApplicationFactory<Startup> _factory;
[Fact]
public async Task GetValueToReplaces_ReturnsSuccessCodeAndResourceWithAccurateFields()
{
var fakeValueToReplaceOne = new FakeValueToReplace { }.Generate();
var fakeValueToReplaceTwo = new FakeValueToReplace { }.Generate();
var appFactory = _factory;
using (var scope = appFactory.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<ValueToReplaceDbContext>();
context.Database.EnsureCreated();
context.ValueToReplaces.RemoveRange(context.ValueToReplaces);
context.ValueToReplaces.AddRange(fakeValueToReplaceOne, fakeValueToReplaceTwo);
context.SaveChanges();
}
var client = appFactory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var result = await client.GetAsync($"api/v1/ValueToReplaceLowers")
.ConfigureAwait(false);
var responseContent = await result.Content.ReadAsStringAsync()
.ConfigureAwait(false);
var response = JsonConvert.DeserializeObject<IEnumerable<ValueToReplaceDto>>(responseContent);
// Assert
result.StatusCode.Should().Be(200);
response.Should().ContainEquivalentOf(fakeValueToReplaceOne);
response.Should().ContainEquivalentOf(fakeValueToReplaceTwo);
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
The fixture can be found here.
namespace Foundation.Api.Tests
{
using Foundation.Api.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder
.ConfigureServices(services =>
{
// Remove the app's ValueToReplaceDbContext registration.
var descriptor = services.SingleOrDefault(
d => d.ServiceType ==
typeof(DbContextOptions<ValueToReplaceDbContext>));
if (descriptor != null)
{
services.Remove(descriptor);
}
// Add ValueToReplaceDbContext using an in-memory database for testing.
services.AddDbContext<ValueToReplaceDbContext>(options =>
{
options.UseInMemoryDatabase("TestingDb");
});
// Build the service provider.
var sp = services.BuildServiceProvider();
// Create a scope to obtain a reference to the database
// context (ValueToReplaceDbContext).
using (var scope = sp.CreateScope())
{
var scopedServices = scope.ServiceProvider;
var db = scopedServices.GetRequiredService<ValueToReplaceDbContext>();
// Ensure the database is created.
db.Database.EnsureCreated();
try
{
db.RemoveRange(db.ValueToReplaces);
// Seed the database with test data.
//Utilities.InitializeDbForTests(db);
}
catch (Exception ex)
{
}
}
});
}
}
}
I've also tried a fixture like so inspired by this one which just times out.
namespace Foundation.Api.Tests
{
using Foundation.Api.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder
.ConfigureServices(services =>
{
// Create a new service provider.
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();
// Add a database context using an in-memory
// database for testing.
services.AddDbContext<ValueToReplaceDbContext>(options =>
{
options.UseInMemoryDatabase("InMemoryDbForTesting");
options.UseInternalServiceProvider(serviceProvider);
});
services.AddScoped(provider => provider.GetService<ValueToReplaceDbContext>());
var sp = services.BuildServiceProvider();
// Create a scope to obtain a reference to the database
using var scope = sp.CreateScope();
var scopedServices = scope.ServiceProvider;
var context = scopedServices.GetRequiredService<ValueToReplaceDbContext>();
// Ensure the database is created.
context.Database.EnsureCreated();
try
{
// Seed the database with test data.
//Utilities.InitializeDbForTests(context);
}
catch (Exception ex)
{
//logger.LogError(ex, "An error occurred seeding the " +
// $"database with test messages. Error: {ex.Message}");
}
})
.UseEnvironment("Test");
}
}
}
The repo can be found here.

Acumatica - Add Reports dropdown to Kit Assembly Screen

I have been trying to add a Reports dropdown to the Kit Assembly screen (IN307000). We have custom reports that are based on the KitInventoryID that will be generated to print a tag essentially and these reports need to be added to the actions of the screen. I noticed that there is normally a transfer in most Report screens that will be used to transfer data so I did write my own statement at the top. Here is what I have so far:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using PX.Data;
using PX.Objects.CS;
using PX.Objects.IN.Overrides.INDocumentRelease;
using PX.Objects.GL;
using PX.Objects.CM;
using System.Diagnostics;
using PX.Objects;
using PX.Objects.IN;
namespace PX.Objects.IN
{
public class KitAssemblyEntry_Extension:PXGraphExtension<KitAssemblyEntry>
{
public PXSelect<INKitRegister, Where<INKitRegister.docType, Equal<Current<INKitRegister.docType>>, And<INKitRegister.kitInventoryID, Equal<Current<INKitRegister.kitInventoryID>>>>> transfer;
public override void Initialize()
{
Report.AddMenuAction(MasterTag);
Report.MenuAutoOpen = true;
}
#region Event Handlers
public PXAction<INKitRegister> Report;
[PXButton]
[PXUIField(DisplayName = "Print Tag", MapEnableRights = PXCacheRights.Select)]
protected void report()
{ }
public PXAction<INKitRegister> MasterTag;
[PXUIField(DisplayName = "Sample/Value Tag", MapEnableRights = PXCacheRights.Select)]
[PXLookupButton]
public virtual IEnumerable masterTag(PXAdapter adapter)
{
INKitRegister doc = Base.transfer.Current;
if (doc != null)
{
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters["DocType"] = this.transfer.Current.DocType;
parameters["ItemNumber"] = this.transfer.Current.KitInventoryID.ToString();
throw new PXReportRequiredException(parameters, "IN610004", "Sample/Value Tag");
}
}
#endregion
}
}
However, when I try to publish I get this error:
Building directory '\WebSiteValidationDomain\App_RuntimeCode\'.
\App_RuntimeCode\KitAssemblyEntry.cs(39): error CS1061: 'PX.Objects.IN.KitAssemblyEntry' does not contain a definition for 'transfer' and no extension method 'transfer' accepting a first argument of type 'PX.Objects.IN.KitAssemblyEntry' could be found (are you missing a using directive or an assembly reference?)
\App_RuntimeCode\KitAssemblyEntry.cs(39): error CS1061: 'PX.Objects.IN.KitAssemblyEntry' does not contain a definition for 'transfer' and no extension method 'transfer' accepting a first argument of type 'PX.Objects.IN.KitAssemblyEntry' could be found (are you missing a using directive or an assembly reference?)
I have also tried changing the INKitRegister doc = Base.transfer.Current;to INKitRegister doc = Base.Document.Current; but get this error:
\App_RuntimeCode\KitAssemblyEntry.cs(37): error CS0161: 'PX.Objects.IN.KitAssemblyEntry_Extension.masterTag(PX.Data.PXAdapter)': not all code paths return a value
\App_RuntimeCode\KitAssemblyEntry.cs(37): error CS0161: 'PX.Objects.IN.KitAssemblyEntry_Extension.masterTag(PX.Data.PXAdapter)': not all code paths return a value
Here is the fixed coded and it is working properly.
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using PX.Data;
using PX.Objects.CS;
using PX.Objects.IN.Overrides.INDocumentRelease;
using PX.Objects.GL;
using PX.Objects.CM;
using System.Diagnostics;
using PX.Objects;
using PX.Objects.IN;
namespace PX.Objects.IN
{
public class KitAssemblyEntry_Extension:PXGraphExtension<KitAssemblyEntry>
{
public PXSelect<INKitRegister, Where<INKitRegister.docType, Equal<Current<INKitRegister.docType>>, And<INKitRegister.kitInventoryID, Equal<Current<INKitRegister.kitInventoryID>>>>> transfer;
public override void Initialize()
{
Report.AddMenuAction(MasterTag);
Report.MenuAutoOpen = true;
}
#region Event Handlers
public PXAction<INKitRegister> Report;
[PXButton]
[PXUIField(DisplayName = "Print Tag", MapEnableRights = PXCacheRights.Select)]
protected void report()
{ }
public PXAction<INKitRegister> MasterTag;
[PXUIField(DisplayName = "Sample/Value Tag", MapEnableRights = PXCacheRights.Select)]
[PXLookupButton]
public virtual IEnumerable masterTag(PXAdapter adapter)
{
INKitRegister doc = Base.Document.Current;
if (doc != null)
{
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters["DocType"] = this.transfer.Current.DocType;
parameters["ItemNumber"] = this.transfer.Current.KitInventoryID.ToString();
throw new PXReportRequiredException(parameters, "IN610004", "Sample/Value Tag");
}
return adapter.Get();
}
#endregion
}
}

How do I extract the output of Style or Javascript Bundle in ASP.NET

I am working on a single page app that uses a CSS bundle in a .cshtml file as shown below:
#Styles.Render("~/content/css/bundle-css")
However, to improve the loading performance of the site, I would like to embed the entire CSS that was bundled and minified into my .cshtml file. So I would like to convert the code above to look like:
#Html.GetInternalCss("~/content/css/bundle-css");
Where GetInternalCss is an extension method that will take the css virtual path and output an internal css. The code is shown below:
public static MvcHtmlString GetInternalCss(this HtmlHelper html, string styleBundleVirtualPath)
{
//TODO:
var bundledCss = "How do I extract the css from the virtual path?";
var internalCss = string.Format("<style>{0}</style>", bundledCss);
return new MvcHtmlString(internalCss);
}
I know the bundled css is in memory somewhere. I just need to know how to get it out. Thanks for all your help.
I may have answered my own question with the code below:
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Web.Mvc;
using System.Web.Optimization;
namespace SomeNameSpace
{
public static class HtmlHelpExtensions
{
private static readonly IDictionary<string,string> InternalCssCache = new ConcurrentDictionary<string, string>();
public static MvcHtmlString GetInternalCss(this HtmlHelper html, string styleBundleVirtualPath)
{
string internalCss = null;
if (InternalCssCache.TryGetValue(styleBundleVirtualPath, out internalCss))
return new MvcHtmlString(internalCss);
//download the css
var relativeUrl = Styles.Url(styleBundleVirtualPath);
var url = html.ViewContext.HttpContext.Request.Url + relativeUrl.ToString().Trim('/');
var webClient = new WebClient();
var css = webClient.DownloadString(url);
internalCss = string.Format("<style>{0}</style>", css);
InternalCssCache[styleBundleVirtualPath] = internalCss;
return new MvcHtmlString(internalCss);
}
}
}

tool/script to visit all pages in an ASP.NET project?

Does anybody know of a tool, script, package, whatever that I can use to visit all pages in an ASP.NET Webforms web application project? (we aren't using any MVC functionality)
Preferably, I would like to be able to generate a list of URLs to hit, edit the list so I can add some query string params, hit all the pages in the list, and collect HTTP response codes: (200, 404, 500, 301, whatever).
Design time
Instead of using string literals for URLs in your application, define Url() methods in each page class like this:
public static string Url() { get { return "~/this_page.aspx"; } }
public static string Url(int ID) { get { return "~/this_page.aspx?id=" + ID; } }
Or list all URLs in a static class
public static class URL {
public static string Login() { get { return "~/login.aspx"; } }
public static string DisplayRecord(int recordID)
{ get { return "~/display.aspx?id=" + recordID; } }
Runtime
Use a web testing framework to crawl all links and edit the result. I blogged about one possible solution using Selenium.
I made a WinForms application that gets the pages that can be accessed from the .csproject and can open them by clicking a button.
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
namespace OpenAllPages
{
public partial class Form1 : Form
{
public static IList<string> Pages;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string xmlstring = ReadXml("TaskManager.csproj");
Pages = ParseAllPages(xmlstring);
pagesListBox.DataSource = Pages;
}
private string ReadXml(string location)
{
try
{
var myFile = new StreamReader(location);
string myString = myFile.ReadToEnd();
myFile.Close();
return myString;
}
catch (Exception e)
{
MessageBox.Show(String.Format("An error occurred: '{0}'", e.Message));
}
return null;
}
private IList<string> ParseAllPages(string xmlstring)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlstring);
XPathNavigator nav = xmlDoc.DocumentElement.CreateNavigator();
XmlNamespaceManager manager = new XmlNamespaceManager(nav.NameTable);
manager.AddNamespace("x", "http://schemas.microsoft.com/developer/msbuild/2003");
var elements = nav.Select("x:ItemGroup/x:Content", manager);
var pageList = new List<string>();
while (elements.MoveNext())
{
var page = elements.Current.GetAttribute("Include", "");
if (page.EndsWith(".aspx"))
pageList.Add(page);
}
return pageList as IList<string>;
}
private string AddPagePrefix(string page)
{
return "http://localhost:8080/" + page;
}
private void openAllButton_Click(object sender, EventArgs e)
{
foreach (string page in Pages)
System.Diagnostics.Process.Start("chrome.exe", AddPagePrefix(page));
}
}
}
Here is a link to the code
You need to place the project file which contains the pages you want to open in the OpenAllPages project and set it's Copy to Output property to "Copy if newer".
I Form1_Load change TaskManager.csproj to the name of your project file.
And in:
System.Diagnostics.Process.Start("chrome.exe", AddPagePrefix(page));
rename parameter to the executable of the browser you are using.

Resources