Sitecore change rendering datasource - sitecore

Hello I would like create special page for private use for where i will be have possibility to change data source value for each rendering item.
I have created next code, but it dos't save any changes to items.
SC.Data.Database master = SC.Configuration.Factory.GetDatabase("master");
SC.Data.Items.Item itm = master.GetItem(tbPath.Text);
if (itm != null)
{
// Get the sublayout to update
//string sublayout_name = txtSublayout.Text.Trim();
//if (!string.IsNullOrEmpty(sublayout_name))
{
// Get the renderings on the item
RenderingReference[] refs = itm.Visualization.GetRenderings(SC.Context.Device, true);
if (refs.Any())
{
//var data = refs.Select(d=>d);
//refs[0].Settings.DataSource
var sb = new StringBuilder();
using (new SC.SecurityModel.SecurityDisabler())
{
itm.Editing.BeginEdit();
foreach (var d in refs)
{
if (d.Settings.DataSource.Contains("/sitecore/content/Site Configuration/"))
{
var newds = d.Settings.DataSource.Replace("/sitecore/content/Site Configuration/", "/sitecore/content/Site Configuration/" + tbLanguage.Text + "/");
// sb.AppendLine(string.Format("{0} old: {1} new: {2}<br/>", d.Placeholder, d.Settings.DataSource, newds));
d.Settings.DataSource = newds;
}
}
itm.Editing.EndEdit();
}
//lblResult.Text = sb.ToString();
}
}
}
how I can change data source ?
thanks

