Get count data from web database sitecore - sitecore

Can anyone help? How to count data from the "web" database Sitecore?
int count = 0;
var webDb = "web";
var rootPath = "/sitecore/content/Home";
Sitecore.Data.Database web = Sitecore.Configuration.Factory.GetDatabase(webDb);
Sitecore.Data.Items.Item dataWebDb = web.GetItem(rootPath);
return count;
I just tried the code above, but actually can't pass the count of items on the web database.
Please help me.
Thanks in advance.

Here you go
int count = 0;
var webDb = "web";
var rootPath = "/sitecore/content/Home";
Sitecore.Data.Database web = Sitecore.Configuration.Factory.GetDatabase(webDb);
count = web.GetItem(rootPath).Children.Count;
return count;
Filter by template
int count = 0;
var webDb = "web";
var rootPath = "/sitecore/content/Home";
Sitecore.Data.Database web = Sitecore.Configuration.Factory.GetDatabase(webDb);
var items = web.GetItem(rootPath).Children.Where(x => x.TemplateID == new ID("{54a1e38d-a052-40bc-b767-def8bcd7e19b}"));
return items.Count;

Related

SharePoint WebsInfo Description is always Null

I'm trying to get the Description of a Site but it's always null in WebsInfo! Can someone please help me understand this? I also tried using OpenWeb but that was messing up the URL that I passed in.
var site = new SPSite(currentWeb.Url);
string url = currentWeb.Url + #"/" + siteName;
var webObject = site.AllWebs;
foreach (var web in webObject.WebsInfo)
{
siteDescription = web.Description;
}
I guess there is a bug in the WebsInfo that has never been resolved!! I ended up using SPWebCollection.
//This will find the current URL and iterate through it's site Collection
var oSiteCollection = new SPSite(SPContext.Current.Web.Url);
//Gets all webs meaning sub webs and their webs.
var collWebsites = oSiteCollection.AllWebs;
foreach (SPWeb web in collWebsites)
{
if (web.ServerRelativeUrl.StartsWith(kpi.BusinessUnitUrl))
{
kpi.BusinessUnitDescription = web.Description;
kpi.SiteSpecificAreaDescription = web.Description;
var collLists = web.Lists;
IterateLists(collLists, false, ref kpi);
}
}

How I can use predicate buider for Sitecore Lucene Search

