Update list in Kotlin - list

So here is my Data Class
data class Bestellung (var id:Int = 0, var anzahl:Int = 1, var speise:String? = null)
my List
private var bestellungList = ArrayList<Bestellung>()
Trying to update the list if "speise" equals "s" but its not working without any error..
if (bestellungList.contains(Bestellung(speise = s))) {
var i = bestellungList.indexOf(Bestellung(speise = s))
bestellungList.set(i, Bestellung(anzahl = +1))

problem is contains
pls try this if you want to check first:
if(bestellungList.any{ it.speise == "s" }) {
// do add logic
} else {
// do something else
}

The problem is your contains part. Replace it like this
val index = bestellungList.indexOfFirst {
it.speise == s
}
if (index >= 0) {
bestellungList[index] = Bestellung(anzahl = +1)
}

if (bestellungList.any{ it.speise == "s" }) {
bestellungList.addAll(Bestellung(anzahl = +1))
} else {
// handle else statement also
}

Related

How to add dynamic values to field injections list with custom trigger to camunda properties panel?

I have two questions here
Is it possible to add dynamic lists values to field injection list input ?
Can I create a trigger for this so this can be initiated from any other input selection say a class selection will populate all fields
I was just looking into FieldInjection.js whether that can be extented for the same
Can someone please provide a hint or direction for this ?
Thanks.
For anyone interested in the answer, I was able to achieve the above goal by changing the set function of the Java Class select input as folllowing
few imports
var extensionElementsHelper = require('../../../../helper/ExtensionElementsHelper'),
elementHelper = require('../../../../helper/ElementHelper')
var CAMUNDA_FIELD_EXTENSION_ELEMENT = 'camunda:Field';
function getExtensionFields(bo) {
return bo && extensionElementsHelper.getExtensionElements(bo, CAMUNDA_FIELD_EXTENSION_ELEMENT) || [];
}
then changing the set function to create extension element and push the field values as :
set: function(element, values, node) {
var bo = getBusinessObject(element);
var type = getImplementationType(element);
var attr = getAttribute(type);
var prop = {}
var commands = [];
prop[attr] = values.delegate || '';
var extensionElements = getExtensionFields(bo);
//remove any extension elements existing before
extensionElements.forEach(function(ele){
commands.push(extensionElementsHelper.removeEntry(getBusinessObject(element), element, ele));
});
if(prop[attr] !== ""){
var extensionElements = elementHelper.createElement('bpmn:ExtensionElements', { values: [] }, bo, bpmnFactory);
commands.push(cmdHelper.updateBusinessObject(element, bo, { extensionElements: extensionElements }));
var arrProperties = ["private org.camunda.bpm.engine.delegate.Expression com.cfe.extensions.SampleJavaDelegate.varOne","private org.camunda.bpm.engine.delegate.Expression com.cfe.extensions.SampleJavaDelegate.varTwo"]
var newFieldElem = "";
arrProperties.forEach(function(prop){
var eachProp = {
name:"",
string:"",
expression:""
}
var type = prop.split(" ")[1].split(".").reverse()[0];
var val = prop.split(" ")[2].split(".").reverse()[0];
eachProp.name = val;
if( type == "String"){
eachProp.string = "${" + val +" }"
}else if( type == "Expression"){
eachProp.expression = "${" + val +" }"
}
newFieldElem = elementHelper.createElement(CAMUNDA_FIELD_EXTENSION_ELEMENT, eachProp, extensionElements, bpmnFactory);
commands.push(cmdHelper.addElementsTolist(element, extensionElements, 'values', [ newFieldElem ]));
});
}
commands.push(cmdHelper.updateBusinessObject(element, bo, prop));
return commands;
}
Cheers !.

How to edit a list of object c# linq to xml

<Team Side="Home" TeamRef="ref123">
<Goal PlayerRef="p1111" Time="10" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p4444" Time="11" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p7777 Time="13" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p7777 Time="17" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
</Team>
public void GetScorer(string side, string OCompetition, string OSeason, string OGameId)
{
try
{
var xDoc = XDocument.Load(test);
var query = from q in xDoc.Descendants("Team")
where (string)q.Attribute("Side") == side
from d in q.Elements("Goal")
select new
{
TeamRef = q.Attribute("TeamRef").Value,
PlayerRef = d.Attribute("PlayerRef").Value,
Time = d.Attribute("Time").Value
};
var count = 0;
foreach (var qq in query)
{
if (side == "Home")
{
if (HomeSlateScorerList[count].PlayerRef != qq.PlayerRef)
{
HomeSlateScorerList.Add(new Scorer() { PlayerRef = qq.PlayerRef, Time = qq.Time, LastName = GetPlayerNameSlate(qq.PlayerRef, OSeason, OCompetition, OGameId) });
}
else
{
HomeSlateScorerList[count].Time = HomeSlateScorerList[count].Time + "' ";
}
}
if (side == "Away")
{
AwaySlateScorerList.Add(new Scorer() { PlayerRef = qq.PlayerRef, Time = qq.Time, LastName = GetPlayerNameSlate(qq.PlayerRef, OCompetition, OSeason, OGameId) });
}
count++;
}
}
catch (Exception)
{
// ignored
}
}
I would like to edit a player in a list of players
HomeSlateScorerList = new List<Scorer>();
AwaySlateScorerList = new List<Scorer>();
what I would like to achieve is for e.g. there are two players with the ref of "p7777" so in the list of object I would like to have one player with the playerref of "p7777" so if the player exist the format will be
playerref = "p7777"
Time = 13' 17'
or if one player its
Time = 13'
or if another goal is added to the xml its
Time = 13' 17' 25'
HomeSlateScorerList = HomeSlateScorerList
.GroupBy(s => s.PlayerRef)
.Select(g => new Scorer { PlayerRef = g.Key, Time = string.Join(", ", g.Select(v => v.Time)) })
.ToList();
Thanks to: #SergeyS SergeyS

How to sort the selected items in a Sitecore Treelist?

Is there a way to always have the selected items in a Sitecore Treelist sorted alphabetically?
No, but you could look in to creating your own 'sorted treelist'. Someone asked a different question earlier today but it has basically the same answer:
Sitecore Tree list datasource - VersionExist
Sitecore lets you create custom field types. They can be based on existing ones, but with some added tweaks.
As mentioned in the answers to the other question, here are 2 articles which are good places to start:
Creating a Composite Custom Field
Apply Dynamic TreeList Source Parameters with the Sitecore ASP.NET CMS
Here's my implementation, which although long, is mostly copy-and-pasted from the decompiled Treelist code. I've highlighted which bits which are new in the Value property and the Add method:
namespace CustomFieldTypes
{
public class Treelist : Sitecore.Shell.Applications.ContentEditor.TreeList
{
public override string Value
{
get
{
// ---------- New code here -----------
var ids = base.Value.Split('|');
var db = Sitecore.Configuration.Factory.GetDatabase("master");
var items = ids.Select(id => db.GetItem(id)).Where(item => item != null);
var orderedItems = items.OrderBy(item => item.Name);
var orderedIds = orderedItems.Select(item => item.ID.ToString());
return String.Join("|", orderedIds);
// ---------------------------------------
}
set
{
base.Value = value;
}
}
protected void Add()
{
if (this.Disabled)
return;
string viewStateString = this.GetViewStateString("ID");
TreeviewEx treeviewEx = this.FindControl(viewStateString + "_all") as TreeviewEx;
Assert.IsNotNull((object) treeviewEx, typeof (DataTreeview));
Listbox listbox = this.FindControl(viewStateString + "_selected") as Listbox;
Assert.IsNotNull((object) listbox, typeof (Listbox));
Item selectionItem = treeviewEx.GetSelectionItem();
if (selectionItem == null)
{
SheerResponse.Alert("Select an item in the Content Tree.", new string[0]);
}
else
{
if (this.HasExcludeTemplateForSelection(selectionItem))
return;
if (this.IsDeniedMultipleSelection(selectionItem, listbox))
{
SheerResponse.Alert("You cannot select the same item twice.", new string[0]);
}
else
{
if (!this.HasIncludeTemplateForSelection(selectionItem))
return;
SheerResponse.Eval("scForm.browser.getControl('" + viewStateString + "_selected').selectedIndex=-1");
ListItem listItem = new ListItem();
listItem.ID = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("L");
// ----- New Code Here -----------------------
bool listItemAdded = false;
for (int i = 0; i < listbox.Controls.Count; i++ )
{
ListItem control = (ListItem)listbox.Controls[i];
if (control == null)
return;
if (String.Compare(GetHeaderValue(selectionItem), control.Header) < 0)
{
listbox.Controls.AddAt(i, listItem);
listItemAdded = true;
break;
}
}
if (!listItemAdded)
{
Sitecore.Context.ClientPage.AddControl((System.Web.UI.Control)listbox, (System.Web.UI.Control)listItem);
}
// ------------------------------------------
listItem.Header = this.GetHeaderValue(selectionItem);
listItem.Value = listItem.ID + (object) "|" + (string) (object) selectionItem.ID.ToString();
SheerResponse.Refresh((Sitecore.Web.UI.HtmlControls.Control) listbox);
SetModified();
}
}
}
protected static void SetModified()
{
Sitecore.Context.ClientPage.Modified = true;
}
private bool HasIncludeTemplateForSelection(Item item)
{
Assert.ArgumentNotNull((object)item, "item");
if (this.IncludeTemplatesForSelection.Length == 0)
return true;
else
return HasItemTemplate(item, this.IncludeTemplatesForSelection);
}
private bool HasExcludeTemplateForSelection(Item item)
{
if (item == null)
return true;
else
return HasItemTemplate(item, this.ExcludeTemplatesForSelection);
}
private bool IsDeniedMultipleSelection(Item item, Listbox listbox)
{
Assert.ArgumentNotNull((object)listbox, "listbox");
if (item == null)
return true;
if (this.AllowMultipleSelection)
return false;
foreach (Sitecore.Web.UI.HtmlControls.Control control in listbox.Controls)
{
string[] strArray = control.Value.Split(new char[1]
{
'|'
});
if (strArray.Length >= 2 && strArray[1] == item.ID.ToString())
return true;
}
return false;
}
private static bool HasItemTemplate(Item item, string templateList)
{
Assert.ArgumentNotNull((object)templateList, "templateList");
if (item == null || templateList.Length == 0)
return false;
string[] strArray = templateList.Split(new char[1]
{
','
});
ArrayList arrayList = new ArrayList(strArray.Length);
for (int index = 0; index < strArray.Length; ++index)
arrayList.Add((object)strArray[index].Trim().ToLowerInvariant());
return arrayList.Contains((object)item.TemplateName.Trim().ToLowerInvariant());
}
}
}
When this is compiled and in your application you need to go to /sitecore/system/Field types/List Types/Treelist in the core database. In there, you need to fill in the Assembly and Class fields, and clear out the Control fields.
You could create a custom field and sort the items in the selected list using generics, then save the guids back to the field. I covered this in a recent blog post. There isn't that much coding involved.

How to unit test unformatted method in mvc?

I have to unit test one of the very big and unformatted method in ASP.NET MVC 4.0.
Below is the code of action method :-
public ActionResult GetDetails(string ProdName, int ProdArea, int ProdAreaId= 0)
{
if (ProdAreaId == 0 && ProdArea == 1 && System.Web.HttpContext.Current.Session["ResponseProdAreaId"] != null)
{
ProdAreaId = (int)System.Web.HttpContext.Current.Session["ResponseProdAreaId"];
}
if (string.IsNullOrEmpty(ProdName))
{
if (System.Web.HttpContext.Current.Session["ProdName"] == null)
{
ProdName = Guid.NewGuid().ToString();
System.Web.HttpContext.Current.Session["ProdName"] = ProdName;
}
else
{
ProdName = System.Web.HttpContext.Current.Session["ProdName"].ToString();
}
}
else
{
ProdName = ProdName.Replace("___", " ");
}
List<StateDetail> stateList = ProductService.GetAllStates().Where(n => n.FKCountryID == (int)Countries.UnitedStates).ToList();
ProductAddressViewModel model = new ProductAddressViewModel
{
ProdArea = ProdArea,
FKProductID = CurrentProductId
};
model.States = stateList != null ? new SelectList(stateList, "StateID", "StateCode") : null;
if (System.Web.HttpContext.Current.Session[“ProdAddresses”] != null && ProdAreaId == 0 && ProdArea == 1)
{
List<ProductAddressDto> lstprodaddresses = (List<ProductAddressDto>)System.Web.HttpContext.Current.Session[“ProdAddresses”];
if (lstprodaddresses.Count > 0)
{
AddressDto addrDto = lstprodaddresses.First().Address;
//save address in DB
model.Address1 = addrDto.Address1;
model.Address2 = addrDto.Address2;
model.ProdArea = 1;
model.City = addrDto.City;
model.IsDefault = true;
model.ProdName = model.ProdName;
model.SelectedAddressTypeID = (int)AddressType.Street;
model.ZIPCode = addrDto.ZIPCode;
model.SelectedStateId = addrDto.FKStateID;
model.AddressTypes = GetAddressTypes();
}
}
else if (model.FKProductID > 0)
{
ToolDto tool = ToolService.GetToolDetails(model.FKProductID);
if (ProdAreaId > 0)
{
model.AddressTypes = GetAddressTypes();
ProductAddressDto prodaddr = tool.ToolAddresses.First(n => n.Tool_AddressID == ProdAreaId);
model.Address1 = prodaddr.Address.Address1;
model.Address2 = prodaddr.Address.Address2;
model.City = prodaddr.Address.City;
model.SelectedStateId = prodaddr.Address.FKStateID;
model.ZIPCode = prodaddr.Address.ZIPCode;
model.SelectedAddressTypeID = prodaddr.Address.FKAddressTypeID;
model.IsDefault = prodaddr.IsDefault;
model.FKAddressID = prodaddr.FKAddressID;
model.Tool_AddressID = prodaddr.Tool_AddressID;
model.FKProductID = prodaddr.FKProductID;
model.AddressTypes = GetAddressTypes();
}
else
{
//address types
List<int> excludeAddrTypes = new List<int>();
foreach (ProductAddressDto prodadrdto in tool.ToolAddresses)
{
if (prodadrdto.Tool_AddressID != ProdAreaId)
{
excludeAddrTypes.Add(prodadrdto.Address.FKAddressTypeID);
}
}
if (System.Web.HttpContext.Current.Session[“ProdAddresses”] != null)
{
excludeAddrTypes.Add((int)AddressType.Street);
}
var addrtypes = from AddressType e in Enum.GetValues(typeof(AddressType))
where !excludeAddrTypes.Contains((int)e)
select new { Id = (int)e, Name = e.ToString() };
model.AddressTypes = addrtypes.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
if (tool.ToolAddresses.Count == 0)
{
model.IsDefault = (ProdArea == 1);
}
}
}
else
{
//filter out address types if responsed tool is there
if (System.Web.HttpContext.Current.Session[“ProdAddresses”] != null)
{
List<int> excludeAddrTypes = new List<int>();
excludeAddrTypes.Add((int)AddressType.Street);
var addrtypes = from AddressType e in Enum.GetValues(typeof(AddressType))
where !excludeAddrTypes.Contains((int)e)
select new { Id = (int)e, Name = e.ToString() };
model.AddressTypes = addrtypes.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
}
else
{
model.AddressTypes = GetAddressTypes();
}
model.IsDefault = (ProdArea == 1);
}
model.ProdName = ProdName;
return PartialView("_AddUpdateAddress", model);
}
May be the method is not in correct format.But i have to do it's unit testing.I have do that in several different ways.But i am not sure about its correctness.
I want to know that how should we do unit test for such a big and unformatted method like this.
Can anyone help me out on this ?
Below is the piece of code of my unit testing method :-
[TestMethod]
public void GetDetailsTest_NotEmpty()
{
var ProdName = random.ToString();
var ProdArea = random.Next();
var ProdAreaId = 0;
var _toolServiceMock = new Mock<IToolService>();
var _lookupServiceMock = new Mock<ILookupService>();
var stateList = new List<StateDto> {
new StateDto() { StateID = random.Next(), StateCode = Guid.NewGuid().ToString(), Description = random.ToString(), FKCountryID = 1 },
new StateDto() { StateID = random.Next(), StateCode = Guid.NewGuid().ToString(), Description = random.ToString(), FKCountryID = random.Next() },
};
_lookupServiceMock.Setup(s => s.GetAllStates()).Returns(stateList); // .Returns(stateList);
//Arrange
CustomerDto cust = _toolService.LookupCustomers("", "").FirstOrDefault();
if (cust != null)
{
ToolDto tool = _toolService.GetToolDetails(cust.Tool.toolId);
if (tool.ToolAddresses.Count > 0 && tool.ToolAddresses.First().Address != null)
{
HttpContext.Current.Session["FKToolID"] = cust.FKToolID;
var controller = new ToolController(_toolServiceMock.Object);
PartialViewResult result = controller.SelectAddress(cust.Tool.Name, 1, tool.ToolAddresses.First().Tool_AddressID) as PartialViewResult;
var viewmodel = (ToolAddressViewModel)((ViewResultBase)(result)).Model;
if (viewmodel != null)
{
//Act
Assert.AreEqual(tool.ToolAddresses.First().Address.Address1, viewmodel.Address1);
Assert.AreEqual("_AddUpdateAddress", result.ViewName);
Assert.IsInstanceOfType(viewmodel, typeof(ToolAddressViewModel));
}
//Act
_lookupServiceMock.VerifyAll();
}
}
}
First of all, your method is a way too complicated and too long.
Make your actions short and with one responsability to respect SOLID principle (http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)).
It will make your methods easier to test.
To help you with your problem, you can do something quick with your code :
Split your actions in internal virtual methods with one concern each (internal to be testable in you unit test project, virtual to be able to mock them).
Put the [assembly: InternalsVisibleTo("YourTestAssembly")] on your controller
In your unit test project, you will be able to test any of your internal methods separately.
Finally, to test your action, use a mocking framework (RhinoMock, Moq) to mock all your internal virtual methods and test the logic of your action (proxies generated by mocking framework will let you mock virtual methods).
It's the easiest way you can test your logic without breaking the existing application.
The inconvenient is that your logic is in internal methods wich let the whole assembly able to use it.

