I am getting an error of 1084 in flash builder project. I want to share the file which I am getting an error.
package com.bykd.g4m.lobby.data
{
import com.bykd.xcom.data.DataObject;
import flash.utils.Dictionary;
import com.bykd.xcom.data.Room;
import com.bykd.xcom.data.User;
import com.bykd.g4m.lobby.GameManager;
public class GameInfo extends DataObject
{
public static const INIT_STATUS:Number = 1;
public static const BET_OPTION:String = "BET";
public static const EMPTY_STATUS:Number = 0;
public static const STATUS_ELEMENT:String = "STATUS";
public static const DRAW_OPTION:String = "DRAW";
public static const WINROUNDS_OPTION:String = "WINROUNDS";
public static const CREATE_STATUS:Number = 2;
public static const GAME_ELEMENT:String = "GAME";
public static const OPTIONS_ELEMENT:String = "OPTIONS";
public static const OBJECT_ELEMENT:String = "GAMEINFO";
public static const TIME_OPTION:String = "TIME";
public static const CREATOR_ELEMENT:String = "CREATOR";
public static const READY_STATUS:Number = 3;
public static const SCORE_OPTION:String = "SCORE";
public static const OPPONENT_ELEMENT:String = "OPPONENT";
private var __id:uint;
public var gameStatus:Number;
public var gameOptions:Dictionary;
public var gameRoom:Room;
public var gameOpponent:User;
public var gameCreator:User;
public var gameJoined:Boolean;
public function GameInfo(id:uint = 0, status:Number = 0, creator:User = null)
{
super();
__id = id;
gameStatus = status;
gameCreator = creator;
gameOptions = new Dictionary();
gameJoined = false;
}
public static function parseHeader(xml:XML) : Object
{
var nodeName:String = xml.localName();
var nodeParts:Array = nodeName.split("_",2);
return {
"element":nodeParts[0],
"id":parseInt(nodeParts[1])
};
}
override public function toXML() : XML
{
return new XML("<" + (OBJECT_ELEMENT + "_" + ID) + "/>");
}
override public function toXMLData(full:Boolean = true) : XML
{
var dataXML:XML = null;
var key:* = null;
var xml:XML = toXML();
if(full)
{
if(!isNaN(gameStatus))
{
dataXML = new XML("<" + STATUS_ELEMENT + "/>");
dataXML.appendChild(gameStatus.toString());
xml.appendChild(dataXML);
}
if(gameCreator != null)
{
dataXML = new XML("<" + CREATOR_ELEMENT + "/>");
dataXML.appendChild(gameCreator.toXML());
xml.appendChild(dataXML);
}
if(gameOptions != null)
{
dataXML = new XML("<" + OPTIONS_ELEMENT + "/>");
for(key in gameOptions)
{
**dataXML.appendChild(new XML("<" + key + ">" + ({gameOptions[key]}) + "</" + key + ">"));**
}
xml.appendChild(dataXML);
}
if(gameOpponent != null)
{
dataXML = new XML("<" + OPPONENT_ELEMENT + "/>");
dataXML.appendChild(gameOpponent.toXML());
xml.appendChild(dataXML);
}
if(gameRoom != null)
{
dataXML = new XML("<" + GAME_ELEMENT + "/>");
dataXML.appendChild(gameRoom.toXML());
xml.appendChild(dataXML);
}
}
return xml;
}
public function get ID() : uint
{
return __id;
}
override public function fromXML(xml:XML) : void
{
var dataXML:XML = null;
var userXML:XML = null;
var roomXML:XML = null;
var gameManager:GameManager = null;
var node:XML = null;
var key:String = null;
var header:Object = parseHeader(xml);
if(header.element == OBJECT_ELEMENT)
{
__id = header.id;
gameManager = GameManager.getInstance();
dataXML = xml.elements(STATUS_ELEMENT)[0];
if(dataXML != null)
{
gameStatus = Number(dataXML.toString());
}
dataXML = xml.elements(CREATOR_ELEMENT)[0];
if(dataXML != null)
{
userXML = dataXML.elements(User.OBJECT_ELEMENT)[0];
if(userXML != null && User.checkID(userXML))
{
gameCreator = gameManager.userService.getUserEntity(User.parseID(userXML));
}
}
dataXML = xml.elements(OPTIONS_ELEMENT)[0];
if(dataXML != null)
{
gameOptions = new Dictionary();
for each(node in dataXML.elements())
{
key = node.localName();
gameOptions[key] = node.toString();
}
}
dataXML = xml.elements(OPPONENT_ELEMENT)[0];
if(dataXML != null && dataXML.hasOwnProperty(User.OBJECT_ELEMENT))
{
userXML = dataXML.elements(User.OBJECT_ELEMENT)[0];
if(userXML != null && User.checkID(userXML))
{
gameOpponent = gameManager.userService.getUserEntity(User.parseID(userXML));
}
}
dataXML = xml.elements(GAME_ELEMENT)[0];
if(dataXML != null && dataXML.hasOwnProperty(Room.OBJECT_ELEMENT))
{
roomXML = dataXML.elements(Room.OBJECT_ELEMENT)[0];
if(roomXML != null && Room.checkID(roomXML))
{
gameRoom = gameManager.roomService.getRoomEntity(Room.parseID(roomXML));
}
}
}
}
}
}
The problem is in this line according to the flash builder:
dataXML.appendChild(new XML("<" + key + ">" + ({gameOptions[key]}) + "</" + key + ">"));
the program says that multiple markers at this line.
it is a syntax error . thanks in advance.
Related
I'm looking to add records to an Umbraco v8 form. I know I need the form guid. Is this how I'd do it? Something like this?
public void PostFormData()
{
Guid FormGuid = new Guid("8494a8f0-94da-490e-bd61-7e658c226142");
var form = _formService.Get(FormGuid);
//place for field data into fieldDic
var fieldDic = new Dictionary<Guid, RecordField>();
var firstName = form.AllFields.First(f => f.Alias == "firstName");
var firstNameRecord = new RecordField(firstName);
firstNameRecord.Values = new List<object>() { "Mad Max" };
fieldDic.Add(firstName.Id, firstNameRecord);
var record = new Record()
{
Created = DateTime.Now,
Form = form.Id,
RecordFields = fieldDic,
State = FormState.Submitted,
};
record.RecordData = record.GenerateRecordDataAsJson();
_recordStorage.InsertRecord(record, form);
}
Here's how I do it. Note, I'm hard-coding the Record.UmbracoPageId to -1 while you might want to actually pass in the correct page ID.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Forms.Core.Data.Storage;
using Umbraco.Forms.Core.Models;
using Umbraco.Forms.Core.Persistence.Dtos;
using Umbraco.Forms.Core.Services;
namespace myProject.Services
{
public class FormServiceComposer : IUserComposer
{
public void Compose(Composition composition)
{
composition.Register<IFormService, FormService>(Lifetime.Request);
}
}
public interface IFormService
{
void InsertFormData(Guid formGuid, object formModel, string ipAddress);
}
public class FormService : IFormService
{
private readonly ILogger _logger;
private readonly Umbraco.Forms.Core.Services.IFormService _formService;
private readonly IRecordStorage _recordStorage;
private readonly IRecordFieldStorage _recordFieldStorage;
private readonly IWorkflowService _workflowService;
public FormService(ILogger logger, Umbraco.Forms.Core.Services.IFormService formService, IRecordStorage recordStorage, IRecordFieldStorage recordFieldStorage, IWorkflowService workflowService)
{
_logger = logger;
_formService = formService;
_recordStorage = recordStorage;
_recordFieldStorage = recordFieldStorage;
_workflowService = workflowService;
}
#region IFormService
public void InsertFormData(Guid formGuid, object formModel, string ipAddress)
{
try
{
Form form = _formService.GetForm(formGuid);
Record record = new Record();
foreach (Field field in form.AllFields)
{
string caption = CleanCaption(field.Caption);
if (formModel.GetType().GetProperty(caption) == null) continue;
var propertyValue = formModel.GetType().GetProperty(caption).GetValue(formModel, null);
if (propertyValue != null)
{
List<object> values = ExtractValues(propertyValue);
RecordField recordField = new RecordField
{
Alias = field.Alias,
FieldId = field.Id,
Field = field,
Key = Guid.NewGuid(),
Record = record.Id,
Values = values
};
_recordFieldStorage.InsertRecordField(recordField);
record.RecordFields.Add(recordField.Key, recordField);
}
}
record.Form = formGuid;
record.IP = ipAddress;
record.UmbracoPageId = -1;
record.State = Umbraco.Forms.Core.Enums.FormState.Approved;
record.RecordData = record.GenerateRecordDataAsJson();
_recordStorage.InsertRecord(record, form);
_recordStorage.DisposeIfDisposable();
}
catch (Exception ex)
{
_logger.Error<FormService>(ex, "Failed inserting Umbraco Forms data for {formGuid}");
}
}
#endregion IFormService
#region Private
private string CleanCaption(string caption)
{
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
return rgx.Replace(caption.Trim().Replace(" ", ""), "");
}
private List<object> ExtractValues(object propertyValue)
{
List<object> result = new List<object>();
if (propertyValue is string == false && propertyValue.GetType().GetGenericTypeDefinition() == typeof(List<>))
{
IEnumerable<object> _propertyValue = (IEnumerable<object>)propertyValue;
if (_propertyValue.Any())
{
if (_propertyValue.First().GetType().GetProperties().Count() > 1)
{
JArray _properties = JArray.Parse(JsonConvert.SerializeObject(propertyValue));
foreach (JToken item in _properties)
{
string _value = string.Empty;
foreach (var _property in _propertyValue.First().GetType().GetProperties())
{
string _key = _property.Name;
_value = _value + (_value == "" ? "" : " - ") + item[_key].ToString();
}
result.Add(_value);
}
}
else
{
string _key = _propertyValue.First().GetType().GetProperties().First().Name;
JArray _properties = JArray.Parse(JsonConvert.SerializeObject(propertyValue));
foreach (JToken item in _properties)
{
result.Add(item[_key].ToString());
}
}
}
}
else
{
result.Add(propertyValue);
}
return result;
}
#endregion Private
}
}
how to send notification to client in kendo mvc ajax bound ,
i do not know if this is good way ..
of course you can add ModelState.AddModelError("notification","….msg.")
and …. But it tell to datasource ajax action failed.. So..
Addclass:
public class AjaxErrorMsg
{
public AjaxErrorMsg()
{
CssClass = "gray";
AutoHide = false;
AutoHideDelay = 200;
Kind = "error";
Title = "error";
}
public string Msg { get; set; }
public string Kind { get; set; }
public Boolean AutoHide { get; set; }
public Int32 AutoHideDelay { get; set; }
public string CssClass { get; set; }
public string Title { get; set; }
}
In controller
public void StoreMessageInCookie(string msg, Boolean isError = false, string msgDivClass = "", string preMessage = "", string msgTitle = "")
{
StoreMessageInCookie(new Exception(msg), isError, msgDivClass, preMessage, msgTitle);
}
public void StoreMessageInCookie(Exception ee, Boolean isError = false, string msgDivClass = "", string preMessage = "", string msgTitle = "")
{
List<AjaxErrorMsg> rs;
var js = new JavaScriptSerializer();
if (this.Response.Cookies[Common1.MsgCookie].HasKeys )
{
try
{
rs = js.Deserialize<List<AjaxErrorMsg>>(this.Response.Cookies[Common1.MsgCookie].Value);
}
catch
{
rs = new List<AjaxErrorMsg>();
}
}
else
{
rs = new List<AjaxErrorMsg>();
}
var msg0 = new AjaxErrorMsg();
if (isError)
{
msgDivClass = msgDivClass == "" ? "DivAlarmStyle6 fontMitra" : msgDivClass;
msg0.Kind = "error";
msg0.AutoHide = false;
msg0.Title = "Error";
}
else
{
msg0.Kind = "alert";
msg0.AutoHide = true;
msg0.Title = "Warning";
}
msg0.Title = msgTitle == "" ? msg0.Title : msgTitle;
msg0.Msg = preMessage + cm2.FilterMessageText(ee, IsAdminUser);
if (msgDivClass.Trim() != "")
msg0.Msg = Common1.WrapTextInDivWithClass(msg0.Msg, msgDivClass);
rs.Add(msg0);
this.Response.Cookies.Add(new HttpCookie(Common1.MsgCookie, js.Serialize(rs)));
}
cm2.FilterMessageText is function to remove database object name from error message string ..also include any inner exception message
Then when you what to send message use command
StoreMessageInCookie("Message 1 2 ! ");
And in your MainProject.js
Add all of code below
function createCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
}
function ReadAnShowCookieForDeliverMessages() {
try {
var listMsg = readCookie("CookieForDeliverMessages")
if (!!listMsg) {
eraseCookie("CookieForDeliverMessages");
ShowAndLogMessageListOfAjaxError($.parseJSON(listMsg));
}
} catch (ee) {
alert(" error in ReadAnShowCookieForDeliverMessages")
}
}
function ShowAndLogMessageListOfAjaxError(ListOfAjaxError) {
if (ListOfAjaxError == undefined)
return;
ListOfAjaxError.forEach(function (AjaxError) {
ShowAndLogMessageByAjaxErrorClass(AjaxError)
})
}
function ShowAndLogMessageByAjaxErrorClass(AjaxError) {
if ((AjaxError != undefined) && (AjaxError.Msg != "")) {
// I used freeow => https://github.com/pjdietz/Freeow
$("#freeow").freeow(AjaxError.Title, AjaxError.Msg, { classes: [AjaxError.CssClass, AjaxError.Kind], autoHide: AjaxError.AutoHide, autoHideDelay: AjaxError.AutoHideDelay });
// LogMsg(AjaxError.Msg, AjaxError.Title); function to log message on client
}
}
$(function () {
MyAjaxSetting();
ReadAnShowCookieForDeliverMessages();
}
function MyAjaxSetting() {
$(document).ajaxComplete(function (o) {
ReadAnShowCookieForDeliverMessages()
});
}
I would like to know can I create a new linked task when I create a workitem.
Can anyone give a tip of how to do this?
I've gone through some old code that I previously used for this scenario. The following code creates a linked task whenever a new bug is set to approved.
The code filters to a specific Team Project and uses a specific account to connect. You need to enter these before the plugin will work. You can then modify this code to create the tasks you want.
For a general introduction to server plugins and how to turn the code below into a functioning plugin see Extending Team Foundation
using Microsoft.TeamFoundation.Framework.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.WorkItemTracking.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.Client;
using System.Net;
using System.Collections;
namespace TfsExtension.CreateTaskForBug
{
public class CreateTaskForBugEventHandler : ISubscriber
{
const string projectName = "<Enter your project name here>";
public string Name
{
get
{
return "CreateTaskForBugEventHandler";
}
}
public SubscriberPriority Priority
{
get
{
return SubscriberPriority.Normal;
}
}
public EventNotificationStatus ProcessEvent(
TeamFoundationRequestContext requestContext,
NotificationType notificationType,
object notificationEventArgs,
out int statusCode,
out string statusMessage,
out ExceptionPropertyCollection properties)
{
statusCode = 0;
properties = null;
statusMessage = String.Empty;
try
{
ProcessNotification(notificationType, notificationEventArgs, requestContext);
}
catch (Exception exception)
{
TeamFoundationApplicationCore.LogException("Error processing event", exception);
}
return EventNotificationStatus.ActionPermitted;
}
private static void ProcessNotification(NotificationType notificationType, object notificationEventArgs, TeamFoundationRequestContext requestContext)
{
if (notificationType == NotificationType.Notification && notificationEventArgs is WorkItemChangedEvent)
{
var ev = notificationEventArgs as WorkItemChangedEvent;
if (ev.PortfolioProject == projectName)
{
string workItemType = (from field in ev.CoreFields.StringFields
where field.Name == "Work Item Type"
select field.NewValue).Single();
if (workItemType == "Bug")
{
ProcessBug(ev, requestContext);
}
}
}
}
private static void ProcessBug(WorkItemChangedEvent ev, TeamFoundationRequestContext requestContext)
{
var stateChange = (from field in ev.ChangedFields.StringFields
where field.Name == "State" && field.NewValue == "Approved"
select field).SingleOrDefault();
if (stateChange != null)
{
AddChildTaskToBug(ev, requestContext);
}
}
private static void AddChildTaskToBug(WorkItemChangedEvent ev, TeamFoundationRequestContext requestContext)
{
WorkItemStore wiStore = GetWorkItemStore(requestContext);
WorkItem witem = wiStore.GetWorkItem(ev.CoreFields.IntegerFields[0].NewValue);
Project teamProject = witem.Project;
int bugID = witem.Id;
string bugTitle = witem.Fields["System.Title"].Value.ToString();
string bugAssignedTo = witem.Fields["System.AssignedTo"].Value.ToString();
string bugAreaPath = witem.Fields["System.AreaPath"].Value.ToString();
string bugIterationPath = witem.Fields["System.IterationPath"].Value.ToString();
string bugChangedBy = witem.Fields["System.ChangedBy"].OriginalValue.ToString();
string bugTeamProject = witem.Project.Name;
string childTaskTitle = "Resolve bug " + bugID + " - " + bugTitle;
if (CreateResolutionTask(wiStore, bugID, childTaskTitle))
{
witem = CreateWorkItem(wiStore, teamProject, bugID, bugTitle, bugAssignedTo, bugAreaPath, bugIterationPath);
if (IsValid(witem))
{
witem.Save();
LinkParentAndChild(wiStore, witem, bugID);
}
}
}
private static bool IsValid(WorkItem witem)
{
ArrayList validationErrors = witem.Validate();
return validationErrors.Count == 0;
}
private static void LinkParentAndChild(WorkItemStore wiStore, WorkItem witem, int bugID)
{
var linkType = wiStore.WorkItemLinkTypes[CoreLinkTypeReferenceNames.Hierarchy];
var parentWorkItem = wiStore.GetWorkItem(bugID);
int taskID = witem.Id;
var childWorkItem = wiStore.GetWorkItem(taskID);
parentWorkItem.Links.Add(new WorkItemLink(linkType.ForwardEnd, childWorkItem.Id));
parentWorkItem.Save();
}
private static WorkItem CreateWorkItem(WorkItemStore wiStore, Project teamProject, int bugID, string bugTitle, string bugAssignedTo, string bugAreaPath, string bugIterationPath)
{
WorkItemTypeCollection workItemTypes = wiStore.Projects[teamProject.Name].WorkItemTypes;
WorkItemType wiType = workItemTypes["Task"];
WorkItem witem = new WorkItem(wiType);
witem.Fields["System.Title"].Value = "Resolve bug " + bugID + " - " + bugTitle;
witem.Fields["System.AssignedTo"].Value = bugAssignedTo;
witem.Fields["System.AreaPath"].Value = bugAreaPath;
witem.Fields["System.IterationPath"].Value = bugIterationPath;
witem.Fields["Microsoft.VSTS.Common.Activity"].Value = "Bug Resolution";
return witem;
}
private static bool CreateResolutionTask(WorkItemStore wiStore, int bugID, string childTaskTitle)
{
WorkItem parentBug = wiStore.GetWorkItem(bugID);
WorkItemLinkCollection links = parentBug.WorkItemLinks;
foreach (WorkItemLink wil in links)
{
if (wil.LinkTypeEnd.Name == "Child")
{
WorkItem childTask = wiStore.GetWorkItem(wil.TargetId);
if ((childTask.Title == childTaskTitle) && (childTask.State != "Closed"))
{
return false;
}
}
}
return true;
}
private static Uri GetTFSUri(TeamFoundationRequestContext requestContext)
{
var locationService = requestContext.GetService<TeamFoundationLocationService>();
return new Uri(locationService.GetServerAccessMapping(requestContext).AccessPoint + "/" + requestContext.ServiceHost.Name);
}
private static WorkItemStore GetWorkItemStore(TeamFoundationRequestContext requestContext)
{
NetworkCredential netCred = new NetworkCredential(
"<username>",
"<password>");
WindowsCredential windowsCred = new WindowsCredential(netCred);
var credentials = new TfsClientCredentials(windowsCred);
credentials.AllowInteractive = true;
var tpc = new TfsTeamProjectCollection(
GetTFSUri(requestContext),
credentials);
tpc.Authenticate();
return tpc.GetService<WorkItemStore>();
}
public Type[] SubscribedTypes()
{
return new Type[1] { typeof(WorkItemChangedEvent) };
}
}
}
I'm building an app were i add tablerows to a view programmatically. I add a deletebutton to every row that is an ImageButton. Now i have a few questions.
Can i use an ImageButton for this?
How do i get the tablerow id
where the deletebutton was clicked?
How can i convert the eventargs
from a clickhandler into MenuItemOnMenuItemClickEventArgs or vice
versa?
How should my clickhandler look like?
Here is my sourcecode:
public class CalculatorSide2 : Activity
{
private Button stepButton;
private IntentHelper intentHelper = new IntentHelper();
private string age;
private string estLife;
private string estPens;
private string[] pensions;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
intentHelper.IntentSide2(Intent, out age, out estLife,out estPens);
SetContentView(Resource.Layout.calculatorside2);
TableLayout tl_layout = FindViewById<TableLayout>(Resource.Id.tableLayout1);
ImageView plusButton = FindViewById<ImageView>(Resource.Id.plusButton);
stepButton = FindViewById<Button>(Resource.Id.cside2stepButton);
plusButton.Click += (sender, e) =>
{
PopupMenu popupMenu = new PopupMenu(this, plusButton);
popupMenu.Inflate(Resource.Menu.popupmenu);
fillPopupMenu(popupMenu);
popupMenu.Show();
popupMenu.MenuItemClick += (s1, arg) =>
{
string info = arg.Item.TitleFormatted.ToString();
string id = arg.Item.ItemId.ToString();
var inputDialog = new AlertDialog.Builder(this);
EditText userInput = new EditText(this);
userInput.InputType = (Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.ClassNumber);
inputDialog.SetTitle(info);
inputDialog.SetView(userInput);
inputDialog.SetPositiveButton("Ok", (ss, ee) =>
{
TextView rowInfo = new TextView(this);
rowInfo.SetLines(2);
rowInfo.TextSize = 20;
rowInfo.SetTextColor(Android.Graphics.Color.Black);
rowInfo.Text = info + ": \n" + userInput.Text + "€";
ImageButton delete = new ImageButton(this);
delete.SetBackgroundDrawable(Resources.GetDrawable(Resource.Drawable.delete_icon));
TableRow row = new TableRow(this);
row.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
row.SetBackgroundColor(Android.Graphics.Color.Rgb(255, 153, 0));
row.SetPadding(0, 0, 0, 30);
row.AddView(rowInfo);
row.AddView(delete);
tl_layout.AddView(row);
});
inputDialog.SetNegativeButton("Cancel", (se, es) => { });
inputDialog.Show();
};
};
stepButton.Click += (object sender, EventArgs e) =>
{
var step = new Intent(this, typeof(CalculatorSide3));
step.PutExtra("Age", age);
step.PutExtra("EstPens", estPens);
step.PutExtra("EstLife", estLife);
step.PutStringArrayListExtra("Pensions", pensions);
StartActivity(step);
};
}
private void fillPopupMenu(PopupMenu menu)
{
int groupId = 0;
int i = 0;
int menuItemId = Android.Views.Menu.First;
int menuItemOrder = Android.Views.Menu.None;
foreach (var item in Enum.GetNames(typeof(PopupMenuItems)))
{
string itemString = item.ToString();
menu.Menu.Add(groupId, menuItemId + i, menuItemOrder + i, itemString.Replace("_", " "));
i++;
}
}
}
I hope someone understands what i mean, bc english is not my native language.
public class CalculatorSide2 : Activity
{
private Button stepButton;
private IntentHelper intentHelper = new IntentHelper();
private string age;
private string estLife;
private string estPens;
private string[] pensions;
private Dictionary<int,string> temp;
private TableLayout tl_layout;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
intentHelper.IntentSide2(Intent, out age, out estLife,out estPens);
SetContentView(Resource.Layout.calculatorside2);
tl_layout = FindViewById<TableLayout>(Resource.Id.tableLayout1);
ImageView plusButton = FindViewById<ImageView>(Resource.Id.plusButton);
stepButton = FindViewById<Button>(Resource.Id.cside2stepButton);
temp = new Dictionary<int,string>();
int i = 0;
plusButton.Click += (sender, e) =>
{
PopupMenu popupMenu = new PopupMenu(this, plusButton);
popupMenu.Inflate(Resource.Menu.popupmenu);
fillPopupMenu(popupMenu);
popupMenu.Show();
popupMenu.MenuItemClick += (s1, arg) =>
{
string info = arg.Item.TitleFormatted.ToString();
string id = arg.Item.ItemId.ToString();
var inputDialog = new AlertDialog.Builder(this);
EditText userInput = new EditText(this);
userInput.InputType = (Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.ClassNumber);
inputDialog.SetTitle(info);
inputDialog.SetView(userInput);
inputDialog.SetPositiveButton("Ok", (ss, ee) =>
{
TextView rowInfo = new TextView(this);
rowInfo.SetLines(2);
rowInfo.TextSize = 20;
rowInfo.SetTextColor(Android.Graphics.Color.Black);
rowInfo.Text = info + ": \n" + userInput.Text + "€";
ImageButton delete = new ImageButton(this);
delete.SetBackgroundDrawable(Resources.GetDrawable(Resource.Drawable.delete_icon));
delete.Focusable = false;
delete.Clickable = false;
TableRow row = new TableRow(this);
row.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
row.SetBackgroundColor(Android.Graphics.Color.Rgb(255, 153, 0));
row.SetPadding(0, 0, 0, 30);
row.Id = 10 + i;
row.Click += new EventHandler(HandleClick);
row.AddView(rowInfo);
row.AddView(delete);
tl_layout.AddView(row);
temp.Add(row.Id,userInput.Text);
i++;
});
inputDialog.SetNegativeButton("Cancel", (se, es) => { });
inputDialog.Show();
};
};
stepButton.Click += (object sender, EventArgs e) =>
{
if (temp.Count != 0)
{
pensions = new string[temp.Count];
var j = 0;
foreach (KeyValuePair<int, string> pair in temp)
{
pensions[j] = pair.Value;
j++;
}
}
else
{
pensions = new string[0];
}
var step = new Intent(this, typeof(CalculatorSide3));
step.PutExtra("Age", age);
step.PutExtra("EstPens", estPens);
step.PutExtra("EstLife", estLife);
step.PutStringArrayListExtra("Pensions", pensions);
StartActivity(step);
};
}
private void fillPopupMenu(PopupMenu menu)
{
int groupId = 0;
int i = 0;
int menuItemId = Android.Views.Menu.First;
int menuItemOrder = Android.Views.Menu.None;
foreach (var item in Enum.GetNames(typeof(PopupMenuItems)))
{
string itemString = item.ToString();
menu.Menu.Add(groupId, menuItemId + i, menuItemOrder + i, itemString.Replace("_", " "));
i++;
}
}
public void HandleClick(object sender, EventArgs e)
{
var clickedTR = sender as TableRow;
int trId = clickedTR.Id;
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Löschen");
builder.SetMessage("Möchten Sie den Eintrag wirklich löschen?");
builder.SetPositiveButton("Ja", (ssr,args) => {
temp.Remove(trId);
tl_layout.RemoveView(clickedTR);
});
builder.SetNegativeButton("Nein",(sse,arge) => { });
builder.SetCancelable(false);
builder.Show();
}
}
How can I parse a xml file in Blackberry? Can I have a link or sample code or tutorial?
I've used SAX to process XML responses from a web api and it worked well for me. Check out: http://developerlife.com/tutorials/?p=28
What exactly are you trying to accomplish with XML?
You should have a interface to implement the listener in order to notify your UI thread once parsing is over.
import java.util.Vector;
public interface MediaFeedListner {
public void mediaItemParsed(Vector mObject);
public void exception(java.io.IOException ioe);
}
implement your class with MediaFeedListner and then override the mediaItemParsed(Vector mObject) and exception(java.io.IOException ioe) methoods.
mediaItemParsed() method will have the logic for notifying the UI thread and perform required operations.
Here is the XML parser code.
package com.test.net;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Vector;
import net.rim.device.api.xml.parsers.ParserConfigurationException;
import net.rim.device.api.xml.parsers.SAXParser;
import net.rim.device.api.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.span.data.MediaObject;
import com.span.utils.FileManager;
public class MediaHandler extends DefaultHandler {
protected static final String TAG_FEED = "feed";
protected static final String TAG_ENTRY = "entry";
protected static final String TAG_TITLE = "title";
protected static final String TAG_MEDIA_GROUP = "group";
protected static final String TAG_MEDIA_CATEGORY = "category";
protected static final String TAG_MEDIA_CONTENT = "content";
protected static final String TAG_MEDIA_DESCRIPTION = "description";
protected static final String TAG_MEDIA_THUMBNAIL = "thumbnail";
protected static final String ATTR_MEDIA_CONTENT= "url";
protected static final String ATTR_MEDIA_THUMBNAIL = "url";
boolean isEntry = false;
boolean isTitle = false;
boolean isCategory = false;
boolean isDescription = false;
boolean isThumbUrl = false;
boolean isMediaUrl = false;
boolean isMediaGroup = false;
String valueTitle = "";
String valueCategory = "";
String valueDescription = "";
String valueThumbnailUrl = "";
String valueMediaUrl = "";
public static Vector mediaObjects = null;
MediaObject _dataObject = null;
MediaFeedListner listner = null;
public MediaHandler(MediaFeedListner listner) {
this.listner = listner;
mediaObjects = new Vector();
}
public void parseXMLString(String xmlString) {
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(new ByteArrayInputStream(xmlString.getBytes()), this);
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
if(localName.equalsIgnoreCase(TAG_FEED)) {
//return;
}
if(localName.equals(TAG_ENTRY))
{
_dataObject = new MediaObject();
isEntry = true;
}
if(isEntry) {
if(localName.equalsIgnoreCase(TAG_TITLE)) {
isTitle = true;
}
if(localName.equals(TAG_MEDIA_GROUP))
isMediaGroup = true;
if(isMediaGroup) {
if(localName.equalsIgnoreCase(TAG_MEDIA_CONTENT)) {
valueMediaUrl = attributes.getValue(ATTR_MEDIA_CONTENT);
if(valueMediaUrl != null) {
_dataObject.setMediaUrl(valueMediaUrl);
valueMediaUrl = "";
}
}
if(localName.equalsIgnoreCase(TAG_MEDIA_THUMBNAIL)) {
valueThumbnailUrl = attributes.getValue(ATTR_MEDIA_THUMBNAIL);
if(valueThumbnailUrl != null) {
_dataObject.setMediaThumb(valueThumbnailUrl);
valueThumbnailUrl = "";
}
}
if(localName.equalsIgnoreCase(TAG_MEDIA_DESCRIPTION)) {
isDescription = true;
}
if(localName.equalsIgnoreCase(TAG_MEDIA_CATEGORY)) {
isCategory = true;
}
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
if(isTitle){
valueTitle = new String(ch, start, length);
_dataObject.setMediaTitle(valueTitle);
System.out.println("Title value " + valueTitle);
valueTitle = "";
}
if(isCategory){
valueCategory = new String(ch, start, length);
_dataObject.setMediaCategory(valueCategory);
System.out.println("category value " + valueCategory);
valueCategory = "";
}
if(isDescription){
valueDescription = new String(ch, start, length);
_dataObject.setMediaDesc(valueDescription);
System.out.println("category value " + valueDescription);
valueDescription = "";
}
}
public void endElement(String uri, String localName, String name) throws SAXException {
if(localName.equalsIgnoreCase(TAG_FEED)) {
listner.mediaItemParsed(mediaObjects);
printMediaInfo(mediaObjects);
}
if(localName.equalsIgnoreCase(TAG_ENTRY)) {
isEntry = false;
isTitle = false;
isCategory = false;
isDescription = false;
mediaObjects.addElement(_dataObject);
}
}
public static void printMediaInfo(Vector v){
int length = v.size();
for(int i = 0 ; i <length ; i++){
MediaObject mediaObj = (MediaObject) v.elementAt(i);
FileManager.getInstance().writeLog("Title: " + mediaObj.getMediaTitle());
FileManager.getInstance().writeLog("Category: " + mediaObj.getMediaCategory());
FileManager.getInstance().writeLog("Desc: " + mediaObj.getMediaDesc());
FileManager.getInstance().writeLog("URL: " + mediaObj.getMediaUrl());
FileManager.getInstance().writeLog("Thumb: " + mediaObj.getMediaThumb());
FileManager.getInstance().writeLog("Fav count: " + mediaObj.getMediaFavCount());
FileManager.getInstance().writeLog("View Count: " + mediaObj.getMediaViewCount());
FileManager.getInstance().writeLog("Ratings: " + mediaObj.getMediaRating());
FileManager.getInstance().writeLog("============================================");
}
}
}
Its done.