I am working on Sitecore 8.1 and I am implementing filter functionality for one of the page by Sitecore lucene. Fot filtering I am using predicate builder. I have 3 multi-lists field on detail items
Product
Category
Services
Now on listing page I have all three group filters as checkboxes as given in below image -
My Requirement is I want to apply Or between inside the group like between products condition should be Or and between two groups condition should be And. For example products and Category should be And.
I followed http://getfishtank.ca/blog/building-dynamic-content-search-linq-queries-in-sitecore-7 blog post to implement this
To achieve this what I am trying -
var builder = PredicateBuilder.True<TestResultItem>();
var Categorybuilder = PredicateBuilder.False<TestResultItem>();
if (!string.IsNullOrEmpty(Categorys))
{
var CategoryItems = Categorys.Split('|');
foreach (var Category in CategoryItems)
{
var ct = Sitecore.ContentSearch.Utilities.IdHelper.NormalizeGuid(Categorys, true);
Categorybuilder = Categorybuilder.Or(i => i.Category.Contains(ct));
}
}
var Servicebuilder = PredicateBuilder.False<TestResultItem>();
if (!string.IsNullOrEmpty(Service))
{
var ServiceItems = Service.Split('|');
foreach (var ser in ServiceItems)
{
var si = Sitecore.ContentSearch.Utilities.IdHelper.NormalizeGuid(ser, true);
Servicebuilder = Servicebuilder.Or(i => i.Service.Contains(si));
}
}
var productsbuilder = PredicateBuilder.False<TestResultItem>();
if (!string.IsNullOrEmpty(products))
{
var productItems = products.Split('|');
foreach (var product in productItems)
{
var pd = Sitecore.ContentSearch.Utilities.IdHelper.NormalizeGuid(product, true);
productsbuilder = productsbuilder.Or(i => i.Category.Contains(pd));
}
}
Servicebuilder = Servicebuilder.Or(Categorybuilder);
productsbuilder = productsbuilder.Or(Servicebuilder);
builder = builder.And(productsbuilder);
The above given code is not working for me. I know I am doing something wrong as I am not good with Predicate builder, Or condition is not working between check boxes group.
Can anyone please tell me where I am wrong in given code or any best way to achieve this.
Any help would be appreciated
I did something similar recently and it works like this:
Create your "or" predicates:
var tagPredicate = PredicateBuilder.False<BlogItem>();
tagPredicate = tagValues.Aggregate(tagPredicate, (current, tag) => current.Or(p => p.Tags.Contains(tag)))
where tagValues is an IEnumerable containing the normalized guids.
I do this for several guid lists. In the end I wrap them together like this:
var predicate = PredicateBuilder.True<BlogItem>();
predicate = predicate.And(tagPredicate);
predicate = predicate.And(...);
Looking at your code: first of all change
Servicebuilder = Servicebuilder.Or(Categorybuilder);
productsbuilder = productsbuilder.Or(Servicebuilder);
builder = builder.And(productsbuilder);
into
builder = builder.And(Categorybuilder);
builder = builder.And(Servicebuilder);
builder = builder.And(productsbuilder);
You need to have one main predicate to join filters with AND condition & other predicates (e.g. for categories or services or products) to join filters internally with OR condition.
// This is your main predicate builder
var builder = PredicateBuilder.True<TestResultItem>();
var Categorybuilder = PredicateBuilder.False<TestResultItem>();
var Servicebuilder = PredicateBuilder.False<TestResultItem>();
var productsbuilder = PredicateBuilder.False<TestResultItem>();
builder = builder.And(Categorybuilder);
builder = builder.And(Servicebuilder);
builder = builder.And(productsbuilder);
Hope this will help you.
Thanks all for providing your inputs -
I updated the code as per your inputs and now it's working.
There was two changes in my old code one was builder for multilist should be inside the if statement and also adding newly created builder to main builder on same location (inside the if statement) -
I am sharing the code below so that if anyone want to use it he can easily copy from here -
var builder = PredicateBuilder.True<TestResultItem>();
if (!string.IsNullOrEmpty(Categorys))
{ var Categorybuilder = PredicateBuilder.False<TestResultItem>();
var CategoryItems = Categorys.Split('|');
foreach (var Category in CategoryItems)
{
var ct = Sitecore.ContentSearch.Utilities.IdHelper.NormalizeGuid(Categorys, true);
Categorybuilder = Categorybuilder.Or(i => i.Category.Contains(ct));
}
builder = builder.And(Categorybuilder);
}
if (!string.IsNullOrEmpty(Service))
{
var Servicebuilder = PredicateBuilder.False<TestResultItem>();
var ServiceItems = Service.Split('|');
foreach (var ser in ServiceItems)
{
var si = Sitecore.ContentSearch.Utilities.IdHelper.NormalizeGuid(ser, true);
Servicebuilder = Servicebuilder.Or(i => i.Service.Contains(si));
}
builder = builder.And(Servicebuilder);
}
if (!string.IsNullOrEmpty(products))
{
var productsbuilder = PredicateBuilder.False<TestResultItem>();
var productItems = products.Split('|');
foreach (var product in productItems)
{
var pd = Sitecore.ContentSearch.Utilities.IdHelper.NormalizeGuid(product, true);
productsbuilder = productsbuilder.Or(i => i.Category.Contains(pd));
}
builder = builder.And(productsbuilder);
}
In the above code Categorys, Service and products are pipe separated values which are coming from Sitecore Multi-list field.
Thanks again everyone for help!!

The query could not be run because the criteria for field '<?>' contained an invalid arithmetic expression

