Search Results

Search found 235 results on 10 pages for 'rachel sparks'.

Page 10/10 | < Previous Page | 6 7 8 9 10 

  • How to avoid double divide in loop?

    - by ignaty
    Thank you for your help. My code looks like: var CatItems = ""; for(var x=0; x < data.PRODUCTS.length; x++) { if (x % 3 === 0) CatItems += '<li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-'+[x]+' jcarousel-item-'+[x]+'-horizontal jcarousel-item-placeholder jcarousel-item-placeholder-horizontal">'; CatItems += '<div><a class="large_image" href="#"><img src="'+ data.PRODUCTS[x].product_img +'" alt="' + data.PRODUCTS[x].product_name +'"></a><h3 class="geo_17_darkbrown">' + data.PRODUCTS[x].product_name +'</h3>'; if ( data.PRODUCTS[x].product_onsale==1 ) { CatItems += '<img alt="sale" src="assets/images/sale.gif" class="sale"><span class="geo_17_red_linethr">&pound;'+ data.PRODUCTS[x].product_retailprice +'</span>&nbsp;&nbsp;<span class="price geo_17_darkbrown">&pound;'+ data.PRODUCTS[x].product_webprice +'</span>'; } else { CatItems += '<span class="price geo_17_darkbrown">&pound;'+ data.PRODUCTS[x].product_webprice +'</span>'; } if ( data.PRODUCTS[x].product_COLOURS ) { CatItems += '<span class="colour">'; for(var y=0; y < data.PRODUCTS[x].product_COLOURS.length; y++) { CatItems += '<span><a href="'+ data.PRODUCTS[x].product_COLOURS[y].colours_large +'"><img src="'+ data.PRODUCTS[x].product_COLOURS[y].colours_thumb +'" alt="'+ data.PRODUCTS[x].product_COLOURS[y].colour_name +'" /></a></span>'; } CatItems += '</span>'; } CatItems += '</div>'; if (x % 3 === 2) CatItems += '</li>'; } and it generates this: <div class="carousel_00 jcarousel-container jcarousel-container-horizontal" style="position: relative; display: block;"> <div class="jcarousel-clip jcarousel-clip-horizontal" style="overflow: hidden; position: relative;"> <ul class="jcarousel-list jcarousel-list-horizontal" style="overflow: hidden; position: relative; top: 0px; left: 0px; margin: 0px; padding: 0px; width: 7890px;"> <li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-0 jcarousel-item-0-horizontal jcarousel-item-placeholder jcarousel-item-placeholder-horizontal"> <div> <a href="#" class="large_image"> <img alt="Elena Top" src="assets/images/dress1.gif"></a> <h3 class="geo_17_darkbrown">Elena Top</h3> <img class="sale" src="assets/images/sale.gif" alt="sale"> <span class="geo_17_red_linethr">£120 </span>&nbsp;&nbsp; <span class="price geo_17_darkbrown">£100 </span> <span class="colour"> <span> <a href="assets/images/colour.gif"> <img alt="Black" src="assets/images/black.gif"></a> </span> <span> <a href="assets/images/colour.gif"> <img alt="Brown" src="assets/images/brown.gif"></a> </span> <span> <a href="assets/images/colour.gif"> <img alt="Purple" src="assets/images/purple.gif"></a> </span> </span> </div> <div> <a href="#" class="large_image"> <img alt="Rachel Dress" src="assets/images/dress2.gif"></a> <h3 class="geo_17_darkbrown">Rachel Dress</h3> <span class="price geo_17_darkbrown">£120 </span> </div> <div> <a href="#" class="large_image"> <img alt="Elena Top" src="assets/images/dress3.gif"></a> <h3 class="geo_17_darkbrown">Elena Top</h3> <span class="price geo_17_darkbrown">£120 </span> </div> </li> <li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-1 jcarousel-item-1-horizontal jcarousel-item-placeholder jcarousel-item-placeholder-horizontal" style="float: left; list-style: none outside none;" jcarouselindex="1"> </li> <li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-3 jcarousel-item-3-horizontal jcarousel-item-placeholder jcarousel-item-placeholder-horizontal"> <div> <a href="#" class="large_image"> <img alt="Elena Top" src="assets/images/dress1.gif"></a> <h3 class="geo_17_darkbrown">Elena Top</h3> <span class="price geo_17_darkbrown">£120 </span> </div> <div> <a href="#" class="large_image"> <img alt="Elena Top" src="assets/images/dress2.gif"></a> <h3 class="geo_17_darkbrown">Elena Top</h3> <span class="price geo_17_darkbrown">£120 </span> </div> <div> <a href="#" class="large_image"> <img alt="Elena Top" src="assets/images/dress3.gif"></a> <h3 class="geo_17_darkbrown">Elena Top</h3> <span class="price geo_17_darkbrown">£120 </span> </div> </li> <li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-6 jcarousel-item-6-horizontal jcarousel-item-placeholder jcarousel-item-placeholder-horizontal"> <div> <a href="#" class="large_image"> <img alt="Elena Top" src="assets/images/dress3.gif"></a> <h3 class="geo_17_darkbrown">Elena Top</h3> <span class="price geo_17_darkbrown">£120 </span> </div> <div> <a href="#" class="large_image"> <img alt="Elena Top" src="assets/images/dress3.gif"></a> <h3 class="geo_17_darkbrown">Elena Top</h3> <span class="price geo_17_darkbrown">£120 </span> </div> </li> </ul> </div> <div class="jcarousel-prev jcarousel-prev-horizontal jcarousel-prev-disabled jcarousel-prev-disabled-horizontal" style="display: block;" disabled="true"> </div> <div class="jcarousel-next jcarousel-next-horizontal" style="display: block;" disabled="false"> </div> <div class="jcarousel-control geo_10_darkbrown_capital"> 7 products&nbsp;&nbsp;&nbsp; <a href="#">1</a> <a href="#">2</a> <a href="#">3</a> <a href="#">4</a> <a href="#">5</a> <a href="#">6</a> <a href="#" class="last">7</a> </div> </div> It works like it should, put every 3 div's in li. but I have another problem with divide. It divide "x" inside the loop. For example in JS: <li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-'+[x]+' jcarousel-item-'+[x]+'-horizontal jcarousel-item-placeholder jcarousel-item-placeholder-horizontal"> And HTML out is: <li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-0 jcarousel-item-0-horizontal jcarousel-item-placeholder jcarousel-item-placeholder-horizontal"></li> then <li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-3 jcarousel-item-3-horizontal jcarousel-item-placeholder jcarousel-item-placeholder-horizontal"></li> then <li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-6 jcarousel-item-6-horizontal jcarousel-item-placeholder jcarousel-item-placeholder-horizontal"></li> etc... What I need is that count goes as 0-1-2-3-4-5-etc, but with divide it goes 0-3-6-etc and jCarousel insert blank li's 1-2, 4-5, 7-8. How I can avoid "x" divide inside the loop? Tnak you!

    Read the article

  • How do I sanitize a string in PHP that contains "; Echo"? (I have a solid reason)

    - by user337878
    I turned this case into a simple PHP page that submits to itself. My issue is that I am submitting track meet results and one of the girl's names is Echo...a lovely name. The problem text I'm submitting is: Pole vault - Rachel Simons, Tow, 8-6; Echo Wilson, Cit, 8-0; Molly Randall, Tow, 7-0; So you see a semicolon followed by white space followed by Echo... After submitting, it says: POST to /results/test.php not supported The end goal is to save it to a database along with some other info and have a search page to find it and simply print out the full result on the screen. I stripped out all my database stuff to get it down to this one error. I mean, I can intentionally mis-spell her name, but there's gotta be a way around this, right??? Here's the test PHP file. <html> <head> <title>title</title> </head> <body> <?php echo "<h3>Edit meet info below</h3>"; echo "<form action=\"test.php\" method=\"post\" id=\"submitForm\">"; echo "Full Results:<br/><textarea NAME=\"results\" id=\"results\" rows=\"20\" cols=\"80\" MAXLENGTH=\"8191\"></textarea><br/><br/>"; echo "<input type=\"submit\" name=\"submitMeet\" value=\"Submit\">"; echo "</form>"; ?> </body> </html>

    Read the article

  • Colorizing as SAS Map

    - by user601828
    I'm trying to generate a map in SAS where I would like to to make gradual color changes which correspond to my results. So the higher the counts the more intense the color changes. Also I would like to add state labels to the map. Here is my code, so far it produces a white map with varying degress of blue blocks. I'd like the states colored in intense colors, like red, bright pink,brilliant, blues and greens. Can anyone please help me modify the code to add state labels and colorize the map, and below the map add a table summarizing the statistics, like counts and percentages. Thanks in advance. goptions gunit=pct cback=white htitle=4 htext=3 colors=(PAGY LIY STY DEGY dark_yellow very_dark_yellow ) ; title "My Map Results"; proc gmap map=maps.us data=My_data all; id state; block person_per_event/levels=6; choro person_per_event/levels=6; run; quit; I looked at his page before for example if I wanted to make a map like this one http://robslink.com/SAS/democd61/election_2012.htm with my data. I tried modifying the code that he gives on the link, but wasnt very successful. I would like to use that map along with the state labels and keep the colors and represent my data with blocks in the corresponding locations with city and state, and high level counts. The rest of the summary statistics I would like to summarize in a colorful table next to the map, like a dashboard of sorts. Appreciate any help in advance. Thanks, -rachel

    Read the article

  • Limiting Audit Exposure and Managing Risk – Q&A and Follow-Up Conversation

    - by Tanu Sood
    Thanks to all who attended the live ISACA webcast on Limiting Audit Exposure and Managing Risk with Metrics-Driven Identity Analytics. We were really fortunate to have Don Sparks from ISACA moderate the webcast featuring Stuart Lincoln, Vice President, IT P&L Client Services, BNP Paribas, North America and Neil Gandhi, Principal Product Manager, Oracle Identity Analytics. Stuart’s insights given the team’s role in providing IT for P&L Client Services and his tremendous experience in identity management and establishing sustainable compliance programs were true value-add at yesterday’s webcast. And if you are a healthcare organization looking to solve your compliance and security challenges, we recommend you join us for a live webcast on Tuesday, November 29 at 10 am PT. The webcast will feature experts from Kaiser Permanente, PricewaterhouseCoopers and Oracle and the focus of the discussion will be around the compliance challenges a healthcare organization faces and best practices for tackling those. Here are the details: Healthcare IT News Webcast: Managing Risk and Enforcing Compliance in Healthcare with Identity Analytics Tuesday, November 29, 201110:00 a.m. PT / 1:00 p.m. ET Register Today The ISACA webcast replay is now available on-demand and the slides are also available for download. Since we didn’t have time to address all the questions we received during the live Q&A portion of the webcast, we have captured responses to the remaining questions here. Please continue to provide us your feedback and insights from your experience in deploying identity compliance solutions. Q. Can you please clarify the mechanism utilized to populate the Identity Warehouse from each individual application's access management function / files? A. Oracle Identity Analytics (OIA) supports direct imports from applications. Data collection is based on Extract, Transform and Load (ETL) that eliminates the need to write connectors to different applications. Oracle Identity Analytics’ import engine supports complex entitlement feeds saved as either text files or XML. The imports can be scheduled on a periodic basis or triggered as needed. If the applications are synchronized with a user provisioning solution like Oracle Identity Manager, Oracle Identity Analytics has a seamless integration to pull in data from Oracle Identity Manager. Q.  Can you provide a short summary of the new features in your latest release of Oracle Identity Analytics? A. Oracle recently announced availability of enhanced Oracle Identity Analytics. This release focused on easing the certification process by offering risk analytics driven certification, advanced certification screens, business centric views and significant improvement in performance including 3X faster data imports, 3X faster certification campaign generation and advanced auto-certification features, that  will allow organizations to improve user productivity by up to 80%. Closed-loop risk feedback and IT policy monitoring with Oracle Identity Manager, a leading user provisioning solution, allows for more accurate certification reviews. And, OIA's improved performance enables customers to scale compliance initiatives supporting millions of user entitlements across thousands of applications, whether on premise or in the cloud, without compromising speed or integrity. Q. Will ISACA grant a CPE credit for attending this ISACA-sponsored webinar today? A. From ISACA: Hello and thank you for your interest in the 2011 ISACA Webinar Program!  Unfortunately, there are no CPEs offered for this program, archived or live.  We will be looking into the feasibility of offering them in the future.  Q. Would you be able to use this to help manage licenses for software? That is to say - could it track software that is not used by a user, thus eliminating the software license? A. OIA’s integration with Oracle Identity Manager, a leading user provisioning solution, allows organizations to detect ghost accounts or unused accounts via account reconciliation. Based on company’s policies, this could trigger an automated workflow for account deletion or asking for further investigation. Closed-loop feedback between the two solutions would then allow visibility into the complete audit trail of when the account was detected, the action taken, by whom, when and the current status. Q. We have quarterly attestations and .xls mechanisms are not working. Once the identity data is correlated in Identity Analytics, do you then automate access certification? A. OIA’s identity warehouse analyzes and correlates identity data across various resources that allows OIA to determine a user’s risk profile, who the access review request should go to, along with all the relevant access details of the user. The access certification manager gets notification on what to review, when and the relevant data is presented in a business friendly screen. Based on the result of the access certification process, actions are triggered and results recorded and archived. Access review managers have visual risk indicators that also allow them to prioritize access certification tasks and efforts. Q. How does Oracle Identity Analytics work with Cloud Security? A. For enterprises looking to build their own cloud(s), Oracle offers a set of security services that cloud developers can leverage including Oracle Identity Analytics.  For enterprises looking to manage their compliance requirements but without hosting those in-house and instead having a hosting provider offer managed Identity Management services to the organizations, Oracle Identity Analytics can be leveraged much the same way as you’d in an on-premise (within the enterprise) environment. In fact, organizations today are leveraging Oracle Identity Analytics to manage identity compliance in both these ways. Q. Would you recommend this as a cost effective solution for a smaller organization with @ 2,500 users? A. The key return-on-investment (ROI) on Oracle Identity Analytics is derived from automating compliance processes thereby eliminating administrative overhead, minimizing errors, maintaining cost- and time-effective sustainable compliance processes and minimizing audit exposures and penalties.  Of course, there are other tangible benefits that are derived from an Oracle Identity Analytics implementation as outlined in the webcast. For a quantitative analysis of your requirements and potential ROI calculation, we recommend you refer to the Forrester Study on Total Economic Impact of Oracle Identity Analytics. For an in-person discussion, please email Richard Caldwell.

    Read the article

  • Silverlight Cream for January 11, 2011 -- #1024

    - by Dave Campbell
    1,000 blogposts is quite a few, but to die-hard geeks, 1000 isn't the number... 1K is the number, and today is my 1K blogpost! I've been working up to this for at least 11 months. Way back at MIX10, I approached some vendors about an idea I had. A month ago I contacted them and others, and everyone I contacted was very generous and supportive of my idea. My idea was not to run a contest, but blog as normal, and whoever ended up on my 1K post would get some swag... and I set a cut-off at 13 posts. So... blogging normally, I had some submittals, and then ran my normal process to pick up the next posts until I hit a total of 13. To provide a distribution channel for the swag, everyone on the list, please send me your snail mail (T-shirts) and email (licenses) addresses as soon as possible.   I'd like to thank the following generous sponsors for their contributions to my fun (in alphabetic order): and Rachel Hawley for contributing 4 Silverlight control sets First Floor Software and Koen Zwikstra for contributing 13 licenses for Silverlight Spy and Sara Faatz/Jason Beres for contributing 13 licenses for Silverlight Data Visualization controls and Svetla Stoycheva for contributing T-Shirts for everyone on the post and Ina Tontcheva for contributing 13 licenses for RadControls for Silverlight + RadControls for Windows Phone and Charlene Kozlan for contributing 1 combopack standard, 2 DataGrid for Silverlight, and 2 Listbox for Silverlight Standard And now finally...in this Issue: Nigel Sampson, Jeremy Likness, Dan Wahlin, Kunal Chowdhurry, Alex Knight, Wei-Meng Lee, Michael Crump, Jesse Liberty, Peter Kuhn, Michael Washington, Tau Sick, Max Paulousky, Damian Schenkelman Above the Fold: Silverlight: "Demystifying Silverlight Dependency Properties" Dan Wahlin WP7: "Using Windows Phone Gestures as Triggers" Nigel Sampson Expression Blend: "PathListBox: making data look cool" Alex Knight From SilverlightCream.com: Using Windows Phone Gestures as Triggers Nigel Sampson blogged about WP7 Gestures, the Toolkit, and using Gestures as Triggers, and actually makes it looks simple :) Jounce Part 9: Static and Dynamic Module Management Jeremy Likness has episode 9 of his explanation of his MVVM framework, Jounce, up... and a big discussion of Modules and Module Management from a Jounce perspective. Demystifying Silverlight Dependency Properties Dan Wahlin takes a page from one of his teaching opportunities, and shares his knowledge of Dependency Properties with us... beginning with what they are, defining them in code, and demonstrating their use. Customizing Silverlight ChildWindow Style using Blend Kunal Chowdhurry has a great post up about getting your Child Windows to match the look & feel of the rest of youra app... plus a bunch of Blend goodness thrown in. PathListBox: making data look cool File this post by Alex Knight in the 'holy crap' file along with the others in this series! ... just check out that cool Ticker Style Path ListBox at the top of the blog... too cool! Web Access in Windows Phone 7 Apps Wei-Meng Lee has the 3rd part of his series on WP7 development up and in this one is discussing Web Access... I mean *discussing* it... tons of detail, code, and explanation... great post. Prevent your Silverlight XAP file from caching in your browser. Michael Crump helps relieve stress on Silverlight developers everywhere by exploring how to avoid caching of your XAP in the browser... (WPFS) MVVM Light Toolkit: Soup To Nuts Part I Jesse Liberty continues his Windows Phone from Scratch series with a new segment exploring Laurent Bugnion's MVVMLight Toolkit beginning with acquiring and installing the toolkit, then proceeds to discuss linking the View and ViewModel, the ViewModel Locator, and page navigation. Silverlight: Making a DateTimePicker Peter Kuhn attacks a problem that crops up on the forums a lot -- a DateTimePicker control for Silverlight... following the "It's so simple to build one yourself" advice, he did so, and provides the code for all of us! Windows Phone 7 Animated Button Press Michael Washington took exception to button presses that gave no visual feedback and produced a behavior that does just that. Using TweetSharp in a Windows Phone 7 app Tau Sick demonstrates using TweetSharp to put a twitter feed into a WP7 app, as he did in "Hangover Helper"... all the instructions from getting Tweeetshaprt to the code necessary. Bindable Application Bar Extensions for Windows Phone 7 Max Paulousky has a post discussing some real extensions to the ApplicationBar for WP7.. he begins with a bindable application bar by Nicolas Humann that I've missed, probably because his blog is in French... and extends it to allow using DelegateCommand. How to: Load Prism modules packaged in a separate XAP file in an OOB application Damian Schenkelman posts about Prism, AppModules in separate XAPs and running OOB... if you've tried this, you know it's a hassle.. Damian has the solution. Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • Community Branching

    - by Dane Morgridge
    As some may have noticed, I have taken a liking to Ruby (and Rails in particular) quite a bit recently. This last weekend I spoke at the NYC Code Camp on a comparison of ASP.NET and Rails as well as an intro to Entity Framework talk.  I am speaking at RubyNation in April and have submitted to other ruby conferences around the area and I am also doing a Rails and MongoDB talk at the Philly Code Camp in April. Before you start to think this is my "I'm leaving .NET post", which it isn't so I need to clarify. I am not, nor do I intend to any time in the near future plan on abandoning .NET.  I am simply branching out into another community based on a development technology that I very much enjoy.  If you look at my twitter bio, you will see that I am into Entity Framework, Ruby on Rails, C++ and ASP.NET MVC, and not necessarily in that order.  I know you're probably thinking to your self that I am crazy, which is probably true on several levels (especially the C++ part). I was actually crazy enough at the NYC Code Camp to show up wearing a Linux t-shirt, presenting with my MacBook Pro on Entity Framework, ASP.NET MVC and Rails. (I did get pelted in the head with candy by Rachel Appel for it though) At all of the code camps I am submitting to this year, i will be submitting sessions on likely all four topics, and some sessions will be a combination of 2 or more.  For example, my "ASP.NET MVC: A Gateway To Rails?" talk touches ASP.NET MVC, Entity Framework Code First and Rails. Simply put (and I talk about this in my MVC & Rails talk) is that learning and using Rails has made me a better ASP.NET MVC developer. Just one example of this is helper methods.  When I started working with ASP.NET MVC, I didn't really want to use helpers and preferred to just use standard html tags, especially where links were concerned.  It was just me being stubborn and not really seeing all of the benefit of the helpers.  To my defense, coming from WebForms, I wanted to be as bare metal as possible and it seemed at first like a lot of the helpers were an unnecessary abstraction. I took my first look at Rails back in v1 and didn't spend very much time with it so I dismissed it and went on my merry ASP.NET WebForms way.  Then I picked up ASP.NET MVC and grasped the MVC pattern itself much better. After this, I took another look at Rails and everything made sense.  I decided then to learn Rails. (I think it is important for developers to learn new languages and platforms regularly so it was a natural progression for me) I wanted to learn it the right way, so when I dug into code, everyone used helpers everywhere for pretty much everything possible. I took some time to dig in and found out how helpful they were and subsequently realized how awesome they were in ASP.NET MVC also and started using them. In short, I love Rails (and Ruby in general).  I also love ASP.NET MVC and Entity Framework and yes I still love C++.  I have varying degrees of love for them individually at any given moment and it is likely to shift based on the current project I am working on.  I know you're thinking it so before you ask the question. "Which do I use when?", I'm going to give the standard developer answer of: It depends.  There are a lot of factors that I am not going to even go into that would go into a decision.  The most basic question I would ask though is,  does this project depend on .NET?  If it does, then I'd say that ASP.NET MVC is probably going to be the more logical choice and I am going to leave it at that.  I am working on projects right now in both technologies and I don't see that changing anytime soon (one project even uses both). With all that being said, you'll find me at code camps, conferences and user groups presenting on .NET, Ruby or both, writing about .NET and Ruby and I will likely be blogging on both in the future.  I know of others that have successfully branched out to other communities and with any luck I'll be successful at it too. On a (sorta) side note, I read a post by Justin Etheredge the other day that pretty much sums up my feelings about Ruby as a language.  I highly recommend checking it out: What Is So Great About Ruby?

    Read the article

  • Wishful Thinking: Why can't HTML fix Script Attacks at the Source?

    - by Rick Strahl
    The Web can be an evil place, especially if you're a Web Developer blissfully unaware of Cross Site Script Attacks (XSS). Even if you are aware of XSS in all of its insidious forms, it's extremely complex to deal with all the issues if you're taking user input and you're actually allowing users to post raw HTML into an application. I'm dealing with this again today in a Web application where legacy data contains raw HTML that has to be displayed and users ask for the ability to use raw HTML as input for listings. The first line of defense of course is: Just say no to HTML input from users. If you don't allow HTML input directly and use HTML Encoding (HttyUtility.HtmlEncode() in .NET or using standard ASP.NET MVC output @Model.Content) you're fairly safe at least from the HTML input provided. Both WebForms and Razor support HtmlEncoded content, although Razor makes it the default. In Razor the default @ expression syntax:@Model.UserContent automatically produces HTML encoded content - you actually have to go out of your way to create raw HTML content (safe by default) using @Html.Raw() or the HtmlString class. In Web Forms (V4) you can use:<%: Model.UserContent %> or if you're using a version prior to 4.0:<%= HttpUtility.HtmlEncode(Model.UserContent) %> This works great as a hedge against embedded <script> tags and HTML markup as any HTML is turned into text that displays as HTML but doesn't render the HTML. But it turns any embedded HTML markup tags into plain text. If you need to display HTML in raw form with the markup tags rendering based on user input this approach is worthless. If you do accept HTML input and need to echo the rendered HTML input back, the task of cleaning up that HTML is a complex task. In the projects I work on, customers are frequently asking for the ability to post raw HTML quite frequently.  Almost every app that I've built where there's document content from users we start out with text only input - possibly using something like MarkDown - but inevitably users want to just post plain old HTML they created in some other rich editing application. See this a lot with realtors especially who often want to reuse their postings easily in multiple places. In my work this is a common problem I need to deal with and I've tried dozens of different methods from sanitizing, simple rejection of input to custom markup schemes none of which have ever felt comfortable to me. They work in a half assed, hacked together sort of way but I always live in fear of missing something vital which is *really easy to do*. My Wishlist Item: A <restricted> tag in HTML Let me dream here for a second on how to address this problem. It seems to me the easiest place where this can be fixed is: In the browser. Browsers are actually executing script code so they have a lot of control over the script code that resides in a page. What if there was a way to specify that you want to turn off script code for a block of HTML? The main issue when dealing with HTML raw input isn't that we as developers are unaware of the implications of user input, but the fact that we sometimes have to display raw HTML input the user provides. So the problem markup is usually isolated in only a very specific part of the document. So, what if we had a way to specify that in any given HTML block, no script code could execute by wrapping it into a tag that disables all script functionality in the browser? This would include <script> tags and any document script attributes like onclick, onfocus etc. and potentially also disallow things like iFrames that can potentially be scripted from the within the iFrame's target. I'd like to see something along these lines:<article> <restricted allowscripts="no" allowiframes="no"> <div>Some content</div> <script>alert('go ahead make my day, punk!");</script> <div onfocus="$.getJson('http://evilsite.com/')">more content</div> </restricted> </article> A tag like this would basically disallow all script code from firing from any HTML that's rendered within it. You'd use this only on code that you actually render from your data only and only if you are dealing with custom data. So something like this:<article> <restricted> @Html.Raw(Model.UserContent) </restricted> </article> For browsers this would actually be easy to intercept. They render the DOM and control loading and execution of scripts that are loaded through it. All the browser would have to do is suspend execution of <script> tags and not hookup any event handlers defined via markup in this block. Given all the crazy XSS attacks that exist and the prevalence of this problem this would go a long way towards preventing at least coded script attacks in the DOM. And it seems like a totally doable solution that wouldn't be very difficult to implement by vendors. There would also need to be some logic in the parser to not allow an </restricted> or <restricted> tag into the content as to short-circuit the rstricted section (per James Hart's comment). I'm sure there are other issues to consider as well that I didn't think of in my off-the-back-of-a-napkin concept here but the idea overall seems worth consideration I think. Without code running in a user supplied HTML block it'd be pretty hard to compromise a local HTML document and pass information like Cookies to a server. Or even send data to a server period. Short of an iFrame that can access the parent frame (which is another restriction that should be available on this <restricted> tag) that could potentially communicate back, there's not a lot a malicious site could do. The HTML could still 'phone home' via image links and href links potentially and basically say this site was accessed, but without the ability to run script code it would be pretty tough to pass along critical information to the server beyond that. Ahhhh… one can dream… Not holding my breath of course. The design by committee that is the W3C can't agree on anything in timeframes measured less than decades, but maybe this is one place where browser vendors can actually step up the pressure. This is something in their best interest to reduce the attack surface for vulnerabilities on their browser platforms significantly. Several people commented on Twitter today that there isn't enough discussion on issues like this that address serious needs in the web browser space. Realistically security has to be a number one concern with Web applications in general - there isn't a Web app out there that is not vulnerable. And yet nothing has been done to address these security issues even though there might be relatively easy solutions to make this happen. It'll take time, and it's probably not going to happen in our lifetime, but maybe this rambling thought sparks some ideas on how this sort of restriction can get into browsers in some way in the future.© Rick Strahl, West Wind Technologies, 2005-2012Posted in ASP.NET  HTML5  HTML  Security   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • How do I add a toolbar to a region with ExtJS

    - by gargantaun
    I have a border layout in ExtJS, The north region contains some HTML, but also needs to contain a toolbar like this... So i've managed to get the border layout set up, added the html to the North Region of the layout, but I can't find any workable examples of how to implement a tool bar. I have found lot's of examples of toolbars on their own, but I've not got the luxury or learning ExtJs thoroughly so it's all greek to me. I suspect there's a way to define a tool bar outside of the cumbersome JSON style flow of creating a layout and somehow attaching it to the region, and I'm hoping it's relativley simple to do. If someone can explain how I'd do this, it would really help. Here's the code so far... //make sure YOUR path is correct to this image!! Ext.BLANK_IMAGE_URL = '../../ext-2.0.2/resources/images/default/s.gif'; //this runs on DOM load - you can access all the good stuff now. Ext.onReady(function(){ var viewport = new Ext.Viewport({ layout: "border", border: false, renderTo: Ext.getBody(), items: [ // ------------------------------------------------------------------ { region: "north", id : "toolbar-area", xtype: 'panel', html: [ "<div id=\"html-header\">", "<div id=\"council-logo\"></div>", "<ul id=\"ancillary-menu\">", "<li><a href=\"#\">Logout</a></li>", "<li><a href=\"#\">Gazeteer Home</a></li>", "<li>Hello Rachel</li>", "</ul>", "<img id=\"inteligent-logo\" src=\"applied-images/logos/inteligent.gif\">", "</div>" ], /* ++++++++++++++++++++++++++++++++++++++++++++ */ /* The toolbar needs to go around here.... */ /* ++++++++++++++++++++++++++++++++++++++++++++ */ height: 100 }, // ------------------------------------------------------------------ // WEST // ------------------------------------------------------------------ { region: 'west', xtype: 'panel', split: true, resizeable: false, maxWidth : 350, minWidth : 349, collapsible: true, title: 'Gazetteer Explorer', width: 350, minSize: 150, // -------------------------------------------------------------- title: 'Nested Layout', layout: 'border', border: false, id: "west", items: [ { // *********************************************** // Search Form // *********************************************** region : "north", height: 300, split : true, id : "left-form-panel", items : [{ xtype : "form", id : "search-form", items : [ // Authority combo box // =============================== { xtype : "combo", fieldLabel : "Authority", name : "authority", hiddenName : "authority", id : "authority-combo" }, // =============================== // Search Fieldset // =============================== { xtype : "fieldset", autoHeight : true, title : "Search by...", id : "search-fieldset", items : [ // Ref Number text Box // %%%%%%%%%%%%%%%% { xtype : "textfield", name : "ref-number", fieldLabel : "Ref. Number", id : "ref-number-textfield" }, // %%%%%%%%%%%%%%%% // Streetname Combo // %%%%%%%%%%%%%%% { xtype : "combo", name : "street-name", hiddenName : "street-name", fieldLabel : "Street Name", id : "street-name-combo" }, // %%%%%%%%%%%%%%%% // Postcode Combo // %%%%%%%%%%%%%%%% { xtype : "combo", name : "postcode", hiddenName : "postcode", fieldLabel : "Postcode", id : "postcode-combo" }, // %%%%%%%%%%%%%%%% // Postcode Combo // %%%%%%%%%%%%%%%% { xtype : "combo", name : "town", hiddenName : "town", fieldLabel : "Town", id : "towm-combo" }, // %%%%%%%%%%%%%%%% // Postcode Combo // %%%%%%%%%%%%%%%% { xtype : "combo", name : "locality", hiddenName : "locality", fieldLabel : "Locality", id : "locality-combo" }, // %%%%%%%%%%%%%%% // Search Button // %%%%%%%%%%%%%%%% { xtype : "button", text : "Search", id : "search-button" }, // Reset Button // %%%%%%%%%%%%%%% { xtype : "button", text : "Reset", id : "reset-button" } ] }, // ======================= ] }] // ********************************************* }, { region: 'center', html: 'Tree view goes here' } ] }, // ------------------------------------------------------------------ { region: 'center', xtype: 'panel', // -------------------------------------------------------------- layout: 'border', border: false, items: [ { region: 'center', height: 200, split: true, html: 'Map goes here' }, { region: 'south', title: "Selection", split: true, height: 200, collapsible: true, html: 'Nested Center' } ] }, // ------------------------------------------------------------------ { region: 'east', }, // ------------------------------------------------------------------ { region: 'south', }] }); }); Sorry there's so much code, but ExtJS makes me scared to touch anything that's working.

    Read the article

  • Hundreds of unknown entries in Linux logwatch

    - by Saif Bechan
    I have a dedicated server which runs centos. Today i got an email from loginwatch on my server with hundreds of lines of 'errors'. I don't really know what they are becasue i am fairly new at this. The lines are in a few sections, I will display the first 10 of all of them, i hope someone can help me fix these problems. --------------------- Named Begin ------------------------ **Unmatched Entries** client 216.146.46.136 notify question section contains no SOA: 8 Time(s) client 92.114.98.10 query (cache) 'adobe.com/A/IN' denied: 4 Time(s) network unreachable resolving '11.254.75.75.in-addr.arpa/PTR/IN': 2001:7fd::1#53: 1 Time(s) network unreachable resolving '136.176.97.93.in-addr.arpa/PTR/IN': 2001:13c7:7002:3000::11#53: 1 Time(s) network unreachable resolving '136.176.97.93.in-addr.arpa/PTR/IN': 2001:500:13::c7d4:35#53: 1 Time(s) network unreachable resolving '136.176.97.93.in-addr.arpa/PTR/IN': 2001:500:2e::1#53: 2 Time(s) network unreachable resolving '136.176.97.93.in-addr.arpa/PTR/IN': 2001:610:240:0:53::193#53: 1 Time(s) network unreachable resolving '136.176.97.93.in-addr.arpa/PTR/IN': 2001:610:240:0:53::3#53: 1 Time(s) network unreachable resolving '136.176.97.93.in-addr.arpa/PTR/IN': 2001:660:3006:1::1:1#53: 1 Time(s) network unreachable resolving '136.176.97.93.in-addr.arpa/PTR/IN': 2001:6b0:7::2#53: 1 Time(s) network unreachable resolving '136.176.97.93.in-addr.arpa/PTR/IN': 2001:dc0:1:0:4777::140#53: 1 Time(s) network unreachable resolving '136.176.97.93.in-addr.arpa/PTR/IN': 2001:dc0:2001:a:4608::59#53: 1 Time(s) network unreachable resolving '146.250.19.67.in-addr.arpa/PTR/IN': 2001:5a0:10::2#53: 1 Time(s) network unreachable resolving '149.207.106.87.in-addr.arpa/PTR/IN': 2001:7fd::1#53: 1 Time(s) network unreachable resolving '178.62.24.195.in-addr.arpa/PTR/IN': 2001:7fd::1#53: 1 Time(s) this goes on for hundreds of lines with all different domain names. --------------------- pam_unix Begin ------------------------ Failed logins from: 78.86.126.211 (78-86-126-211.zone2.bethere.co.uk): 111 times 93.97.176.136 (93-97-176-136.dsl.cnl.uk.net): 113 times 121.14.145.32: 136 times 190.152.69.5: 248 times 209.160.72.15: 572 times 210.26.48.35: 2 times 212.235.111.224 (DSL212-235-111-224.bb.netvision.net.il): 140 times 218.206.25.29: 140 times Illegal users from: 78.86.126.211 (78-86-126-211.zone2.bethere.co.uk): 2665 times 93.97.176.136 (93-97-176-136.dsl.cnl.uk.net): 2539 times 121.14.145.32: 116 times 190.152.69.5: 34 times 209.160.72.15: 324 times 218.206.25.29: 8051 times proftpd: Unknown Entries: session opened for user cent_ftp by (uid=0): 15 Time(s) session closed for user cent_ftp: 14 Time(s) sshd: Authentication Failures: unknown (218.206.25.29): 8051 Time(s) unknown (78-86-126-211.zone2.bethere.co.uk): 2665 Time(s) unknown (93.97.176.136): 2539 Time(s) root (209.160.72.15): 558 Time(s) unknown (209.160.72.15): 324 Time(s) root (190.152.69.5): 246 Time(s) unknown (121.14.145.32): 116 Time(s) root (121.14.145.32): 106 Time(s) root (dsl212-235-111-224.bb.netvision.net.il): 70 Time(s) root (93.97.176.136): 44 Time(s) root (78-86-126-211.zone2.bethere.co.uk): 37 Time(s) unknown (190.152.69.5): 34 Time(s) mysql (121.14.145.32): 30 Time(s) nobody (218.206.25.29): 26 Time(s) mail (218.206.25.29): 24 Time(s) news (218.206.25.29): 24 Time(s) root (218.206.25.29): 24 Time(s) --------------------- SSHD Begin ------------------------ **Unmatched Entries** pam_succeed_if(sshd:auth): error retrieving information about user tavi : 2 time(s) pam_succeed_if(sshd:auth): error retrieving information about user pam : 2 time(s) pam_succeed_if(sshd:auth): error retrieving information about user konchog : 1 time(s) pam_succeed_if(sshd:auth): error retrieving information about user stavrum : 2 time(s) pam_succeed_if(sshd:auth): error retrieving information about user rachel : 1 time(s) pam_succeed_if(sshd:auth): error retrieving information about user affiliates : 24 time(s) pam_succeed_if(sshd:auth): error retrieving information about user nen : 1 time(s) pam_succeed_if(sshd:auth): error retrieving information about user cobra : 1 time(s) pam_succeed_if(sshd:auth): error retrieving information about user pass : 7 time(s) pam_succeed_if(sshd:auth): error retrieving information about user hacer : 1 time(s) pam_succeed_if(sshd:auth): error retrieving information about user chung : 1 time(s) pam_succeed_if(sshd:auth): error retrieving information about user zainee : 1 time(s) pam_succeed_if(sshd:auth): error retrieving information about user radu : 2 time(s) pam_succeed_if(sshd:auth): error retrieving information about user alka : 4 time(s) pam_succeed_if(sshd:auth): error retrieving information about user albert : 5 time(s) pam_succeed_if(sshd:auth): error retrieving information about user turcia : 2 time(s) pam_succeed_if(sshd:auth): error retrieving information about user cordell : 2 time(s) pam_succeed_if(sshd:auth): error retrieving information about user silver : 2 time(s) pam_succeed_if(sshd:auth): error retrieving information about user dragon : 3 time(s) If someone wants to see the whole log i can upload it somewhere. Am i being hacked, what is this all?? I hope someone can help me, this does not look good at all.

    Read the article

  • Building a better mouse-trap &ndash; Improving the creation of XML Message Requests using Reflection, XML &amp; XSLT

    - by paulschapman
    Introduction The way I previously created messages to send to the GovTalk service I used the XMLDocument to create the request. While this worked it left a number of problems; not least that for every message a special function would need to created. This is OK for the short term but the biggest cost in any software project is maintenance and this would be a headache to maintain. So the following is a somewhat better way of achieving the same thing. For the purposes of this article I am going to be using the CompanyNumberSearch request of the GovTalk service – although this technique would work for any service that accepted XML. The C# functions which send and receive the messages remain the same. The magic sauce in this is the XSLT which defines the structure of the request, and the use of objects in conjunction with reflection to provide the content. It is a bit like Sweet Chilli Sauce added to Chicken on a bed of rice. So on to the Sweet Chilli Sauce The Sweet Chilli Sauce The request to search for a company based on it’s number is as follows; <GovTalkMessage xsi:schemaLocation="http://www.govtalk.gov.uk/CM/envelope http://xmlgw.companieshouse.gov.uk/v1-0/schema/Egov_ch-v2-0.xsd" xmlns="http://www.govtalk.gov.uk/CM/envelope" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:gt="http://www.govtalk.gov.uk/schemas/govtalk/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > <EnvelopeVersion>1.0</EnvelopeVersion> <Header> <MessageDetails> <Class>NumberSearch</Class> <Qualifier>request</Qualifier> <TransactionID>1</TransactionID> </MessageDetails> <SenderDetails> <IDAuthentication> <SenderID>????????????????????????????????</SenderID> <Authentication> <Method>CHMD5</Method> <Value>????????????????????????????????</Value> </Authentication> </IDAuthentication> </SenderDetails> </Header> <GovTalkDetails> <Keys/> </GovTalkDetails> <Body> <NumberSearchRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://xmlgw.companieshouse.gov.uk/v1-0/schema/NumberSearch.xsd"> <PartialCompanyNumber>99999999</PartialCompanyNumber> <DataSet>LIVE</DataSet> <SearchRows>1</SearchRows> </NumberSearchRequest> </Body> </GovTalkMessage> This is the XML that we send to the GovTalk Service and we get back a list of companies that match the criteria passed A message is structured in two parts; The envelope which identifies the person sending the request, with the name of the request, and the body which gives the detail of the company we are looking for. The Chilli What makes it possible is the use of XSLT to define the message – and serialization to convert each request object into XML. To start we need to create an object which will represent the contents of the message we are sending. However there is a common properties in all the messages that we send to Companies House. These properties are as follows SenderId – the id of the person sending the message SenderPassword – the password associated with Id TransactionId – Unique identifier for the message AuthenticationValue – authenticates the request Because these properties are unique to the Companies House message, and because they are shared with all messages they are perfect candidates for a base class. The class is as follows; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using Microsoft.WindowsAzure.ServiceRuntime; namespace CompanyHub.Services { public class GovTalkRequest { public GovTalkRequest() { try { SenderID = RoleEnvironment.GetConfigurationSettingValue("SenderId"); SenderPassword = RoleEnvironment.GetConfigurationSettingValue("SenderPassword"); TransactionId = DateTime.Now.Ticks.ToString(); AuthenticationValue = EncodePassword(String.Format("{0}{1}{2}", SenderID, SenderPassword, TransactionId)); } catch (System.Exception ex) { throw ex; } } /// <summary> /// returns the Sender ID to be used when communicating with the GovTalk Service /// </summary> public String SenderID { get; set; } /// <summary> /// return the password to be used when communicating with the GovTalk Service /// </summary> public String SenderPassword { get; set; } // end SenderPassword /// <summary> /// Transaction Id - uses the Time and Date converted to Ticks /// </summary> public String TransactionId { get; set; } // end TransactionId /// <summary> /// calculate the authentication value that will be used when /// communicating with /// </summary> public String AuthenticationValue { get; set; } // end AuthenticationValue property /// <summary> /// encodes password(s) using MD5 /// </summary> /// <param name="clearPassword"></param> /// <returns></returns> public static String EncodePassword(String clearPassword) { MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider(); byte[] hashedBytes; UTF32Encoding encoder = new UTF32Encoding(); hashedBytes = md5Hasher.ComputeHash(ASCIIEncoding.Default.GetBytes(clearPassword)); String result = Regex.Replace(BitConverter.ToString(hashedBytes), "-", "").ToLower(); return result; } } } There is nothing particularly clever here, except for the EncodePassword method which hashes the value made up of the SenderId, Password and Transaction id. Each message inherits from this object. So for the Company Number Search in addition to the properties above we need a partial number, which dataset to search – for the purposes of the project we only need to search the LIVE set so this can be set in the constructor and the SearchRows. Again all are set as properties. With the SearchRows and DataSet initialized in the constructor. public class CompanyNumberSearchRequest : GovTalkRequest, IDisposable { /// <summary> /// /// </summary> public CompanyNumberSearchRequest() : base() { DataSet = "LIVE"; SearchRows = 1; } /// <summary> /// Company Number to search against /// </summary> public String PartialCompanyNumber { get; set; } /// <summary> /// What DataSet should be searched for the company /// </summary> public String DataSet { get; set; } /// <summary> /// How many rows should be returned /// </summary> public int SearchRows { get; set; } public void Dispose() { DataSet = String.Empty; PartialCompanyNumber = String.Empty; DataSet = "LIVE"; SearchRows = 1; } } As well as inheriting from our base class, I have also inherited from IDisposable – not just because it is just plain good practice to dispose of objects when coding, but it gives also gives us more versatility when using the object. There are four stages in making a request and this is reflected in the four methods we execute in making a call to the Companies House service; Create a request Send a request Check the status If OK then get the results of the request I’ve implemented each of these stages within a static class called Toolbox – which also means I don’t need to create an instance of the class to use it. When making a request there are three stages; Get the template for the message Serialize the object representing the message Transform the serialized object using a predefined XSLT file. Each of my templates I have defined as an embedded resource. When retrieving a resource of this kind we have to include the full namespace to the resource. In making the code re-usable as much as possible I defined the full ‘path’ within the GetRequest method. requestFile = String.Format("CompanyHub.Services.Schemas.{0}", RequestFile); So we now have the full path of the file within the assembly. Now all we need do is retrieve the assembly and get the resource. asm = Assembly.GetExecutingAssembly(); sr = asm.GetManifestResourceStream(requestFile); Once retrieved  So this can be returned to the calling function and we now have a stream of XSLT to define the message. Time now to serialize the request to create the other side of this message. // Serialize object containing Request, Load into XML Document t = Obj.GetType(); ms = new MemoryStream(); serializer = new XmlSerializer(t); xmlTextWriter = new XmlTextWriter(ms, Encoding.ASCII); serializer.Serialize(xmlTextWriter, Obj); ms = (MemoryStream)xmlTextWriter.BaseStream; GovTalkRequest = Toolbox.ConvertByteArrayToString(ms.ToArray()); First off we need the type of the object so we make a call to the GetType method of the object containing the Message properties. Next we need a MemoryStream, XmlSerializer and an XMLTextWriter so these can be initialized. The object is serialized by making the call to the Serialize method of the serializer object. The result of that is then converted into a MemoryStream. That MemoryStream is then converted into a string. ConvertByteArrayToString This is a fairly simple function which uses an ASCIIEncoding object found within the System.Text namespace to convert an array of bytes into a string. public static String ConvertByteArrayToString(byte[] bytes) { System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); return enc.GetString(bytes); } I only put it into a function because I will be using this in various places. The Sauce When adding support for other messages outside of creating a new object to store the properties of the message, the C# components do not need to change. It is in the XSLT file that the versatility of the technique lies. The XSLT file determines the format of the message. For the CompanyNumberSearch the XSLT file is as follows; <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <GovTalkMessage xsi:schemaLocation="http://www.govtalk.gov.uk/CM/envelope http://xmlgw.companieshouse.gov.uk/v1-0/schema/Egov_ch-v2-0.xsd" xmlns="http://www.govtalk.gov.uk/CM/envelope" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:gt="http://www.govtalk.gov.uk/schemas/govtalk/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > <EnvelopeVersion>1.0</EnvelopeVersion> <Header> <MessageDetails> <Class>NumberSearch</Class> <Qualifier>request</Qualifier> <TransactionID> <xsl:value-of select="CompanyNumberSearchRequest/TransactionId"/> </TransactionID> </MessageDetails> <SenderDetails> <IDAuthentication> <SenderID><xsl:value-of select="CompanyNumberSearchRequest/SenderID"/></SenderID> <Authentication> <Method>CHMD5</Method> <Value> <xsl:value-of select="CompanyNumberSearchRequest/AuthenticationValue"/> </Value> </Authentication> </IDAuthentication> </SenderDetails> </Header> <GovTalkDetails> <Keys/> </GovTalkDetails> <Body> <NumberSearchRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://xmlgw.companieshouse.gov.uk/v1-0/schema/NumberSearch.xsd"> <PartialCompanyNumber> <xsl:value-of select="CompanyNumberSearchRequest/PartialCompanyNumber"/> </PartialCompanyNumber> <DataSet> <xsl:value-of select="CompanyNumberSearchRequest/DataSet"/> </DataSet> <SearchRows> <xsl:value-of select="CompanyNumberSearchRequest/SearchRows"/> </SearchRows> </NumberSearchRequest> </Body> </GovTalkMessage> </xsl:template> </xsl:stylesheet> The outer two tags define that this is a XSLT stylesheet and the root tag from which the nodes are searched for. The GovTalkMessage is the format of the message that will be sent to Companies House. We first set up the XslCompiledTransform object which will transform the XSLT template and the serialized object into the request to Companies House. xslt = new XslCompiledTransform(); resultStream = new MemoryStream(); writer = new XmlTextWriter(resultStream, Encoding.ASCII); doc = new XmlDocument(); The Serialize method require XmlTextWriter to write the XML (writer) and a stream to place the transferred object into (writer). The XML will be loaded into an XMLDocument object (doc) prior to the transformation. // create XSLT Template xslTemplate = Toolbox.GetRequest(Template); xslTemplate.Seek(0, SeekOrigin.Begin); templateReader = XmlReader.Create(xslTemplate); xslt.Load(templateReader); I have stored all the templates as a series of Embedded Resources and the GetRequestCall takes the name of the template and extracts the relevent XSLT file. /// <summary> /// Gets the framwork XML which makes the request /// </summary> /// <param name="RequestFile"></param> /// <returns></returns> public static Stream GetRequest(String RequestFile) { String requestFile = String.Empty; Stream sr = null; Assembly asm = null; try { requestFile = String.Format("CompanyHub.Services.Schemas.{0}", RequestFile); asm = Assembly.GetExecutingAssembly(); sr = asm.GetManifestResourceStream(requestFile); } catch (Exception) { throw; } finally { asm = null; } return sr; } // end private static stream GetRequest We first take the template name and expand it to include the full namespace to the Embedded Resource I like to keep all my schemas in the same directory and so the namespace reflects this. The rest is the default namespace for the project. Then we get the currently executing assembly (which will contain the resources with the call to GetExecutingAssembly() ) Finally we get a stream which contains the XSLT file. We use this stream and then load an XmlReader with the contents of the template, and that is in turn loaded into the XslCompiledTransform object. We convert the object containing the message properties into Xml by serializing it; calling the Serialize() method of the XmlSerializer object. To set up the object we do the following; t = Obj.GetType(); ms = new MemoryStream(); serializer = new XmlSerializer(t); xmlTextWriter = new XmlTextWriter(ms, Encoding.ASCII); We first determine the type of the object being transferred by calling GetType() We create an XmlSerializer object by passing the type of the object being serialized. The serializer writes to a memory stream and that is linked to an XmlTextWriter. Next job is to serialize the object and load it into an XmlDocument. serializer.Serialize(xmlTextWriter, Obj); ms = (MemoryStream)xmlTextWriter.BaseStream; xmlRequest = new XmlTextReader(ms); GovTalkRequest = Toolbox.ConvertByteArrayToString(ms.ToArray()); doc.LoadXml(GovTalkRequest); Time to transform the XML to construct the full request. xslt.Transform(doc, writer); resultStream.Seek(0, SeekOrigin.Begin); request = Toolbox.ConvertByteArrayToString(resultStream.ToArray()); So that creates the full request to be sent  to Companies House. Sending the request So far we have a string with a request for the Companies House service. Now we need to send the request to the Companies House Service. Configuration within an Azure project There are entire blog entries written about configuration within an Azure project – most of this is out of scope for this article but the following is a summary. Configuration is defined in two files within the parent project *.csdef which contains the definition of configuration setting. <?xml version="1.0" encoding="utf-8"?> <ServiceDefinition name="OnlineCompanyHub" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition"> <WebRole name="CompanyHub.Host"> <InputEndpoints> <InputEndpoint name="HttpIn" protocol="http" port="80" /> </InputEndpoints> <ConfigurationSettings> <Setting name="DiagnosticsConnectionString" /> <Setting name="DataConnectionString" /> </ConfigurationSettings> </WebRole> <WebRole name="CompanyHub.Services"> <InputEndpoints> <InputEndpoint name="HttpIn" protocol="http" port="8080" /> </InputEndpoints> <ConfigurationSettings> <Setting name="DiagnosticsConnectionString" /> <Setting name="SenderId"/> <Setting name="SenderPassword" /> <Setting name="GovTalkUrl"/> </ConfigurationSettings> </WebRole> <WorkerRole name="CompanyHub.Worker"> <ConfigurationSettings> <Setting name="DiagnosticsConnectionString" /> </ConfigurationSettings> </WorkerRole> </ServiceDefinition>   Above is the configuration definition from the project. What we are interested in however is the ConfigurationSettings tag of the CompanyHub.Services WebRole. There are four configuration settings here, but at the moment we are interested in the second to forth settings; SenderId, SenderPassword and GovTalkUrl The value of these settings are defined in the ServiceDefinition.cscfg file; <?xml version="1.0"?> <ServiceConfiguration serviceName="OnlineCompanyHub" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration"> <Role name="CompanyHub.Host"> <Instances count="2" /> <ConfigurationSettings> <Setting name="DiagnosticsConnectionString" value="UseDevelopmentStorage=true" /> <Setting name="DataConnectionString" value="UseDevelopmentStorage=true" /> </ConfigurationSettings> </Role> <Role name="CompanyHub.Services"> <Instances count="2" /> <ConfigurationSettings> <Setting name="DiagnosticsConnectionString" value="UseDevelopmentStorage=true" /> <Setting name="SenderId" value="UserID"/> <Setting name="SenderPassword" value="Password"/> <Setting name="GovTalkUrl" value="http://xmlgw.companieshouse.gov.uk/v1-0/xmlgw/Gateway"/> </ConfigurationSettings> </Role> <Role name="CompanyHub.Worker"> <Instances count="2" /> <ConfigurationSettings> <Setting name="DiagnosticsConnectionString" value="UseDevelopmentStorage=true" /> </ConfigurationSettings> </Role> </ServiceConfiguration>   Look for the Role tag that contains our project name (CompanyHub.Services). Having configured the parameters we can now transmit the request. This is done by ‘POST’ing a stream of XML to the Companies House servers. govTalkUrl = RoleEnvironment.GetConfigurationSettingValue("GovTalkUrl"); request = WebRequest.Create(govTalkUrl); request.Method = "POST"; request.ContentType = "text/xml"; writer = new StreamWriter(request.GetRequestStream()); writer.WriteLine(RequestMessage); writer.Close(); We use the WebRequest object to send the object. Set the method of sending to ‘POST’ and the type of data as text/xml. Once set up all we do is write the request to the writer – this sends the request to Companies House. Did the Request Work Part I – Getting the response Having sent a request – we now need the result of that request. response = request.GetResponse(); reader = response.GetResponseStream(); result = Toolbox.ConvertByteArrayToString(Toolbox.ReadFully(reader));   The WebRequest object has a GetResponse() method which allows us to get the response sent back. Like many of these calls the results come in the form of a stream which we convert into a string. Did the Request Work Part II – Translating the Response Much like XSLT and XML were used to create the original request, so it can be used to extract the response and by deserializing the result we create an object that contains the response. Did it work? It would be really great if everything worked all the time. Of course if it did then I don’t suppose people would pay me and others the big bucks so that our programmes do not a) Collapse in a heap (this is an area of memory) b) Blow every fuse in the place in a shower of sparks (this will probably not happen this being real life and not a Hollywood movie, but it was possible to blow the sound system of a BBC Model B with a poorly coded setting) c) Go nuts and trap everyone outside the airlock (this was from a movie, and unless NASA get a manned moon/mars mission set up unlikely to happen) d) Go nuts and take over the world (this was also from a movie, but please note life has a habit of being of exceeding the wildest imaginations of Hollywood writers (note writers – Hollywood executives have no imagination and judging by recent output of that town have turned plagiarism into an art form). e) Freeze in total confusion because the cleaner pulled the plug to the internet router (this has happened) So anyway – we need to check to see if our request actually worked. Within the GovTalk response there is a section that details the status of the message and a description of what went wrong (if anything did). I have defined an XSLT template which will extract these into an XML document. <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ev="http://www.govtalk.gov.uk/CM/envelope" xmlns:gt="http://www.govtalk.gov.uk/schemas/govtalk/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <xsl:template match="/"> <GovTalkStatus xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Status> <xsl:value-of select="ev:GovTalkMessage/ev:Header/ev:MessageDetails/ev:Qualifier"/> </Status> <Text> <xsl:value-of select="ev:GovTalkMessage/ev:GovTalkDetails/ev:GovTalkErrors/ev:Error/ev:Text"/> </Text> <Location> <xsl:value-of select="ev:GovTalkMessage/ev:GovTalkDetails/ev:GovTalkErrors/ev:Error/ev:Location"/> </Location> <Number> <xsl:value-of select="ev:GovTalkMessage/ev:GovTalkDetails/ev:GovTalkErrors/ev:Error/ev:Number"/> </Number> <Type> <xsl:value-of select="ev:GovTalkMessage/ev:GovTalkDetails/ev:GovTalkErrors/ev:Error/ev:Type"/> </Type> </GovTalkStatus> </xsl:template> </xsl:stylesheet>   Only thing different about previous XSL files is the references to two namespaces ev & gt. These are defined in the GovTalk response at the top of the response; xsi:schemaLocation="http://www.govtalk.gov.uk/CM/envelope http://xmlgw.companieshouse.gov.uk/v1-0/schema/Egov_ch-v2-0.xsd" xmlns="http://www.govtalk.gov.uk/CM/envelope" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:gt="http://www.govtalk.gov.uk/schemas/govtalk/core" If we do not put these references into the XSLT template then  the XslCompiledTransform object will not be able to find the relevant tags. Deserialization is a fairly simple activity. encoder = new ASCIIEncoding(); ms = new MemoryStream(encoder.GetBytes(statusXML)); serializer = new XmlSerializer(typeof(GovTalkStatus)); xmlTextWriter = new XmlTextWriter(ms, Encoding.ASCII); messageStatus = (GovTalkStatus)serializer.Deserialize(ms);   We set up a serialization object using the object type containing the error state and pass to it the results of a transformation between the XSLT above and the GovTalk response. Now we have an object containing any error state, and the error message. All we need to do is check the status. If there is an error then we can flag an error. If not then  we extract the results and pass that as an object back to the calling function. We go this by guess what – defining an XSLT template for the result and using that to create an Xml Stream which can be deserialized into a .Net object. In this instance the XSLT to create the result of a Company Number Search is; <?xml version="1.0" encoding="us-ascii"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ev="http://www.govtalk.gov.uk/CM/envelope" xmlns:sch="http://xmlgw.companieshouse.gov.uk/v1-0/schema" exclude-result-prefixes="ev"> <xsl:template match="/"> <CompanySearchResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <CompanyNumber> <xsl:value-of select="ev:GovTalkMessage/ev:Body/sch:NumberSearch/sch:CoSearchItem/sch:CompanyNumber"/> </CompanyNumber> <CompanyName> <xsl:value-of select="ev:GovTalkMessage/ev:Body/sch:NumberSearch/sch:CoSearchItem/sch:CompanyName"/> </CompanyName> </CompanySearchResult> </xsl:template> </xsl:stylesheet> and the object definition is; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CompanyHub.Services { public class CompanySearchResult { public CompanySearchResult() { CompanyNumber = String.Empty; CompanyName = String.Empty; } public String CompanyNumber { get; set; } public String CompanyName { get; set; } } } Our entire code to make calls to send a request, and interpret the results are; String request = String.Empty; String response = String.Empty; GovTalkStatus status = null; fault = null; try { using (CompanyNumberSearchRequest requestObj = new CompanyNumberSearchRequest()) { requestObj.PartialCompanyNumber = CompanyNumber; request = Toolbox.CreateRequest(requestObj, "CompanyNumberSearch.xsl"); response = Toolbox.SendGovTalkRequest(request); status = Toolbox.GetMessageStatus(response); if (status.Status.ToLower() == "error") { fault = new HubFault() { Message = status.Text }; } else { Object obj = Toolbox.GetGovTalkResponse(response, "CompanyNumberSearchResult.xsl", typeof(CompanySearchResult)); } } } catch (FaultException<ArgumentException> ex) { fault = new HubFault() { FaultType = ex.Detail.GetType().FullName, Message = ex.Detail.Message }; } catch (System.Exception ex) { fault = new HubFault() { FaultType = ex.GetType().FullName, Message = ex.Message }; } finally { } Wrap up So there we have it – a reusable set of functions to send and interpret XML results from an internet based service. The code is reusable with a little change with any service which uses XML as a transport mechanism – and as for the Companies House GovTalk service all I need to do is create various objects for the result and message sent and the relevent XSLT files. I might need minor changes for other services but something like 70-90% will be exactly the same.

    Read the article

< Previous Page | 6 7 8 9 10