How to Retrieve News Feed using Facebook Graph API.?

I am working on WPF application and I want to retrieve News Feed using facebook Graph API so how I can access it also convert into serialize.!
Thank you.
You're gonna use Facebook.dll u can download it using Package Manager in Visual studio if u are using C# for example
NuGet Package here..
and code may look like this
public List<string> Facebook(string query)
{
// Facebook.FacebookAPI api = new FacebookAPI();
List<string> list = new List<string>();
string[] arr = new string[5];
string result = null;
FacebookAPI api = new FacebookAPI(token);
// query is ur search criteria
JSONObject q = api.Get("https://graph.facebook.com/search?q="+query+"&type=post");
foreach (JSONObject item in q.Dictionary["data"].Array)
{
if (item.IsDictionary)
{
foreach (KeyValuePair<String,JSONObject> jso in item.Dictionary)
{
if (jso.Key == "message"/* || jso.Key == "name" || jso.Key == "description" || jso.Key == "link"*/)
{
for (int i = 0; i < 5; i++)
{
arr[i] = jso.Value.String;
}
list.Add (jso.Value.String);
}
else if (jso.Key == "likes")
{
foreach (JSONObject like in jso.Value.Dictionary["data"].Array)
{
foreach (KeyValuePair<String, JSONObject> lik in like.Dictionary)
{
if (lik.Key == "name")
{
result += lik.Value.String;
}
else if (lik.Key == "id")
{
result += lik.Value.String;
}
}
}
foreach (KeyValuePair<String, JSONObject> count in jso.Value.Dictionary)
{
if (count.Key == "count")
{
result += count.Value.String;
}
}
}
else if (jso.Key == "from")
{
foreach (KeyValuePair<String, JSONObject> froms in jso.Value.Dictionary)
{
if (froms.Key == "name")
{
result += froms.Value.String;
}
}
}
}
}
/*
else if (item.IsArray)
{
foreach (JSONObject j in item.Dictionary["data"].Array)
{
if (j.IsDictionary)
{
foreach (KeyValuePair<String,JSONObject> x in j.Dictionary)
{
result += (x.Key + " --- "+x.Value.String);
}
}
}
}
*/
}
return list;
}
you can of course change post and query to whatever you want to search in Facebook Graph API
and there is another way to do that using FQL and its really easy
hope that will be helpful.