The query could not be run because the criteria for field '' contained an invalid arithmetic expression
Hi,
I faced some issue when i try to pass a value in Server Script and it keep come out with this error " doesnt support operator sbl-dat-00479". When i try to remove one of my value which is PRS Account No and it successfully come out. My value for PRS Account No = P-35971. Below is my server script.
function Print()
{
try
{
TheApplication().TraceOn("C:\\spool\\PRS SOA.txt", "Allocation", "All");
var Account = "";
var Year = "";
var Period = "";
var LPeriod = "";
var ContactID = "";
var Bookmark = "";
var ReportId = "";
var ReportName = "Customer Portal PRS Statement of Account";
//Active Field
this.BusComp().ActivateField("PRSAccountNo");
this.BusComp().ActivateField("Year2");
this.BusComp().ActivateField("Period2");
this.BusComp().ActivateField("LPeriod");
this.BusComp().ActivateField("CONTACT_ID");
//Get Account Row Id
Account = this.BusComp().GetFieldValue("PRSAccountNo");
Year = this.BusComp().GetFieldValue("Year2");
Period = this.BusComp().GetFieldValue("Period2");
LPeriod = this.BusComp().GetFieldValue("LPeriod");
ContactID = this.BusComp().GetFieldValue("CONTACT_ID");
//Construct Bookmark Query
Bookmark = "'cwa CustPortal PRS SOA Account'.Search = \"([PRS Account No] = '"+ Account +"') AND ([Year] = '"+ Year +"') AND ([Period] = '"+ LPeriod +"') AND ([CONTACT_ID] = '"+ ContactID +"')\"";
TheApplication().Trace("Bookmark: " + Bookmark);
//Retrieve Report Row Id
var boReport = TheApplication().GetBusObject("cwa CustPortal Report Administration");
var bcReport = boReport.GetBusComp("Report Standard Templates");
with(bcReport)
{
ActivateField("Report Name");
SetViewMode(AllView);
ClearToQuery();
SetSearchSpec("Report Name", ReportName);
ExecuteQuery(ForwardOnly);
if(FirstRecord())
{
ReportId = GetFieldValue("Id");
}
}
//Generate BIP Report
var GenReport = TheApplication().GetService("Workflow Process Manager");
var GenInput = TheApplication().NewPropertySet();
var GenOutput = TheApplication().NewPropertySet();
GenInput.SetProperty("ProcessName", "cwa CustPortal Generate BIP Report Workflow");
GenInput.SetProperty("Report Id", ReportId);
GenInput.SetProperty("Bookmark", Bookmark);
GenReport.InvokeMethod("RunProcess", GenInput, GenOutput);
var ErrMsg = GenOutput.GetProperty("Error Message");
if(ErrMsg == "")
{
//BIP Report successful generated, redirect to view report page
TheApplication().GotoView("cwa CustPortal PRS SOA Report View");
}
else
{
Popup(ErrMsg);
return(CancelOperation);
}
TheApplication().TraceOff();
}
catch(e)
{
Popup(e);
}
finally
{
}
}
Code looks ok, would be data issue or calc field logic error.
I think "Year2", "Period2" are Calculated fields & could be returning the special character ("/") leading to render the searchspec incorrectly.

Updating Location and ShipQty in Acumatica Shipment Lines