You're mixing up two different things in Sitecore here.
The datasource that is assigned to a rendering at run-time, when Sitecore is rendering a page
The datasource that is assigned to the presentation details of an item
The simplest approach to achieve what I think you're trying to achieve, would be this.
Item itm = database.GetItem("your item");
string presentationXml = itm["__renderings"];
itm.Editing.BeginEdit();
presentationXml.Replace("what you're looking for", "what you want to replace it with");
itm.Editing.EndEdit();
(I've not compiled and run this code, but it should pretty much work as is)

You are not saving the changes to the field.
Use the LayoutDefinitation class to parse the layout field, and foreach all the device definition, and rendering definitions.
And finaly commit the LayoutDifinition to the layout field.
SC.Data.Items.Item itm = master.GetItem(tbPath.Text);
var layoutField = itm.Fields[Sitecore.FieldIDs.LayoutField];
LayoutDefinition layout = LayoutDefinition.Parse(layoutField.Value);
for (int i = 0; i < layout.Devices.Count; i++)
{
DeviceDefinition device = layout.Devices[i] as DeviceDefinition;
for (int j = 0; j < device.Renderings.Count; j++)
{
RenderingDefinition rendering = device.Renderings[j] as RenderingDefinition;
rendering.Datasource = rendering.DataSource.Replace("/sitecore/content/Site Configuration/",
"/sitecore/content/Site Configuration/" + tbLanguage.Text + "/");
}
}
itm.Editing.BeginEdit();
var xml =layout.ToXml()
layoutField.Value = xml;
itm.Editing.EndEdit();
The code is not testet, but are changed from something i have in production to replace datasources on a copy event

If any one looking for single line Linq : (Tested)
var layoutField = item.Fields[Sitecore.FieldIDs.LayoutField];
if (layoutField != null)
{
var layout = LayoutDefinition.Parse(layoutField.Value);
if (layout != null)
{
foreach (var rendering in layout.Devices.Cast<DeviceDefinition>()
.SelectMany
(device => device.Renderings.Cast<RenderingDefinition>()
.Where
(rendering => rendering.ItemID == "RenderingYoulooking")))
{
rendering.Datasource = "IDYouWantToInsert";
}
layoutField.Value = layout.ToXml();
}
}

Related

Multiple unrelated dataViewMappings for custom visuals Power BI Report Server

There is a well-known problem connected with creating custom visuals for Power BI Report Sever - you can't create multiple unrelated dataViewMappings. It means that every field you put inside Fields must be related.
There have been a long-lasting request from users to add this feature.
However, it looks like Microsoft hasn't implemented it yet.
https://github.com/Microsoft/PowerBI-visuals/issues/251
I found a workaround - you can combine all your different tables in one and chain with a tableName key.
For example, you have a table A:
value1|value2|tableName
1|2|tableA
3|4|tableA
and a table B:
value3|tableName
a|tableB
b|tableB
You create a tableC by using M function Table.Combine({tableA, tableB}) or other technique. As a result, it looks like this:
value1|value2|value3|tableName
1|2|null|tableA
3|4|null|tableA
null|null|a|tableB
null|null|b|tableB
Then, inside your custom visual you implement the following function which parses the input:
public parseOptionsToTables(options: VisualUpdateOptions) {
var i: number;
var j: number;
var cntRows: number;
var cntCols: number;
var nameTable: string;
var tempDict: {} = {};
var tempVal: any;
var colName: string;
var cats: any = options.dataViews[0].table;
this.tables = {};
cntCols = cats.columns.length;
cntRows = cats.rows.length;
for (i = 0; i < cntRows; i++) {
tempVal = null;
colName = null;
nameTable = null;
tempDict = {};
for (j = 0; j < cntCols; j++) {
//for every row - check the TableName column and add to dict
tempVal = cats.rows[i][j];
colName = cats.columns[j].displayName;
if (colName == 'tableName') {
nameTable = tempVal;
} else {
//add id not null
if (tempVal !== null) {
tempDict[colName] = tempVal;
}
}
}
//push to dict
this.tables[nameTable] = this.tables[nameTable] || [];
this.tables[nameTable].push(this.deepcopy(tempDict));
}
}
As a result, it creates a this.tables object with your tableA and tableB inside.
Although it helps to solve the main problem, I can't get out of feeling of creating crutches.
So, are there any other approaches to solve this problem more effeciently?

Place order, clear Cart in Nop Commerce 4

How can I Place an order from the cart and clear the cart?
I want to do this in my own controller and not by the checkout page.
I try to use this, but it doesn't work
//place order
var processPaymentRequest = HttpContext.Session.Get<ProcessPaymentRequest>("OrderPaymentInfo");
if (processPaymentRequest == null)
{
//Check whether payment workflow is required
if (_orderProcessingService.IsPaymentWorkflowRequired(cart))
return RedirectToRoute("CheckoutPaymentInfo");
processPaymentRequest = new ProcessPaymentRequest();
}
GenerateOrderGuid(processPaymentRequest);
processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
processPaymentRequest.PaymentMethodSystemName =
_genericAttributeService.GetAttribute<string>(_workContext.CurrentCustomer,
NopCustomerDefaults.SelectedPaymentMethodAttribute,
_storeContext.CurrentStore.Id);
HttpContext.Session.Set<ProcessPaymentRequest>("OrderPaymentInfo",
processPaymentRequest);
var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);
You can use PlaceOrder method in IOrderProcessingService to place an order. CheckoutController also uses this method. For using it, you have to create a ProcessPaymentRequest by yourself. here is a sample code for such a task (I use the code placed in the CheckoutController which doing the same job):
var processPaymentRequest = HttpContext.Session.Get<ProcessPaymentRequest>("OrderPaymentInfo");
if (processPaymentRequest == null)
{
//Check whether payment workflow is required
if (_orderProcessingService.IsPaymentWorkflowRequired(cart))
return RedirectToRoute("CheckoutPaymentInfo");
processPaymentRequest = new ProcessPaymentRequest();
}
//prevent 2 orders being placed within an X seconds time frame
if (!IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer))
throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval"));
//place order
processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
processPaymentRequest.PaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(
SystemCustomerAttributeNames.SelectedPaymentMethod,
_genericAttributeService, _storeContext.CurrentStore.Id);
//____this is main line of code____
var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);
if (placeOrderResult.Success)
{
HttpContext.Session.Set<ProcessPaymentRequest>("OrderPaymentInfo", null);
//do payment process:
var postProcessPaymentRequest = new PostProcessPaymentRequest
{
Order = placeOrderResult.PlacedOrder
};
_paymentService.PostProcessPayment(postProcessPaymentRequest);
if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone)
{
//redirection or POST has been done in PostProcessPayment
return Content("Redirected");
}
return RedirectToRoute("CheckoutCompleted", new { orderId = placeOrderResult.PlacedOrder.Id });
}

when I select many row of table and insert breakpoint dont show my list correctly?

when I trace code don't show city list correctly
how I can fix it ?
My code
public ActionResult GetCity(int idCountry)
{
TravelEnterAdminTemplate.Models.LG.MyJsonResult myresult = new Models.LG.MyJsonResult();
var citystable = db.Cities.Where(p => p.CountryId == idCountry).ToList();
if (citystable != null)
{
myresult.Result = true;
myresult.obj = citystable;
}
else
{
myresult.Result = false;
myresult.message = "داده ای یافت نشد";
}
return Json(myresult, JsonRequestBehavior.AllowGet);
}
This is not the error you are getting the data. There were 32 data in cities table . You just click on every node there the detail will visible

XSLT processing on IE11?

