Can I manually add to InclusiveNamespaces PrefixList in WSS4J - wss4j
I am using WSS4J 2.1.10 to sign a soap message with a timestamp.
The service I am sending the message to is requiring that I
1) include the namespace "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512" in the Signature, Timestamp and BST elements
2) add the "wsu" namespace to the InclusiveNamespaces PrefixList for the Transform for the Timestamp Element like such:
<ds:Reference URI="#TS-634a1acd-e8fd-4629-a19a-1935e677797b">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="wsu wsse env"/>
</ds:Transform>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<ds:DigestValue>uDqH4tK4HcsJWOit+DUW8llsEk8=</ds:DigestValue>
</ds:Reference>
3) add the "wsse" namespace to the InclusiveNamespaces PrefixList for CanonicalizationMethod for the Signature Element like such:
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="wsse env"/>
</ds:CanonicalizationMethod>
Can anyone tell me if this is possible and how?
My code so far is:
WSSConfig.init();
SOAPMessage soapMessage = getSoapMessage();
SOAPHeader soapHeader = soapMessage.getSOAPHeader();
Name toHeaderName = soapFactory.createName("To", "", "http://www.w3.org/2005/08/addressing");
SOAPHeaderElement toHeader = soapHeader.addHeaderElement(toHeaderName);
toHeader.setAttributeNS(WSConstants.WSU_NS, WSConstants.WSU_PREFIX + ":Id", "_5002");//TODO: Does this need to be a fixed value?
Attr idAttr = toHeader.getAttributeNode(WSConstants.WSU_PREFIX + ":Id");
toHeader.setIdAttributeNode(idAttr, true);
toHeader.setTextContent(vgEndpoint);
Name actionHeaderName = soapFactory.createName("Action", "", "http://www.w3.org/2005/08/addressing");
SOAPHeaderElement actionHeader = soapHeader.addHeaderElement(actionHeaderName);
actionHeader.setTextContent("http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue");
actionHeader.setMustUnderstand(true);
Name replyToHeaderName = soapFactory.createName("ReplyTo", "", "http://www.w3.org/2005/08/addressing");
SOAPHeaderElement replyToHeader = soapHeader.addHeaderElement(replyToHeaderName);
Name rtAddressName = soapFactory.createName("Address");
SOAPElement rtAddress = replyToHeader.addChildElement(rtAddressName);
rtAddress.setTextContent("http://www.w3.org/2005/08/addressing/anonymous");
Name faultToHeaderName = soapFactory.createName("FaultTo", "", "http://www.w3.org/2005/08/addressing");
SOAPHeaderElement faultToHeader = soapHeader.addHeaderElement(faultToHeaderName);
Name ftAddressName = soapFactory.createName("Address");
SOAPElement ftAddress = faultToHeader.addChildElement(ftAddressName);
ftAddress.setTextContent("http://www.w3.org/2005/08/addressing/anonymous");
Name messageIdName = soapFactory.createName("MessageID", "", "http://www.w3.org/2005/08/addressing");
SOAPHeaderElement messageIdHeader = soapHeader.addHeaderElement(messageIdName);
messageIdHeader.setTextContent("uuid:" + UUID.randomUUID().toString());
Name secHeaderName = soapFactory.createName(WSConstants.WSSE_LN, WSConstants.WSSE_PREFIX, WSConstants.WSSE_NS);
SOAPHeaderElement secHeader = soapHeader.addHeaderElement(secHeaderName);
secHeader.addNamespaceDeclaration("wsc", "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512");
secHeader.setMustUnderstand(true);
Merlin crypto = getCrypto(privateKey, password, salt, certChain);
Document unsignedDocument = soapMessage.getSOAPPart().getEnvelope().getOwnerDocument();
WSSecHeader wsSecHeader = new WSSecHeader(unsignedDocument);
wsSecHeader.insertSecurityHeader();
WSSecTimestamp timestamp = new WSSecTimestamp();
timestamp.setPrecisionInMilliSeconds(false);
timestamp.setTimeToLive(600);
timestamp.build(unsignedDocument, wsSecHeader);
// Setup the signer
WSSecSignature signer = new WSSecSignature();
signer.setUserInfo("signingCert", password);
signer.setSignatureAlgorithm(WSConstants.RSA_SHA1);
signer.setDigestAlgo(WSConstants.SHA1);
signer.setSigCanonicalization(WSConstants.C14N_EXCL_OMIT_COMMENTS);
signer.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
signer.setAddInclusivePrefixes(true);
signer.setUseSingleCertificate(true);
signer.getParts().add(new WSEncryptionPart("Timestamp", WSConstants.WSU_NS, null));
signer.getParts().add(new WSEncryptionPart("To", "http://www.w3.org/2005/08/addressing", null));
signer.build(unsignedDocument, crypto, wsSecHeader);
And here is the resultant Soap Message obviously missing these 3 points:
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
<env:Header>
<To xmlns="http://www.w3.org/2005/08/addressing" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="_5002">https://localhost/service.svc</To>
<Action xmlns="http://www.w3.org/2005/08/addressing" env:mustUnderstand="true">http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue</Action>
<ReplyTo xmlns="http://www.w3.org/2005/08/addressing">
<Address>http://www.w3.org/2005/08/addressing/anonymous</Address>
</ReplyTo>
<FaultTo xmlns="http://www.w3.org/2005/08/addressing">
<Address>http://www.w3.org/2005/08/addressing/anonymous</Address>
</FaultTo>
<MessageID xmlns="http://www.w3.org/2005/08/addressing">uuid:dc08272f-609f-47e3-ac9b-6049a98a0dab</MessageID>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" env:mustUnderstand="true">
<wsse:BinarySecurityToken EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" wsu:Id="X509-848ca3b0-a273-4cbf-ae1a-e34dc570444e">*** REMOVED ***</wsse:BinarySecurityToken>
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="SIG-25253839-097b-495a-ae60-24fa8a5f0ada">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="env"/>
</ds:CanonicalizationMethod>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<ds:Reference URI="#TS-634a1acd-e8fd-4629-a19a-1935e677797b">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="wsse env"/>
</ds:Transform>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<ds:DigestValue>uDqH4tK4HcsJWOit+DUW8llsEk8=</ds:DigestValue>
</ds:Reference>
<ds:Reference URI="#_5002">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="env"/>
</ds:Transform>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<ds:DigestValue>LiNgJUCK0GyrUZ3BpbdlRbVKnfo=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>l8EyofVcLesFD1c6btPu2zJ6dTRTyqCSWy7aW7MVH4x3nWh3y0Ir7xY2nNSZeXpcc5Q/7wrWOVgX+TkT/zwEVL62hpq4HyUJb/aIwTDhUIlH5UL7UeudDCRvvAnPOtzEp/jnapKUbsJpIzXWmvlS6tB2E3SUDT/MChradRcawJ0=</ds:SignatureValue>
<ds:KeyInfo Id="KI-c2995ba4-6fe5-457c-9367-25c5d98eff91">
<wsse:SecurityTokenReference wsu:Id="STR-4bc8eb55-9b1f-4bb8-a7cc-d4685bd3aa2c">
<wsse:Reference URI="#X509-848ca3b0-a273-4cbf-ae1a-e34dc570444e" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"/>
</wsse:SecurityTokenReference>
</ds:KeyInfo>
</ds:Signature>
<wsu:Timestamp wsu:Id="TS-634a1acd-e8fd-4629-a19a-1935e677797b">
<wsu:Created>2017-07-11T02:38:06Z</wsu:Created>
<wsu:Expires>2017-07-11T02:48:06Z</wsu:Expires>
</wsu:Timestamp>
</wsse:Security>
</env:Header>
<env:Body/>
</env:Envelope>
i did so
List<String> prefixList = new ArrayList<String>();
prefixList.add("ser soapenv");
sigFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,new ExcC14NParameterSpec(prefixList));
Result
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<InclusiveNamespaces xmlns="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="ser soapenv"/>
</ds:CanonicalizationMethod>
The sample https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/2.0/xmldsig/api/javax/xml/crypto/doc-files/SignedSoap.java
Related
Discord Bot does not respond anymore
Long question due to the code, but why does my bot not respond anymore? It's custom made for a friend and has been working for the past week or so, but now just does not respond. No errors are raised either. The only time it sends a message is when League Membership isn't in member roles and it sends the correct message. Otherwise, the bot does not respond. import discord from discord.ext import commands from keep_alive import keep_alive import asyncio import os import pytz from datetime import datetime timestamp = datetime.now(pytz.timezone('EST')) intents = discord.Intents.default() intents.members=True bot = commands.Bot(command_prefix='-', intents=intents) #bot.event async def on_member_join(member): guild = bot.get_guild(801206329049612288) membercount = len([m for m in guild.members if not m.bot]) embedwelcome = discord.Embed(title="Your KFG Future Awaits You.", description=None, color=discord.Color.teal()) embedwelcome.add_field(name="Things to do:", value=f"•Get Signed or claim a Franchise!\n•Make friends in the community!\n•Collect Rings\n•Make your way to the Super Bowl and win it all!\nWhat are you waiting for? Hurry up and get started!\n (You were member #{membercount}.)", inline=True) await member.send(embed=embedwelcome) print(f"{timestamp} - {member}") #bot.command() async def membercount(ctx): guild = bot.get_guild(801206329049612288) membercount = len([m for m in guild.members if not m.bot]) await ctx.send(f'KFG has {membercount} members.') print(f"{timestamp} - {ctx.author}") #bot.command() async def welcomemessage(ctx): guild = bot.get_guild(801206329049612288) membercount = len([m for m in guild.members if not m.bot]) embedwelcome = discord.Embed(title="Your KFG Future Awaits You.", description=None, color=discord.Color.teal()) embedwelcome.add_field(name="Things to do:", value=f"•Get Signed or claim a Franchise!\n•Make friends in the community!\n•Collect Rings\n•Make your way to the Super Bowl and win it all!\nWhat are you waiting for? Hurry up and get started!\n (You were member #{membercount}.)", inline=True) await ctx.send(embed=embedwelcome) print(f"{timestamp} - {ctx.author}") #bot.event async def on_ready(): print ("I'm online.") await bot.change_presence(activity=discord.Game(name="KFG on top!")) #bot.event async def on_message(message, user:discord.Member=None): if "sign" in message.content: signer=message.author signee=message.mentions[0].mention signeeid=message.mentions[0].id server=bot.get_guild(801206329049612288) teamsidslist=[801217912689393714, 801218094814986300, 801224104086208513, 801224243115196426, 801218409878519849, 801222227479625758, 801217334395011113, 801224558589378570, 801222379682005035, 801224701128343662, 801222478646476820, 801222668128747540, 801224835032285225, 801225075231031316, 801225211306967080, 801225374369185793, 801225554199576627, 801225700283121674, 801222743030104104, 801225798408732692, 801222852132995132, 801225991242514473, 801222923746148392, 801223092298186782, 801226082207924244, 801223311081996288, 801226241948647496, 801223486973542451, 801223635858882562, 801223809340276745, 801226427890139137, 801223952344416337] teamnames=['Arizona Cardinals', 'Atlanta Falcons', 'Baltimore Ravens', 'Buffalo Bills', 'Carolina Panthers', 'Chicago Bears', 'Cincinnati Bengals', 'Cleveland Browns', 'Dallas Cowboys', 'Denver Broncos', 'Detroit Lions', 'Green Bay Packers', 'Houston Texans', 'Indianapolis Colts', 'Jacksonville Jaguars', 'Kansas City Chiefs', 'Miami Dolphins', 'Los Angeles Chargers', 'Kansas City Chiefs', 'Indianapolis Colts', 'Jacksonville Jaguars', 'Kansas City Chiefs', 'Las Vegas Raiders', 'Los Angeles Chargers', 'Los Angeles Rams', 'Miami Dolphins', 'Minnesota Vikings', 'New England Patriots','New Orleans Saints', 'New York Giants', 'New York Jets', 'Philidelphia Eagles', 'Pittsburgh Steelers', 'San Fransisco 49ers', 'Seattle Seahawks', 'Tampa Bay Buccaneers', 'Tennesse Titans', 'Washington Football Team'] teamemojis=['Arizona_Cardinals', 'Atlanta_Falcons', 'Baltimore_Ravens', 'Buffalo_Bills', 'Carolina_Panthers', 'Chicago_Bears', 'Cincinnati_Bengals', 'Cleveland_Browns', 'Dallas_Cowboys', 'Denver_Broncos', 'Detroit_Lions', 'Green_Bay_Packers', 'Houston_Texans', 'Indianaoplis_Colts', 'Jacksonville_Jaguars', 'Kansas_City_Chiefs', 'Miami_Dolphins', 'Los_Angeles_Chargers', 'Kansas_City_Chiefs', 'Indianaoplis_Colts', 'Jacksonville_Jaguars', 'Kansas_City_Chiefs', 'Las_Vegas_Raiders', 'Los_Angeles_Chargers', 'Los_Angeles_Rams', 'Miami_Dolphins', 'Minnesota_Vikings', 'New_England_Patriots', 'New_Orleans_Saints', 'New_York_Giants', 'New_York_Jets', 'Philidelphia_Eagles', 'Pittsburgh_Steelers', 'San_Francisco_49ers', 'Seattle_Seahawks', 'Tampa_Bay_Buccaneers', 'Tennessee_Titans', 'Washington_Football_Team'] FO = discord.utils.get(message.author.guild.roles, id=801257262240235530) GM = discord.utils.get(message.author.guild.roles, id=801257315620749362) HC = discord.utils.get(message.author.guild.roles, id=801257358751694848) AC = discord.utils.get(message.author.guild.roles, id=801257421334904872) FA = discord.utils.get(message.author.guild.roles, id=801255786062807090) Suspended = discord.utils.get(message.author.guild.roles, id=805818648802361426) roster=[] agency=[] teams=[] for rolesids in message.author.roles: if rolesids.id in teamsidslist: teams.append(rolesids.id) step2=str(teams) step3=step2.replace("[","") step4=step3.replace("]","") print(step4) step5=teamsidslist.index(int(step4)) print(step5) emote=discord.utils.get(server.emojis,name=teamemojis[step5]) teamname=teamnames[step5] team = discord.utils.get(message.author.guild.roles,id=int(step4)) for agents in server.members: if FA in agents.roles: agency.append(agents.id) if signeeid not in agency: embedno = discord.Embed(title="Transaction Failed!", description=None, color=discord.Color.red()) embedno.add_field(name="This Transaction Couldn't Be Completed.", value="This player is signed already! Have them demand from their team or get released.") await message.channel.send(embed=embedno) elif [FO, GM, HC, AC] in message.author.roles: for guys in server.members: if guys.id==signeeid: await guys.add_roles(team) await guys.remove_roles(FA) if Suspended in guys.roles: await message.channel.send("This player is signable, but is ineligible as they are suspended.") roster.append(guys) roster_size=str(len(roster)) SignEmbed= discord.Embed(title="KFG Transactions", description=None, color=discord.Color.green()) SignEmbed.add_field(name='Successful Transaction.', value=signee+" has been signed to the "+str(emote)+" "+teamname+"!") SignEmbed.add_field(name="Roster Size is now ", value=roster_size+'/20', inline=True) await message.channel.send(embed=SignEmbed) bot.remove_command('help') #bot.event async def on_message3(message, user:discord.Member=None): if "I demand" in message.content: signer=message.author signee=message.mentions[0].mention signeeid=message.mentions[0].id server=bot.get_guild(801206329049612288) teamsidslist=[801217912689393714, 801218094814986300, 801224104086208513, 801224243115196426, 801218409878519849, 801222227479625758, 801217334395011113, 801224558589378570, 801222379682005035, 801224701128343662, 801222478646476820, 801222668128747540, 801224835032285225, 801225075231031316, 801225211306967080, 801225374369185793, 801225554199576627, 801225700283121674, 801222743030104104, 801225798408732692, 801222852132995132, 801225991242514473, 801222923746148392, 801223092298186782, 801226082207924244, 801223311081996288, 801226241948647496, 801223486973542451, 801223635858882562, 801223809340276745, 801226427890139137, 801223952344416337] teamnames=['Arizona Cardinals', 'Atlanta Falcons', 'Baltimore Ravens', 'Buffalo Bills', 'Carolina Panthers', 'Chicago Bears', 'Cincinnati Bengals', 'Cleveland Browns', 'Dallas Cowboys', 'Denver Broncos', 'Detroit Lions', 'Green Bay Packers', 'Houston Texans', 'Indianapolis Colts', 'Jacksonville Jaguars', 'Kansas City Chiefs', 'Miami Dolphins', 'Los Angeles Chargers', 'Kansas City Chiefs', 'Indianapolis Colts', 'Jacksonville Jaguars', 'Kansas City Chiefs', 'Las Vegas Raiders', 'Los Angeles Chargers', 'Los Angeles Rams', 'Miami Dolphins', 'Minnesota Vikings', 'New England Patriots','New Orleans Saints', 'New York Giants', 'New York Jets', 'Philidelphia Eagles', 'Pittsburgh Steelers', 'San Fransisco 49ers', 'Seattle Seahawks', 'Tampa Bay Buccaneers', 'Tennesse Titans', 'Washington Football Team'] teamemojis=['Arizona_Cardinals', 'Atlanta_Falcons', 'Baltimore_Ravens', 'Buffalo_Bills', 'Carolina_Panthers', 'Chicago_Bears', 'Cincinnati_Bengals', 'Cleveland_Browns', 'Dallas_Cowboys', 'Denver_Broncos', 'Detroit_Lions', 'Green_Bay_Packers', 'Houston_Texans', 'Indianaoplis_Colts', 'Jacksonville_Jaguars', 'Kansas_City_Chiefs', 'Miami_Dolphins', 'Los_Angeles_Chargers', 'Kansas_City_Chiefs', 'Indianaoplis_Colts', 'Jacksonville_Jaguars', 'Kansas_City_Chiefs', 'Las_Vegas_Raiders', 'Los_Angeles_Chargers', 'Los_Angeles_Rams', 'Miami_Dolphins', 'Minnesota_Vikings', 'New_England_Patriots', 'New_Orleans_Saints', 'New_York_Giants', 'New_York_Jets', 'Philidelphia_Eagles', 'Pittsburgh_Steelers', 'San_Francisco_49ers', 'Seattle_Seahawks', 'Tampa_Bay_Buccaneers', 'Tennessee_Titans', 'Washington_Football_Team'] FO = discord.utils.get(message.author.guild.roles, id=801257262240235530) GM = discord.utils.get(message.author.guild.roles, id=801257315620749362) HC = discord.utils.get(message.author.guild.roles, id=801257358751694848) AC = discord.utils.get(message.author.guild.roles, id=801257421334904872) FA = discord.utils.get(message.author.guild.roles, id=801255786062807090) roster=[] teams=[] agency=[] for rolesids in message.author.roles: if rolesids.id in teamsidslist: teams.append(rolesids.id) step2=str(teams) step3=step2.replace("[","") step4=step3.replace("]","") print(step4) step5=teamsidslist.index(int(step4)) print(step5) emote=discord.utils.get(server.emojis,name=teamemojis[step5]) teamname=teamnames[step5] team = discord.utils.get(message.author.guild.roles,id=int(step4)) if [teams] in message.author.roles: for guys in server.members: if guys.id==signeeid: await guys.add_roles(FA) await guys.remove_roles(team) if signeeid in agency: await message.channel.send('You are not signed and cannot demand!') roster.append(guys) roster_size=str(len(roster)) SignEmbed= discord.Embed(title="KFG Transactions", description=None, color=discord.Color.green()) SignEmbed.add_field(name='Successful Transaction.', value=signee+" has demanded from the "+str(emote)+" "+teamname+"!") SignEmbed.add_field(name=f"{str(emote)} {teamname}Roster Size is now ", value=roster_size+'/20', inline=True) await message.channel.send(embed=SignEmbed) #bot.event async def on_message2(message, user:discord.Member=None): if "release" in message.content: signer=message.author signee=message.mentions[0].mention signeeid=message.mentions[0].id74 server=bot.get_guild(801206329049612288) teamsidslist=[801217912689393714, 801218094814986300, 801224104086208513, 801224243115196426, 801218409878519849, 801222227479625758, 801217334395011113, 801224558589378570, 801222379682005035, 801224701128343662, 801222478646476820, 801222668128747540, 801224835032285225, 801225075231031316, 801225211306967080, 801225374369185793, 801225554199576627, 801225700283121674, 801222743030104104, 801225798408732692, 801222852132995132, 801225991242514473, 801222923746148392, 801223092298186782, 801226082207924244, 801223311081996288, 801226241948647496, 801223486973542451, 801223635858882562, 801223809340276745, 801226427890139137, 801223952344416337] teamnames=['Arizona Cardinals', 'Atlanta Falcons', 'Baltimore Ravens', 'Buffalo Bills', 'Carolina Panthers', 'Chicago Bears', 'Cincinnati Bengals', 'Cleveland Browns', 'Dallas Cowboys', 'Denver Broncos', 'Detroit Lions', 'Green Bay Packers', 'Houston Texans', 'Indianapolis Colts', 'Jacksonville Jaguars', 'Kansas City Chiefs', 'Miami Dolphins', 'Los Angeles Chargers', 'Kansas City Chiefs', 'Indianapolis Colts', 'Jacksonville Jaguars', 'Kansas City Chiefs', 'Las Vegas Raiders', 'Los Angeles Chargers', 'Los Angeles Rams', 'Miami Dolphins', 'Minnesota Vikings', 'New England Patriots','New Orleans Saints', 'New York Giants', 'New York Jets', 'Philidelphia Eagles', 'Pittsburgh Steelers', 'San Fransisco 49ers', 'Seattle Seahawks', 'Tampa Bay Buccaneers', 'Tennesse Titans', 'Washington Football Team'] teamemojis=['Arizona_Cardinals', 'Atlanta_Falcons', 'Baltimore_Ravens', 'Buffalo_Bills', 'Carolina_Panthers', 'Chicago_Bears', 'Cincinnati_Bengals', 'Cleveland_Browns', 'Dallas_Cowboys', 'Denver_Broncos', 'Detroit_Lions', 'Green_Bay_Packers', 'Houston_Texans', 'Indianaoplis_Colts', 'Jacksonville_Jaguars', 'Kansas_City_Chiefs', 'Miami_Dolphins', 'Los_Angeles_Chargers', 'Kansas_City_Chiefs', 'Indianaoplis_Colts', 'Jacksonville_Jaguars', 'Kansas_City_Chiefs', 'Las_Vegas_Raiders', 'Los_Angeles_Chargers', 'Los_Angeles_Rams', 'Miami_Dolphins', 'Minnesota_Vikings', 'New_England_Patriots', 'New_Orleans_Saints', 'New_York_Giants', 'New_York_Jets', 'Philidelphia_Eagles', 'Pittsburgh_Steelers', 'San_Francisco_49ers', 'Seattle_Seahawks', 'Tampa_Bay_Buccaneers', 'Tennessee_Titans', 'Washington_Football_Team'] FO = discord.utils.get(message.author.guild.roles, id=801257262240235530) GM = discord.utils.get(message.author.guild.roles, id=801257315620749362) HC = discord.utils.get(message.author.guild.roles, id=801257358751694848) AC = discord.utils.get(message.author.guild.roles, id=801257421334904872) FA = discord.utils.get(message.author.guild.roles, id=801255786062807090) roster=[] teams=[] for rolesids in message.author.roles: if rolesids.id in teamsidslist: teams.append(rolesids.id) step2=str(teams) step3=step2.replace("[","") step4=step3.replace("]","") print(step4) step5=teamsidslist.index(int(step4)) print(step5) emote=discord.utils.get(server.emojis,name=teamemojis[step5]) teamname=teamnames[step5] team = discord.utils.get(message.author.guild.roles,id=int(step4)) if [FO, GM, HC, AC] in message.author.roles: for guys in server.members: if guys.id==signeeid: await guys.add_roles(FA) await guys.remove_roles(team) roster.append(guys) roster_size=str(len(roster)) SignEmbed= discord.Embed(title="KFG Transactions", description=None, color=discord.Color.green()) SignEmbed.add_field(name='Successful Transaction.', value=signee+" has been released from the "+str(emote)+" "+teamname+"!") SignEmbed.add_field(name="Roster Size is now ", value=roster_size+'/20', inline=True) await message.channel.send(embed=SignEmbed) async def on_message5(message, member:discord.Member=None): if "promote" in message.content: signer=message.author signee=message.mentions[0].mention signeeid=message.mentions[0].id server=bot.get_guild(801206329049612288) teamsidslist=[801217912689393714, 801218094814986300, 801224104086208513, 801224243115196426, 801218409878519849, 801222227479625758, 801217334395011113, 801224558589378570, 801222379682005035, 801224701128343662, 801222478646476820, 801222668128747540, 801224835032285225, 801225075231031316, 801225211306967080, 801225374369185793, 801225554199576627, 801225700283121674, 801222743030104104, 801225798408732692, 801222852132995132, 801225991242514473, 801222923746148392, 801223092298186782, 801226082207924244, 801223311081996288, 801226241948647496, 801223486973542451, 801223635858882562, 801223809340276745, 801226427890139137, 801223952344416337] teamnames=['Arizona Cardinals', 'Atlanta Falcons', 'Baltimore Ravens', 'Buffalo Bills', 'Carolina Panthers', 'Chicago Bears', 'Cincinnati Bengals', 'Cleveland Browns', 'Dallas Cowboys', 'Denver Broncos', 'Detroit Lions', 'Green Bay Packers', 'Houston Texans', 'Indianapolis Colts', 'Jacksonville Jaguars', 'Kansas City Chiefs', 'Miami Dolphins', 'Los Angeles Chargers', 'Kansas City Chiefs', 'Indianapolis Colts', 'Jacksonville Jaguars', 'Kansas City Chiefs', 'Las Vegas Raiders', 'Los Angeles Chargers', 'Los Angeles Rams', 'Miami Dolphins', 'Minnesota Vikings', 'New England Patriots','New Orleans Saints', 'New York Giants', 'New York Jets', 'Philidelphia Eagles', 'Pittsburgh Steelers', 'San Fransisco 49ers', 'Seattle Seahawks', 'Tampa Bay Buccaneers', 'Tennesse Titans', 'Washington Football Team'] teamemojis=['Arizona_Cardinals', 'Atlanta_Falcons', 'Baltimore_Ravens', 'Buffalo_Bills', 'Carolina_Panthers', 'Chicago_Bears', 'Cincinnati_Bengals', 'Cleveland_Browns', 'Dallas_Cowboys', 'Denver_Broncos', 'Detroit_Lions', 'Green_Bay_Packers', 'Houston_Texans', 'Indianaoplis_Colts', 'Jacksonville_Jaguars', 'Kansas_City_Chiefs', 'Miami_Dolphins', 'Los_Angeles_Chargers', 'Kansas_City_Chiefs', 'Indianaoplis_Colts', 'Jacksonville_Jaguars', 'Kansas_City_Chiefs', 'Las_Vegas_Raiders', 'Los_Angeles_Chargers', 'Los_Angeles_Rams', 'Miami_Dolphins', 'Minnesota_Vikings', 'New_England_Patriots', 'New_Orleans_Saints', 'New_York_Giants', 'New_York_Jets', 'Philidelphia_Eagles', 'Pittsburgh_Steelers', 'San_Francisco_49ers', 'Seattle_Seahawks', 'Tampa_Bay_Buccaneers', 'Tennessee_Titans', 'Washington_Football_Team'] FO = discord.utils.get(message.author.guild.roles, id=801257262240235530) GM = discord.utils.get(message.author.guild.roles, id=801257315620749362) HC = discord.utils.get(message.author.guild.roles, id=801257358751694848) AC = discord.utils.get(message.author.guild.roles, id=801257421334904872) staffroles = [GM, HC, AC] teams=[] roster=[] for rolesids in message.author.roles: if rolesids.id in teamsidslist: teams.append(rolesids.id) step2=str(staffroles) step3=step2.replace("[","") step4=step3.replace("]","") print(step4) step5=teamsidslist.index(int(step4)) print(step5) emote=discord.utils.get(server.emojis,name=teamemojis[step5]) teamname=teamnames[step5] team = discord.utils.get(message.author.guild.roles,id=int(step4)) if FO in message.author.roles: for guys in server.members: if guys.id==signeeid: await guys.add_roles(staffroles) embedpromoted = discord.Embed(title='KFG Transactions', description=None) embedpromoted.add_field(name="The "+teamname+ " have made a promotion!", value="Congratulations to "+signee+" as the "+str(emote)+teamname+ " has promoted them to "+staffroles+".") await message.channel.send(embed=embedpromoted) #bot.event async def on_message4(message, member:discord.Member=None): if "demote" in message.content: signer=message.author signee=message.mentions[0].mention signeeid=message.mentions[0].id server=bot.get_guild(801206329049612288) teamsidslist=[801217912689393714, 801218094814986300, 801224104086208513, 801224243115196426, 801218409878519849, 801222227479625758, 801217334395011113, 801224558589378570, 801222379682005035, 801224701128343662, 801222478646476820, 801222668128747540, 801224835032285225, 801225075231031316, 801225211306967080, 801225374369185793, 801225554199576627, 801225700283121674, 801222743030104104, 801225798408732692, 801222852132995132, 801225991242514473, 801222923746148392, 801223092298186782, 801226082207924244, 801223311081996288, 801226241948647496, 801223486973542451, 801223635858882562, 801223809340276745, 801226427890139137, 801223952344416337] teamnames=['Arizona Cardinals', 'Atlanta Falcons', 'Baltimore Ravens', 'Buffalo Bills', 'Carolina Panthers', 'Chicago Bears', 'Cincinnati Bengals', 'Cleveland Browns', 'Dallas Cowboys', 'Denver Broncos', 'Detroit Lions', 'Green Bay Packers', 'Houston Texans', 'Indianapolis Colts', 'Jacksonville Jaguars', 'Kansas City Chiefs', 'Miami Dolphins', 'Los Angeles Chargers', 'Kansas City Chiefs', 'Indianapolis Colts', 'Jacksonville Jaguars', 'Kansas City Chiefs', 'Las Vegas Raiders', 'Los Angeles Chargers', 'Los Angeles Rams', 'Miami Dolphins', 'Minnesota Vikings', 'New England Patriots','New Orleans Saints', 'New York Giants', 'New York Jets', 'Philidelphia Eagles', 'Pittsburgh Steelers', 'San Fransisco 49ers', 'Seattle Seahawks', 'Tampa Bay Buccaneers', 'Tennesse Titans', 'Washington Football Team'] teamemojis=['Arizona_Cardinals', 'Atlanta_Falcons', 'Baltimore_Ravens', 'Buffalo_Bills', 'Carolina_Panthers', 'Chicago_Bears', 'Cincinnati_Bengals', 'Cleveland_Browns', 'Dallas_Cowboys', 'Denver_Broncos', 'Detroit_Lions', 'Green_Bay_Packers', 'Houston_Texans', 'Indianaoplis_Colts', 'Jacksonville_Jaguars', 'Kansas_City_Chiefs', 'Miami_Dolphins', 'Los_Angeles_Chargers', 'Kansas_City_Chiefs', 'Indianaoplis_Colts', 'Jacksonville_Jaguars', 'Kansas_City_Chiefs', 'Las_Vegas_Raiders', 'Los_Angeles_Chargers', 'Los_Angeles_Rams', 'Miami_Dolphins', 'Minnesota_Vikings', 'New_England_Patriots', 'New_Orleans_Saints', 'New_York_Giants', 'New_York_Jets', 'Philidelphia_Eagles', 'Pittsburgh_Steelers', 'San_Francisco_49ers', 'Seattle_Seahawks', 'Tampa_Bay_Buccaneers', 'Tennessee_Titans', 'Washington_Football_Team'] FO = discord.utils.get(message.author.guild.roles, id=801257262240235530) GM = discord.utils.get(message.author.guild.roles, id=801257315620749362) HC = discord.utils.get(message.author.guild.roles, id=801257358751694848) AC = discord.utils.get(message.author.guild.roles, id=801257421334904872) staffroles = [GM, HC, AC] teams=[] roster=[] for rolesids in message.author.roles: if rolesids.id in teamsidslist: teams.append(rolesids.id) step2=str(staffroles) step3=step2.replace("[","") step4=step3.replace("]","") print(step4) step5=teamsidslist.index(int(step4)) print(step5) emote=discord.utils.get(server.emojis,name=teamemojis[step5]) teamname=teamnames[step5] team = discord.utils.get(message.author.guild.roles,id=int(step4)) if FO in message.author.roles: for guys in server.members: if guys.id==signeeid: await guys.remove_roles(staffroles) embedpromoted = discord.Embed(title='KFG Transactions', description=None) embedpromoted.add_field(name="The "+teamname+ " has made a demotion.", value='Tough luck for '+signee+' as they have been demoted from their spot as '+staffroles+'on the '+str(emote)+teamname+'.', inline=True) await message.channel.send(embed=embedpromoted) #bot.command() async def rostercount(ctx, member:discord.Member=None): server=bot.get_guild(801206329049612288) teamsidslist=[801217912689393714, 801218094814986300, 801224104086208513, 801224243115196426, 801218409878519849, 801222227479625758, 801217334395011113, 801224558589378570, 801222379682005035, 801224701128343662, 801222478646476820, 801222668128747540, 801224835032285225, 801225075231031316, 801225211306967080, 801225374369185793, 801225554199576627, 801225700283121674, 801222743030104104, 801225798408732692, 801222852132995132, 801225991242514473, 801222923746148392, 801223092298186782, 801226082207924244, 801223311081996288, 801226241948647496, 801223486973542451, 801223635858882562, 801223809340276745, 801226427890139137, 801223952344416337] teamnames=['Arizona Cardinals', 'Atlanta Falcons', 'Baltimore Ravens', 'Buffalo Bills', 'Carolina Panthers', 'Chicago Bears', 'Cincinnati Bengals', 'Cleveland Browns', 'Dallas Cowboys', 'Denver Broncos', 'Detroit Lions', 'Green Bay Packers', 'Houston Texans', 'Indianapolis Colts', 'Jacksonville Jaguars', 'Kansas City Chiefs', 'Miami Dolphins', 'Los Angeles Chargers', 'Kansas City Chiefs', 'Indianapolis Colts', 'Jacksonville Jaguars', 'Kansas City Chiefs', 'Las Vegas Raiders', 'Los Angeles Chargers', 'Los Angeles Rams', 'Miami Dolphins', 'Minnesota Vikings', 'New England Patriots','New Orleans Saints', 'New York Giants', 'New York Jets', 'Philidelphia Eagles', 'Pittsburgh Steelers', 'San Fransisco 49ers', 'Seattle Seahawks', 'Tampa Bay Buccaneers', 'Tennesse Titans', 'Washington Football Team'] teamemojis=['Arizona_Cardinals', 'Atlanta_Falcons', 'Baltimore_Ravens', 'Buffalo_Bills', 'Carolina_Panthers', 'Chicago_Bears', 'Cincinnati_Bengals', 'Cleveland_Browns', 'Dallas_Cowboys', 'Denver_Broncos', 'Detroit_Lions', 'Green_Bay_Packers', 'Houston_Texans', 'Indianaoplis_Colts', 'Jacksonville_Jaguars', 'Kansas_City_Chiefs', 'Miami_Dolphins', 'Los_Angeles_Chargers', 'Kansas_City_Chiefs', 'Indianaoplis_Colts', 'Jacksonville_Jaguars', 'Kansas_City_Chiefs', 'Las_Vegas_Raiders', 'Los_Angeles_Chargers', 'Los_Angeles_Rams', 'Miami_Dolphins', 'Minnesota_Vikings', 'New_England_Patriots', 'New_Orleans_Saints', 'New_York_Giants', 'New_York_Jets', 'Philidelphia_Eagles', 'Pittsburgh_Steelers', 'San_Francisco_49ers', 'Seattle_Seahawks', 'Tampa_Bay_Buccaneers', 'Tennessee_Titans', 'Washington_Football_Team'] roster=[] teams=[] roster=[] step2=str(teams) step3=step2.replace("[","") step4=step3.replace("]","") print(step4) step5=teamsidslist.index(int(step4)) print(step5) emote=discord.utils.get(server.emojis,name=teamemojis[step5]) teamname=teamnames[step5] team = discord.utils.get(ctx.author.guild.roles,id=int(step4)) for guys in server.members: await asyncio.sleep(1) roster_size=(len(roster)) teamlist = discord.Embed(title=+str(emote)+teamname+"'s roster count:") teamlist.add_field(name=roster_size, value=str(emote)+teamname+f"'s roster count - brought up by {ctx.author}") await ctx.send(embed=teamlist) #bot.event async def on_command_error(ctx, error): print(f"Some idiot raised an error at {timestamp} - it was {ctx.author}: {error}") raise error keep_alive() bot.run(os.getenv('kfgbottoken'))
You cannot create more than one on_message event. Only the last one will work. Also, you have to add bot.process_commands(message) to the last line of on_message event. Otherwise it prevents commands from running. #bot.event async def on_message(message): ... await bot.process_commands(message) All you have to do is putting all your on_message events in just one.
Reorder XML Elements in Extendscript Indesign
I want to reorder the following list of movies in such a way that movies of the version==3D should be placed before the ones in version==2D. Input <films> <film name="Foobar" version="2D"></film> <film name="Foobar" version="3D"></film> <film name="Foobaz" version="2D"></film> <film name="Foobaz" version="3D"></film> </films> Desired Output <films> <film name="Foobar" version="3D"></film> <film name="Foobar" version="2D"></film> <film name="Foobaz" version="3D"></film> <film name="Foobaz" version="2D"></film> </films> I've fiddled around and ended up with the following code. Hopefully it understandable. /*** Extend Array prototype to have a indeOf function ***/ Array.prototype.indexOf = function(item) { var index = 0, length = this.length; for ( ; index < length; index++ ) { if ( this[index] == item ) return index; } return -1; }; var xmlString = '\ <films>\ <film name="Foobar" version="2D"></film>\ <film name="Foobar" version="3D"></film>\ <film name="Foobaz" version="2D"></film>\ <film name="Foobaz" version="3D"></film>\ </films>'; var xml = new XML(xmlString); var sortVersion = ['2D', '3D']; var uniqueMovies = new Array(); for (var index = 0; index < xml.elements().length(); index++) { if (index == 0) continue; // Fetch meta data of previous movie var prevTitle = xml.elements()[index - 1].#name; var prevVersion = xml.elements()[index - 1].#version; var prevVersionIdx = sortVersion.indexOf(prevVersion); // Fetch meta data of current movie var curTitle = xml.elements()[index].#name; var curVersion = xml.elements()[index].#version; var curVersionIdx = sortVersion.indexOf(curVersion); // If both movie title matches verify which movie should be prioritized if (prevTitle == curTitle) { if (prevVersionIdx < curVersionIdx) { // Movie prio movie before less prio movie xml.insertChildBefore(xml.elements()[index - 1], xml.elements()[index]); // And delete the next in index delete xml.elements()[index + 1]; } } } $.writeln("-----"); $.writeln(""); $.writeln(xml.elements().toString()); return xml However when I run this script I end with the following result where nothing is changed at all although the both if condition are hit and the element on index[1] is added before index[0]. <films> <film name="Foobar" version="2D"/> <film name="Foobar" version="3D"/> <film name="Foobaz" version="2D"/> <film name="Foobaz" version="3D"/> </films> Does anyone have an idea what I am doing wrong here?
Consider the following approach instead: script.jsx /** * Extend Array prototype to have a indexOf function */ Array.prototype.indexOf = function(item) { var index = 0, length = this.length; for ( ; index < length; index++ ) { if ( this[index] == item ) return index; } return -1; }; var xmlString = '\ <films>\ <film name="Foobar" version="2D"></film>\ <film name="Foobar" version="3D"></film>\ <film name="Foobaz" version="2D"></film>\ <film name="Foobaz" version="3D"></film>\ <film name="Foo" version="3D"></film>\ <film name="Quux" version="2D"></film>\ <film name="Quux" version="3D"></film>\ </films>'; var xml = new XML(xmlString); var sortVersion = ['2D', '3D']; // 1. Create a temporary XML object with a matching `films` root element. var tempXml = new XML('<' + xml.name() + '></' + xml.name() + '>'); for (var index = 0, max = xml.elements().length(); index < max; index++) { // Fetch meta data of previous movie var prevTitle = String(xml.elements()[index - 1].#name); var prevVersion = xml.elements()[index - 1].#version; var prevVersionIdx = sortVersion.indexOf(prevVersion); // Fetch meta data of current movie var curTitle = String(xml.elements()[index].#name); var curVersion = xml.elements()[index].#version; var curVersionIdx = sortVersion.indexOf(curVersion); // 2. Insert each XML element node from the original XML Object into // the temporary XML Object and position (i.e. sort) as neccessary. if (prevTitle === curTitle && prevVersion < curVersion) { tempXml.insertChildBefore(tempXml.elements()[index -1], xml.elements()[index]) } else { // There's nothing to change (i.e. sort) so insert it as-is . tempXml.insertChildBefore(tempXml.elements()[index], xml.elements()[index]) } } // 3. Overwrite original XML object's children with temporary (sorted) XML objects children. xml.setChildren(tempXml.children()); // 4. Delete temporary XML object. tempXml = undefined; // Testing... $.writeln(xml) $.writeln('-----------------') $.writeln(xml.elements().length()) $.writeln('-----------------') Explanation: Instead of attempting to manipulate (i.e. sort) the original XML Object the gist above does the following instead: Creates another XML Object that contains a <films> root element only. This XML Object will be temporary. During each turn of the for loop we; Insert a clone of each XML element node from the original XML Object into the temporary XML Object. Position (i.e. sort) each XML element node as necessary. Overwrite the original XML objects child element nodes with child element nodes from the temporary/sorted XML Object. Finally we delete the temporary XML Object (i.e. set it to undefined) as it's no longer required. Result The example gist above includes the following source XML: <films> <film name="Foobar" version="2D"></film> <film name="Foobar" version="3D"></film> <film name="Foobaz" version="2D"></film> <film name="Foobaz" version="3D"></film> <film name="Foo" version="3D"></film> <film name="Quux" version="2D"></film> <film name="Quux" version="3D"></film> </films> which will be transformed to the following: <films> <film name="Foobar" version="3D"/> <film name="Foobar" version="2D"/> <film name="Foobaz" version="3D"/> <film name="Foobaz" version="2D"/> <film name="Foo" version="3D"/> <film name="Quux" version="3D"/> <film name="Quux" version="2D"/> </films> Note: For more complex XML structures and transformation requirements than the example provided in your question, I'd consider utilizing XSLT instead. Given your current requirement a template like this one will achieve your desired result.
How can I use condition and filters in LinkEntity?
I want to create a QueryExpression to simulate this SQL statement select * from A inner join B on A.b_id=B.ID where B.Name like "% what ever %" this is how the FetchXML might look like <?xml version="1.0" encoding="UTF-8"?> <fetch distinct="true" mapping="logical" output-format="xml-platform" version="1.0"> <entity name="A"> <attribute name="ID" /> <attribute name="sce_name" /> <link-entity name="B" alias="ab" to="b_id" from="A"> <filter type="and"> <condition attribute="Name" value="% what ever %" operator="like" /> </filter> </link-entity> </entity> </fetch> How I can make this in QueryExpression LinkQuery Conditions and Filters, also I don't want to start from B since A might have its conditions too. This is what I have tried so far QueryExpression query = new QueryExpression("A"); query.ColumnSet.AllColumns = true; var link = new LinkEntity() { JoinOperator = JoinOperator.Inner, EntityAlias = "c", LinkFromEntityName = "A", LinkToEntityName = "B", LinkFromAttributeName = "b_id", LinkToAttributeName = "ID", }; using (var Service = new OrganizationService("con")) { EntityCollection entities = Service.RetrieveMultiple(query); }
Hopefully this should be self explanatory. QueryExpression query = new QueryExpression("a") //Start on A { ColumnSet = new ColumnSet(), //Columns to retrieve from A Criteria = new FilterExpression(LogicalOperator.And) //Conditions for A { Conditions = { new ConditionExpression() } }, LinkEntities = { //Link to B new LinkEntity("a", "b", "aid", "bid", JoinOperator.Inner) { Columns = new ColumnSet(), //Columns to retrieve from B LinkCriteria = new FilterExpression() //Conditions for B { Conditions = { new ConditionExpression() } } } } };
In addition to James' answer, don't forget you can also query using the fetch statement you already have: RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest { Query = new FetchExpression( #"<fetch distinct="true" mapping="logical" output-format="xml-platform" version="1.0"> <entity name="A"> ... </entity> </fetch>"); }; I rarely bother writing out QueryExpressions because executing with fetch is much easier.
Reset mx:hslider value
I am new to flex and my question is how to reset mx hslider value with "reset" button. here is a sample script: <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <fx:Script> <![CDATA[ import mx.events.SliderEvent; private var txtvalue:int = 0; protected function Focal_changeHandler(event:SliderEvent):void { txtvalue = Focal.value; if(txtvalue == 0) Slider_txt.text = "Low"; if(txtvalue == 1) Slider_txt.text = "Middle"; if(txtvalue == 2) Slider_txt.text = "High"; } ]]> </fx:Script> <mx:HSlider id="Focal" x="476" y="345" maximum="2" minimum="0" value="0" buttonMode="true" enabled="true" snapInterval="1" tickInterval="1" allowTrackClick="true" liveDragging="true" change="Focal_changeHandler(event)"/> <s:Label id="Slider_txt" x="472" y="319" text= "Low"/> <s:Button x="476" y="459" label="Reset" id="Res_btn"/> </s:Application>
Normally you could do <s:Button x="476" y="459" label="Reset" id="Res_btn" click="{Focal.value = 0}"/> But since you'd need to update the text as well, it's better to do an own method for that: <s:Button x="476" y="459" label="Reset" id="Res_btn" click="onResetClick()"/> and in your code part: protected function Focal_changeHandler(event:SliderEvent):void { updateSliderText(); } private function onResetClick():void { Focal.value = 0; updateSliderText(); } private function updateSliderText():void { txtvalue = Focal.value; if (txtvalue == 0) Slider_txt.text = "Low"; if (txtvalue == 1) Slider_txt.text = "Middle"; if (txtvalue == 2) Slider_txt.text = "High"; }
Adding XElement to XML file using Linq to XML
Using Linq to XML, I am trying to add an XElement to an existing XML file. It has to be done in the Windows Phone .NET framework. Currently my XML file looks like this: <?xml version="1.0" encoding="utf-8"?> <Kids> <Child> <Name>Kid1</Name> <FirstName>hisname</FirstName> </Child> </Kids> and my code looks like this: using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("YourKids.xml", fileMode, store)) { XDocument x = XDocument.Load(stream); XElement t = new XElement("Child", new XElement("Name", pName), new XElement("FirstName", pFirstname)); t.Add(from el in x.Elements() where el == el.Descendants("Child").Last() select el); x.Save(stream); } this doesn't do what I want to achieve. I want to add a new "Child" element to the the exisiting XML file like this : <?xml version="1.0" encoding="utf-8"?> <Kids> <Child> <Name>Kid1</Name> <FirstName>hisname</FirstName> </Child> <Child> <Name>kid2</Name> <FirstName>SomeName</FirstName> </Child> </Kids> Could use some help because I am stuck ;-) After the tips from GSerjo, my code looks like this now: try { if (store.FileExists("YourKids.xml")) { using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("YourKids.xml",FileMode.Open, store)) { var x = XElement.Load(stream); var t = new XElement("Child", new XElement("Name", pName), new XElement("FirstName", pFirstname) ); x.Add(t); x.Save(stream); stream.Close(); return; } } else { using (IsolatedStorageFileStream CreateIsf = new IsolatedStorageFileStream("YourKids.xml",FileMode.Create,store)) { var xDoc = new XElement("Kids", new XElement("Child", new XElement("Name", pName), new XElement("FirstName", pFirstname) ) ); xDoc.Save(CreateIsf); CreateIsf.Close(); return; } } } catch (Exception ex) { message = ex.Message; } Which gives me an xml file like this: <?xml version="1.0" encoding="utf-8"?> <Kids> <Child> <Name>test</Name> <FirstName>test</FirstName> </Child> </Kids><?xml version="1.0" encoding="utf-8"?> <Kids> <Child> <Name>test</Name> <FirstName>test</FirstName> </Child> <Child> <Name>testing</Name> <FirstName>testing</FirstName> </Child> </Kids> Which is still not correct, any ideas anyone ?
Initial xml file <?xml version="1.0" encoding="utf-8"?> <Kids> <Child> <Name>Kid1</Name> <FirstName>hisname</FirstName> </Child> </Kids> Following code add one new child to existing xml [Test] public void Test() { string filPath = #"YourKids.xml"; var root = XElement.Load(filPath); var newChild = new XElement("Child", new XElement("Name", "NewName"), new XElement("FirstName", "NewFirstName")); root.Add(newChild); root.Save(filPath); } Result xml file <?xml version="1.0" encoding="utf-8"?> <Kids> <Child> <Name>Kid1</Name> <FirstName>hisname</FirstName> </Child> <Child> <Name>NewName</Name> <FirstName>NewFirstName</FirstName> </Child> </Kids> Update Bug on save, you should set stream length to 0 Explanation After reader existing file, stream does not remove any data using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("YourKids.xml",FileMode.Open, store)) { var x = XElement.Load(stream); So when you call, data has been appended x.Save(stream); stream.Close(); Add stream.SetLength(0); before x.Save(stream); and all data will be overwritten. Here is full version if (store.FileExists("YourKids.xml")) { using (var stream = new IsolatedStorageFileStream("YourKids.xml", FileMode.Open, store)) { var x = XElement.Load(stream); var t = new XElement("Child", new XElement("Name", pName), new XElement("FirstName", pFirstname) ); x.Add(t); stream.SetLength(0); x.Save(stream); stream.Close(); } } else { using (var CreateIsf = new IsolatedStorageFileStream("YourKids.xml", FileMode.Create, store)) { var xDoc = new XElement("Kids", new XElement("Child", new XElement("Name", pName), new XElement("FirstName", pFirstname) ) ); xDoc.Save(CreateIsf); CreateIsf.Close(); } } Please note: I've removed return statements as useless. P.S. Take a look on resharper, it can improve code.