I'm having this weird problem in acumatica webservices, I'm updating existing Shipments in acumatica using webservices. My code is supposed to update the Location and ShippedQty but for no reason it updates all the items except the last one. It happens when the Shipment has multiple items. Please help me solve this problem, below is my code and an image of the Shipment screen with the last item not updated.
Thanks.
var commands = new List<Acumatica_LSOne_Integration.SO302000.Command>();
commands.Add(new SO302000.Value { Value = shipmentNbr, LinkedCommand = shipmentSchema.ShipmentSummary.ShipmentNbr });
commands.Add(new SO302000.Value { Value = shipmentType, LinkedCommand = shipmentSchema.ShipmentSummary.Type });
commands.Add(shipmentSchema.DocumentDetails.ShipmentNbr);
commands.Add(shipmentSchema.DocumentDetails.LineNbr);
commands.Add(shipmentSchema.DocumentDetails.InventoryID);
commands.Add(shipmentSchema.DocumentDetails.Warehouse);
commands.Add(shipmentSchema.DocumentDetails.Location);
commands.Add(shipmentSchema.DocumentDetails.OrderedQty);
var soLines = context.Submit(commands.ToArray());
List<Acumatica_LSOne_Integration.SO302000.Command> commandList = new List<Acumatica_LSOne_Integration.SO302000.Command>();
for (int index = 0; index < soLines.Length; index++)
{
string sShipNbr = soLines[index].DocumentDetails.ShipmentNbr.Value;
string sLineNbr = soLines[index].DocumentDetails.LineNbr.Value;
string sInventoryID = soLines[index].DocumentDetails.InventoryID.Value;
string sWarehouse = soLines[index].DocumentDetails.Warehouse.Value;
string sLocation = soLines[index].DocumentDetails.Location.Value;
string sOrderedQty = soLines[index].DocumentDetails.OrderedQty.Value;
commandList.Add(new SO302000.Key
{
ObjectName = shipmentSchema.DocumentDetails.ShipmentNbr.ObjectName,
FieldName = shipmentSchema.DocumentDetails.ShipmentNbr.FieldName,
Value = sShipNbr.Trim(), Commit = true
});
commandList.Add(new SO302000.Key
{
ObjectName = shipmentSchema.DocumentDetails.LineNbr.ObjectName,
FieldName = shipmentSchema.DocumentDetails.LineNbr.FieldName,
Value = sLineNbr.Trim(), Commit = true
});
commandList.Add(new SO302000.Value
{
Value = vLocation.Trim(),
LinkedCommand = shipmentSchema.DocumentDetails.Location
});
commandList.Add(new SO302000.Value { Value = sOrderedQty, LinkedCommand = shipmentSchema.DocumentDetails.ShippedQty,IgnoreError = true, Commit = true });
}
commandList.Add(shipmentSchema.Actions.ConfirmShipmentAction);
context.Submit(commandList.ToArray());
Sample Output:
I guessed that you have allowed negative quantity on your inventory, by default when an item has zero quantity on a particular warehouse the location will set as and a shipped quantity of zero and as I've seen you're code, check this line code
string sLocation = soLines[index].DocumentDetails.Location.Value;
if this soLine retreives a value as I guess this line is the cause why it won't update.
I've actually come up with a solution that works well using the Contract Based Web Services. Below is my sample code:
using (DefaultSoapClient soapClient = new DefaultSoapClient())
{
InitializeWebService(soapClient,sAUser,sAPass,vCompany,vBranchID);
Shipment shipmentToBeFound = new Shipment
{
Type = new StringSearch { Value = shipmentType },
ShipmentNbr = new StringSearch { Value = shipmentNbr },
};
Shipment shipment = (Shipment)soapClient.Get(shipmentToBeFound);
int iLineNbr = Int32.Parse(sLineNbr);
ShipmentDetail shipmentLine = shipment.Details.Single(
orderLineToBeUpdated =>
orderLineToBeUpdated.LineNbr.Value == iLineNbr);
shipmentLine.LocationID = new StringValue { Value = vLocation.Trim() };
shipmentLine.ShippedQty = new DecimalValue { Value = decimal.Parse(sOrderedQty) };
shipment = (Shipment)soapClient.Put(shipment);
soapClient.Logout();
}

Using GP Web Service: How do I delete a SalesOrderLine from a SalesOrder?

Can someone help me delete a SalesOrderLine from a SalesOrder?
I'm using the GP WS Native Endpoint
My code executes without an error.
However, after updating the SalesOrder, the line I removed still remains.
var salesDocumentKeyObject = new SalesDocumentKey {Id = salesDocumentKey, CompanyKey = this.CompanyKey};
var salesOrder = this.DynamicsGpClient.GetSalesOrderByKey(salesDocumentKeyObject, this.Context);
var newLines = salesOrder.Lines.Where(l => l.Key.LineSequenceNumber != lineItemSequence).ToArray();
salesOrder.Lines = newLines;
var salesOrderUpdatePolicy = this.DynamicsGpClient.GetPolicyByOperation("UpdateSalesOrder", this.Context);
this.DynamicsGpClient.UpdateSalesOrder(salesOrder, this.Context, salesOrderUpdatePolicy);
Thank you for any help,
Karl
Microsoft Dynamics GP Web Service has poor documentation and examples.
Do delete a sales order line, you retrieve the order, locate the line to delete and set the sales order line property, DeleteOnUpdate to true, and then save the order.
Updated code below:
var salesDocumentKeyObject = new SalesDocumentKey {Id = salesDocumentKey, CompanyKey = this.CompanyKey};
var salesOrder = this.DynamicsGpClient.GetSalesOrderByKey(salesDocumentKeyObject, this.Context);
var target= salesOrder.Lines.FirstOrDefault(l => l.Key.LineSequenceNumber == lineItemSequence);
if (target != null) {
target.DeleteOnUpdate = true;
}
var salesOrderUpdatePolicy = this.DynamicsGpClient.GetPolicyByOperation("UpdateSalesOrder", this.Context);
this.DynamicsGpClient.UpdateSalesOrder(salesOrder, this.Context, salesOrderUpdatePolicy);