What has happened to the XSLT processing in IE11?
On IE8/9/10, you can use:
if (window.ActiveXObject) {
var xslt = new ActiveXObject("Msxml2.XSLTemplate");
....
}
On Chrome/Firefox/Safari, you can use:
else {
var xsltProcessor = new XSLTProcessor();
}
But on IE11, neither of these are supported. Does anyone know how this can be accomplished?
Try
if (window.ActiveXObject || "ActiveXObject" in window)
This worked for me working with IE11 and allowed me to instantiate ActiveX objects since the standard old check was being bypassed.
This works for me on Chrome/Edge/Firefox/IE11
function loadXMLDoc(filename) {
if (window.ActiveXObject || "ActiveXObject" in window) {
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} else {
xhttp = new XMLHttpRequest();
}
xhttp.open("GET", filename, false);
xhttp.send("");
return xhttp.responseXML;
}
if (window.ActiveXObject || "ActiveXObject" in window) {
ie();
} else {
xml = loadXMLDoc("input.xml");
xsl = loadXMLDoc("mmlctop2_0.xsl");
if (document.implementation && document.implementation.createDocument) {
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToDocument(xml, document);
var serializer = new XMLSerializer();
var transformed = serializer.serializeToString(resultDocument.documentElement);
alert(transformed);
}
}
// https://msdn.microsoft.com/en-us/library/ms753809(v=vs.85).aspx
function ie() {
var xslt = new ActiveXObject("Msxml2.XSLTemplate.3.0");
var xslDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.3.0");
var xslProc;
xslDoc.async = false;
xslDoc.load("mmlctop2_0.xsl");
if (xslDoc.parseError.errorCode != 0) {
var myErr = xslDoc.parseError;
alert("You have error " + myErr.reason);
} else {
xslt.stylesheet = xslDoc;
var xmlDoc = new ActiveXObject("Msxml2.DOMDocument.3.0");
xmlDoc.async = false;
xmlDoc.load("input.xml");
if (xmlDoc.parseError.errorCode != 0) {
var myErr = xmlDoc.parseError;
alert("You have error " + myErr.reason);
} else {
xslProc = xslt.createProcessor();
xslProc.input = xmlDoc;
xslProc.addParameter("param1", "Hello");
xslProc.transform();
alert(xslProc.output);
}
}
}
You could consider Saxon CE, an XSLT 2.0 processor implemented entirely in JavaScript. This would give you a consistent API across all browsers and would allow you to code using the more powerful XSLT 2.0 language rather than 1.0.
The reason if(window.ActiveXObject) fails in IE11 is because for some reason window.ActiveXObject has become falsy, even though it is still a function. I've taken to being more explicit in my feature detection:
if(window.ActiveXObject !== undefined){
...
}
This approach also covers the case of checking for attributes that are present but not set to a truthy value:
if(document.createElement("span").draggable !== undefined){
...
}
For me running site in a compatibility mode in IE - 11 solved the issue....
Note : This might not be a solution , but I was in a situation where one if my old site was using above mentioned code. But I'm not in a position to Re-code the site
You Can use ("ActiveXObject" in window) which will allow all the IE browsers to come inside the if condition .
Exp :-
if ("ActiveXObject" in window) {
// Internet Explorer For all versions like IE8 , IE9 , IE10 or IE11 etc
}else{
// code for Mozilla, Firefox, Opera, etc.
}

subsonic 3.0 active record update

I am able to retrieve database values and insert database values, but I can't figure out what the Update() syntax should be with a where statement.
Environment -> ASP.Net, C#
Settings.ttinclude
const string Namespace = "subsonic_db.Data";
const string ConnectionStringName = "subsonic_dbConnectionString";
//This is the name of your database and is used in naming
//the repository. By default we set it to the connection string name
const string DatabaseName = "subsonic_db";
Retreive example
var product = equipment.SingleOrDefault(x => x.id == 1);
Insert Example
equipment my_equipment = new equipment();
try
{
// insert
my_equipment.parent_id = 0;
my_equipment.primary_id = 0;
my_equipment.product_code = product_code.Text;
my_equipment.product_description = product_description.Text;
my_equipment.product_type_id = Convert.ToInt32(product_type_id.SelectedItem.Value);
my_equipment.created_date = DateTime.Now;
my_equipment.serial_number = serial_number.Text;
my_equipment.Save();
}
catch (Exception err)
{
lblError.Text = err.Message;
}
Edit: Think that I was just too tired last night, it is pretty easy to update. Just use the retrieve function and use the Update() on that.
var equip = Equipment.SingleOrDefault(x => x.id == 1);
lblGeneral.Text = equip.product_description;
equip.product_description = "Test";
equip.Update();
Resolved. View answer above.