Search Results

Search found 1062 results on 43 pages for 'broke artist'.

Page 9/43 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Resolution independence - resize on the fly or ship all sizes?

    - by RecursiveCall
    My game relies heavily on textures of various sizes with some being full-screen. The game is targeted for multiple resolutions. I found that resizing textures (downsizing) works quite well for this game’s art type (it’s not Pixel Art or anything like that). I asked my artist to ensure that all textures at the edges of the screen to be created in such a way that they can safely “overflow” off screen; this means that aspect ratio is not an issue. So with no aspect ratio issues, I figured that I would simply ask my artist to create assets in very high resolution, and then resize them down to the appropriate screen resolution. The question is, when and how do I do that? Do I pre-resize everything to common resolutions in Photoshop and package all assets in the final product (increasing the size download that the user has to deal with) and then select the appropriate asset based on the detected resolution? Or do I ship with the largest set of Textures, detect the resolution on load, set a render target and draw all downsized assets to it and use that? Or for the latter, do I use some sort of a CPU-sided algorithm to resize on game load?

    Read the article

  • Uwall.tv Turns YouTube into a Video Jukebox

    - by ETC
    If you frequently hit up YouTube to get your music fix, Uwall.tv is a video playlist service that turns YouTube into your personal music video jukebox. Visit Uwall.tv, plug in an artist or band name, and Uwall.tv generates a playlist of music by the act you’re interested in. You can further filter by popularity, upload date, rating, and video quality. Uwall.tv also suggests other artists you might be interested in. If you login with Facebook Connect you can also build custom playlists and break free from the one-artist-list limitation. UWall.tv is a free service, login only required for creating and saving custom playlists. UWall.tv [via Google Tutor] Latest Features How-To Geek ETC Learn To Adjust Contrast Like a Pro in Photoshop, GIMP, and Paint.NET Have You Ever Wondered How Your Operating System Got Its Name? Should You Delete Windows 7 Service Pack Backup Files to Save Space? What Can Super Mario Teach Us About Graphics Technology? Windows 7 Service Pack 1 is Released: But Should You Install It? How To Make Hundreds of Complex Photo Edits in Seconds With Photoshop Actions Add a “Textmate Style” Lightweight Text Editor with Dropbox Syncing to Chrome and Iron Is the Forcefield Really On or Not? [Star Wars Parody Video] Google Updates Picasa Web Albums; Emphasis on Sharing and Showcasing Uwall.tv Turns YouTube into a Video Jukebox Early Morning Sunrise at the Beach Wallpaper Data Networks Visualized via Light Paintings [Video]

    Read the article

  • What's the best way to generate an NPC's face using web technologies?

    - by Vael Victus
    I'm in the process of creating a web app. I have many randomly-generated non-player characters in a database. I can pull a lot of information about them - their height, weight, down to eye color, hair color, and hair style. For this, I am solely interested in generating a graphical representation of the face. Currently the information is displayed with text in the nicest way possible, but I believe it's worth generating these faces for a more... human experience. Problem is, I'm not artist. I wouldn't mind commissioning an artist for this system, but I wouldn't know where to start. Were it 2007, I'd naturally think to myself that using Flash would be the best choice. I'd love to see "breathing" simulated. However, since Flash is on its way out, I'm not sure of a solid solution. With a previous game, I simply used layered .pngs to represent various aspects of the player's body: their armor, the face, the skin color. However, these solutions weren't very dynamic and felt very amateur. I can't go deep into this project feeling like that's an inferior way to present these faces, and I'm certain there's a better way. Can anyone give some suggestion on how to pull this off well?

    Read the article

  • Laptop touchpad works incorrect when on power supply

    - by Ikke
    My original laptop adapter broke down, so I've baught a new one. It's a no-brand adapter from a dutch internet shop. The power of the new adapter is slightly more than the old adapter, but in my opinion that shouldn't be a problem. The laptop is a Toshiba Sattelite L40-15B. When the old adapter broke down due to short circuit, this laptop was connected. When the adapter is unplugged, the touchpad works correctly and smoothly. But as soon as it is connected, the cursor moves jumpy, and response badly. Does anyone know where this problem comes from, and if there's a solution?

    Read the article

  • What You Said: How You Organize a Messy Music Collection

    - by Jason Fitzpatrick
    Earlier this week we asked you to share your tips, tricks, and tools, for managing a messy music collection. Now we’re back to share so great reader tips; read on to find ways to tame your mountain of music. Several readers were, despite having tried various techniques over the years, fans of doing things largely the manual way. Aurora900 explains: I spent a weekend sorting everything myself once. Took a while, but now I have folders sorted by artist, and within the artist folders are folders for their albums. With my collection at about 260gb, it can be a daunting task, but it’s well worth it in the end. I don’t have the tagging issue as I make sure anything I have is properly tagged to begin with… If I’m ripping a CD I use Easy CD-DA Extractor, which automatically searches a database on the internet for the tags. If I’m downloading something, if its from a reputable source its going to be properly tagged already. Bilbo Baggins would love to automate, but eclectic music tastes make it hard: How to Own Your Own Website (Even If You Can’t Build One) Pt 3 How to Sync Your Media Across Your Entire House with XBMC How to Own Your Own Website (Even If You Can’t Build One) Pt 2

    Read the article

  • What is a "Technical Programmer"? [closed]

    - by Mike E
    I've noticed in job posting boards a few postings, all from European companies in the games industry, for a "Technical Programmer". The job description in both was similar, having to do with tools development, 3d graphics programming, etc. It seems to be somewhere between a Technical Artist who's more technical than artist or who can code, and a Technical Director but perhaps without the seniority/experience. Information elsewhere on the position is sparse. The title seems redundant and I haven't seen any American companies post jobs by that name exactly. One example is this job posting on gamedev.net which isn't exactly thorough. In case the link dies: Subject: Technical Programmer Frictional Games, the creators of Amnesia: The Dark Descent and the Penumbra series, are looking for a talented programmer to join the company! You will be working for a small team with a big focus on finding new and innovating solutions. We want you who are not afraid to explore uncharted territory and constantly learn new things. Self-discipline and independence are also important traits as all work will be done from home. Some the things you will work with include: 3D math, rendering, shaders and everything else related. Console development (most likely Xbox 360). Hardware implementations (support for motion controls, etc). All coding is in C++, so great skills in that is imperative. As I mentioned, the job title has appeared from European companies so maybe it goes by another title in America. What other titles might this specialization of programmer go by?

    Read the article

  • Force Windows to output only mono sound

    - by J. Polfer
    So, the 'right' half of my pair of headphones broke (the transducer+wire are fine, but the earpiece broke on the headband and so the earpiece won't sit over my ear). So now the right channel is being broadcast to my cube neighbors when I wear my headphones. Yes, they look very silly. Is there a way to ensure, in Windows XP (or Windows Media Player), that all stereo sound is downmixed to the left channel only (ie, in mono) so my neighbors don't hear my music? I know that I can setup the mixer to set the balance to 100% left, but information in the right channel won't be heard.

    Read the article

  • How does the TuneIn mobile application resume a live stream, when the connection breaks?

    - by navnav
    So I have this TuneIn application on my phone, which allows me to listen to many radio stations. It also allows me to rewind and pause the live stream, which I know is doable with today's technology. What gets me puzzled, though, is how when the internet connection breaks, the live stream will stop, but, when the connection comes back, the app can just pick up from where it broke. Why it gets me puzzled is because there is no way for the app to cache the live stream when the net connection has gone, yet it can start the live stream back up, from where it broke. Is there is possible to start a live stream, at a specific point of the audio stream? Or are they using some other method?

    Read the article

  • Slightly off topic - How to Fix Sky Go Error [t6013-c1501] (and [t6000-c1501])

    - by bconlon
    Sky doesn't seem to understand what their own errors mean, so I cobbled together an understanding from some other posts and managed to get it working.When you see the error [t6013-c1501] instead of your TV programme in Sky Go, it seems to mean:'You registered a device, but then changed the hardware, so now I'm confused!'In other words, the Digital rights management (DRM) used between Sky Go and Silverlight stored an old fingerprint of your PC, but rather than recognising this and allowing you to remove the device, it just disappears from the 'Manage Devices' page.DISCLAIMER: Perform the following steps at your own risk. It worked for me, but I didn't care if it broke stuff. If you care....don't do it!So, to fix this I did the following:1. Login to Sky Go and click 'Watch live TV' from the home page. It will attempt to show Sky News and fail with the error [t6013-c1501].2. Right click on the error and you should see the Menu option 'Silverlight'. Select this and a dialog should appear. Click the 'Application Storage' tab and delete any entry that relates to sky go. Clcik OK to close the dialog.3. Open explorer and navigate to the folder C:\ProgramData\Microsoft\PlayReady4. Rename the file mspr.hds to mspr.hds.OLD5. Go back to the browser and click F5. You may need to logout/login (not sure).Note: Don't rename/delete the folder C:\ProgramData\Microsoft\PlayReady or you will get the error [t6000-c1501]. The folder must exist in order for the new file to be created by Silverlight. Techie talk:So whoever wrote the code to create a new mspr.hds file didn't write code to check the folder existed causing what I assume is a generic error t6000, probably something like:catch (Exception ex) { WriteToLog("Oops, something broke!"); }#

    Read the article

  • "Keep iTune music files organized" no longer works?

    - by user22105
    I remember iTunes used to have the option to "keep music files organized" (i know it still does in its advanced Properties). When I used to edit music's artist, genre or album information. The mp3 file is automatically updated as well. But lately I've been updating some mp3s. And if I tried to open the updated mp3's Properties, under Details, the Artist, genre, and album information is not available. How can i fix this? Added: you can try editing this mp3 file with iTunes, it didn't work on my PC Here's a screenshot of what Im seeing after the edit.

    Read the article

  • Check "Id3 Tag" integrity from mp3 (almost a "debug"). Is it possible?

    - by Somebody still uses you MS-DOS
    I'm using Mp3Tag do edit Id3 tags in my mp3 files. In the editor everything looks ok, but in my iTunes, some of them just ge messed up. The artist isn't read, Album Artist doesn't show up, this kind of thing. It's just random, some are messed up, some aren't. How do I "debug" this problem? How can I check what is written in my mp3 metadata, if possible, running all my mp3 in a batch (since I have 100gb)? How do I know if there are "garbage" in the metadata section along with information I correctly edited?

    Read the article

  • c# - PubNub JSON serialization code works in example project but not in my project

    - by pilau
    I am making a Winamp plugin with the single function of sending the details of the song being played over HTTP to a webpage. It works like this: Winamp song event triggered - check for new song - publish to webpage using PubNub (C# API). So far I got to the stage where everything works exactly as it is supposed to, except for the PubNub code which doesn't serialize the object I'm passing for publishing into JSON. All I keep getting in the PubNub console is a mere {} - an empty JSON object. A little background on the project structure: I am using Sharpamp which is a custom library that enables making Winamp plugins with C#. I am also using the PubNub C# API. The gen_notifier_cs project is the C++ plugin wrapper created by Sharpamp. notifier_cs is where all my code resides. The two other projects are self explanatory I assume. I have referenced the PubNub API in notifier_cs, and also have referenced Sharpamp in both notifier_cs and PubNub API. So, the objects that need to get serialized are of a class Song as defined in Sharpamp: public class Song { public string Title { get; internal set; } public string Artist { get; internal set; } public string Album { get; internal set; } public string Year { get; internal set; } public bool HasMetadata { get; internal set; } public string Filename { get; internal set; } } So let's say if I have a song object with song data in it, I would go pubnub.publish("winamp_pipe", song); to publish it and PubNub will automatically serialize the data into JSON. But that's just not working in my solution. To test why it wasn't serializing, I copied that class to the example code file in the PubNub API. Visual Studio changed the class to this (notice the public Song() method): public class Song { public Song() { return; } public string Album { get; set; } public string Artist { get; set; } public string Filename { get; set; } public bool HasMetadata { get; set; } public string Title { get; set; } public string Year { get; set; } } On the same example file I initiated a default song object with some values: Song song = new Song(); song.Album = "albumname"; song.Artist = "artistname"; song.HasMetadata = true; song.Title = "songtitle"; song.Year = "2012"; And published it: pubnub.publish("winamp_pipe", song); and it worked! I got the JSON object in the PubNub channel! {"Album":"albumname","Artist":"artistname","Filename":null,"HasMetadata":true,"Title":"songtitle","Year":"2012"} So, I tried replacing the "new" Song class with the original one defined in Sharpamp. I tried adding another class definition in the notifier_cs project but that clashes with the one in Sharpamp which I have to rely on. I have been trying so many things as far as I could come up with. Needless to say none prevailed. Still, all I get is an empty JSON object. I have been pulling out my hair for the last day. I know this post is super long but I appreciate your input nonetheless. Thanks in advance.

    Read the article

  • search a collection for a specific keyword

    - by icelated
    What i want to do is search a hashset with a keyword.. I have 3 classes... main() Library Item(CD, DVD,Book classes) In library i am trying to do my search of the items in the hashsets.. In Item class is where i have the getKeywords function.. here is the Items class... import java.io.PrintStream; import java.util.Collection; import java.util.*; class Item { private String title; private String [] keywords; public String toString() { String line1 = "title: " + title + "\n" + "keywords: " + Arrays.toString(keywords); return line1; } public void print() { System.out.println(toString()); } public Item() { } public Item(String theTitle, String... theKeyword) { this.title = theTitle; this.keywords = theKeyword; } public String getTitle() { return title; } public String [] getKeywords() { return keywords; } } class CD extends Item { private String artist; private String [] members; // private String [] keywords; private int number; public CD(String theTitle, String theBand, int Snumber, String... keywords) { super(theTitle, keywords); this.artist = theBand; this.number = Snumber; // this.keywords = keywords; } public void addband(String... member) { this.members = member; } public String getArtist() { return artist; } public String [] getMembers() { return members; } // public String [] getKeywords() // { // return keywords; //} public String toString() { return "-Music-" + "\n" + "band: " + artist + "\n" + "# songs: " + number + "\n" + "members: " + Arrays.toString(members) + "\n" + super.toString() // + "keywords: " + Arrays.toString(keywords) + "\n" + "\n" ; } public void print() { System.out.println(toString()); } } class DVD extends Item { private String director; private String [] cast; private int scenes; // private String [] keywords; public DVD(String theTitle, String theDirector, int nScenes, String... keywords) { super(theTitle, keywords); this.director = theDirector; this.scenes = nScenes; // this.keywords = keywords; } public void addmoviecast(String... members) { this.cast = members; } public String [] getCast() { return cast; } public String getDirector() { return director; } // public String [] getKeywords() // { // return keywords; // } public String toString() { return "-Movie-" + "\n" + "director: " + director + "\n" + "# scenes: " + scenes + "\n" + "cast: " + Arrays.toString(cast) + "\n" + super.toString() // + "keywords: " + Arrays.toString(keywords) + "\n" + "\n" ; } public void print() { System.out.println(toString()); } } class Book extends Item { private String author; private int pages; public Book(String theTitle, String theAuthor, int nPages, String... keywords) { super(theTitle, keywords); this.author = theAuthor; this.pages = nPages; // this.keywords = keywords; } public String getAuthor() { return author; } //public String [] getKeywords() // { // return keywords; //} public void print() { System.out.println(toString()); } public String toString() { return "-Book-" + "\n" + "Author: " + author + "\n" + "# pages " + pages + "\n" + super.toString() // + "keywords: " + Arrays.toString(keywords) + "\n" + "\n" ; } } I hope i didnt confuse you? I need help with the itemsForKeyword(String keyword) function.. the first keyword being passed in is "science fiction" and i want to search the keywords in the sets and return the matches.. What am i doing so wrong? Thank you

    Read the article

  • PHP returning part of the code document

    - by The.Anti.9
    I have a PHP page that does a couple of different things depending on what action is set to in the GET data. Depending, it is supposed to return some JSON, but instead of doing anything it is supposed to it returns the bottom half of the code document itself, starting in the middle of the line. Heres the snippit from where it starts: ... } elseif ($_GET['action'] == 'addtop') { if (!isset($_GET['pname']) || !isset($_GET['url']) || !isset($_GET['artist']) || !isset($_GET['album']) || !isset($_GET['file'])) { die('Error: Incomplete data!'); } if (!file_exists($_GET['pname'].".txt")) { die('Error: No such playlist!'); } $plist = json_decode(file_get_contents($_GET['pname'].".txt"), true); $fh = fopen($_GET['pname'].".txt", 'w') or die('Could not open playlist!'); array_push($plist, array("artist" => $_GET['artist'], "album" => $_GET['album'], "file" => $_GET['file'], "url" => $_GET['url'])); fwrite($fh,json_encode($plist)); } elseif ($_GET['action'] == 'delfromp') { ... And here is what I get when I go to the page: $_GET['artist'], "album" = $_GET['album'], "file" = $_GET['file'], "url" = $_GET['url'])); fwrite($fh,json_encode($plist)); } elseif ($_GET['action'] == 'delfromp') { if (!isset($_GET['pname']) || !isset($_GET['id'])) { die('Error: Incomplete data!'); } if (!file_exists($_GET['pname'].".txt")) { die('Error: No such playlist!'); } $plist = json_decode(file_get_contents($_GET['pname'].".txt"), true); $fh = fopen($_GET['pname'].".txt", 'w') or die('Could not open playlist!'); unset($plist[$_GET['id']]); $plist = array_values($plist); fwrite($fh,json_encode($plist)); } elseif ($_GET['action'] == 'readp') { if (!file_exists($_GET['pname'].".txt")) { die('Error: No such playlist!'); } $plist = json_decode(file_get_contents($_GET['pname'].".txt"), true); $arr = array("entries" = $plist); $json = json_encode($arr); echo $json; } elseif ($_GET['action'] == 'getps') { $plists = array(); if ($handle = opendir('Playlists')) { while (false !== ($playlist = readdir($handle))) { if ($playlist != "." && $playlist != "..") { array_push($plists, substr($playlist, 0, strripos($playlist, '.')-1)); } } } else { die('Error: Can\'T open playlists!'); } $arr = array("entries"=$plists); $json = json_encode($arr); echo $json; } else { die('Error: No such action!'); } ? It starts in the middle of the array_push(... line. I really can't think of what it is doing. Theres no echos anywhere around it. Any ideas?

    Read the article

  • Simple Adapter error

    - by Rahul Varma
    Hi, I have the following errors when i try to access the simple adapter from my program... Plz can anyone help me solving the error... Desperate to get it done.... android.widget.SimpleAdapter.getCount(SimpleAdapter.java:95) android.widget.ListView.setAdapter(ListView.java:431) com.stellent.gorinka.MusicListActivity.list(MusicListActivity.java:76) com.stellent.gorinka.MusicListActivity$1.run(MusicListActivity.java:67) android.os.Handler.handleCallback(Handler.java:587) android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:123) android.os.Handler.handleCallback(Handler.java:587) android.os.Handler.dispatchMessage(Handler.java:92) android.os.Looper.loop(Looper.java:123) Here' the code for Adapter... public class SongsAdapter extends SimpleAdapter{ static List<HashMap<String,String>> songsList; Context context; LayoutInflater inflater; public SongsAdapter(Context context,List<HashMap<String,String>> imgListWeb,int layout,String[] from,int[] to,LayoutInflater inflater) { super(context,songsList,layout,from,to); this.songsList=songsList; this.context=context; this.inflater=inflater; // TODO Auto-generated constructor stub }@Override public View getView(int postition,View convertView,ViewGroup parent)throws java.lang.OutOfMemoryError{ try { View v = ((LayoutInflater) inflater).inflate(R.layout.row,null); ImageView images=(ImageView)v.findViewById(R.id.image); TextView tvTitle=(TextView)v.findViewById(R.id.text1); TextView tvAlbum=(TextView)v.findViewById(R.id.text2); TextView tvArtist=(TextView)v.findViewById(R.id.text3); HashMap<String,String> songsHash=songsList.get(postition); String path=songsHash.get("path"); String title=songsHash.get("title"); String album=songsHash.get("album"); String artist=songsHash.get("artist"); String imgPath=path; final ImageView imageView = (ImageView) v.findViewById(R.id.image); AsyncImageLoaderv asyncImageLoader=new AsyncImageLoaderv(); Bitmap cachedImage = asyncImageLoader.loadDrawable(imgPath, new AsyncImageLoaderv.ImageCallback() { public void imageLoaded(Bitmap imageDrawable, String imageUrl) { imageView.setImageBitmap(imageDrawable); } }); imageView.setImageBitmap(cachedImage); tvTitle.setText(title); tvAlbum.setText(album); tvArtist.setText(artist); return v; } catch(Exception e){ Log.e("error",e.toString()); } return null; } And also in my main program the focus is not entering the loop... The implementation in the loop isnt getting executed...Here's the code for it... public void list() { Log.d("#####","#####"); LayoutInflater inflater=getLayoutInflater(); String[] from={}; int[] n={}; adapter=new SongsAdapter(getApplicationContext(),songNodeDet,R.layout.row,from,n,inflater); lv.setAdapter(adapter);} private Handler handler = new Handler() { public void handleMessage(Message msg){ Log.d("*****","handler"); removeDialog(0); p.dismiss(); } }; public void webObjectList(Object[] imgListObj,String logInSess) throws XMLRPCException{ songNodeWeb = new HashMap<?,?>[imgListObj.length]; if(imgListObj!=null){ Log.e("completed","completed"); for(int i=0;i<imgListObj.length;i++){ //imgListObj.length songNodeWeb[i]=(HashMap<?,?>)imgListObj[i]; String nodeid=(String) songNodeWeb[i].get("nid"); Log.e("img",i+"completed"); HashMap<String,String> nData=new HashMap<String,String>(); nData.put("nid",nodeid); Object nodeget=client.call("node.get",logInSess,nodeid); HashMap<?,?> imgNode=(HashMap<?,?>)nodeget; String titleName=(String) imgNode.get("titles"); String movieName=(String) imgNode.get("album"); String singerName=(String) imgNode.get("artist"); nData.put("titles", titleName); nData.put("album", movieName); nData.put("artist", singerName); Object[] imgObject=(Object[])imgNode.get("title_format"); HashMap<?,?>[] imgDetails=new HashMap<?,?>[imgObject.length]; imgDetails[0]=(HashMap<?, ?>)imgObject[0]; String path=(String) imgDetails[0].get("filepath"); if(path.contains(" ")){ path=path.replace(" ", "%20"); } String imgPath="http://www.gorinka.com/"+path; paths.add(imgPath); nData.put("path", imgPath); Log.e("my path",path); String mime=(String)imgDetails[0].get("filemime"); nData.put("mime", mime); SongsList songs=new SongsList(titleName,movieName,singerName,imgPath,imgPath); SngList.add(i,songs); songNodeDet.add(i,nData); } Log.e("paths values",paths.toString()); // return imgNodeDet; handler.sendEmptyMessage(0); } } public void getSongs() throws MalformedURLException, XMLRPCException { String ur="http://www.gorinka.com/?q=services/xmlrpc"; URL u=new URL(ur); client = new XMLRPCClient(u); //Connecting to the website HashMap<?, ?> siteConn =(HashMap<?, ?>) client.call("system.connect"); // Getting initial sessio id String initSess=(String)siteConn.get("sessid"); //Login to the site using session id HashMap<?, ?> logInConn =(HashMap<?, ?>) client.call("user.login",initSess,"prakash","stellentsoft2009"); //Getting Login sessid logInSess=(String)logInConn.get("sessid"); websongListObject =(Object[]) client.call("nodetype.get",logInSess,""); webObjectList(websongListObject,logInSess); Log.d("webObjectList","webObjectList"); runOnUiThread(returnRes); } }

    Read the article

  • An Introduction to ASP.NET Web API

    - by Rick Strahl
    Microsoft recently released ASP.NET MVC 4.0 and .NET 4.5 and along with it, the brand spanking new ASP.NET Web API. Web API is an exciting new addition to the ASP.NET stack that provides a new, well-designed HTTP framework for creating REST and AJAX APIs (API is Microsoft’s new jargon for a service, in case you’re wondering). Although Web API ships and installs with ASP.NET MVC 4, you can use Web API functionality in any ASP.NET project, including WebForms, WebPages and MVC or just a Web API by itself. And you can also self-host Web API in your own applications from Console, Desktop or Service applications. If you're interested in a high level overview on what ASP.NET Web API is and how it fits into the ASP.NET stack you can check out my previous post: Where does ASP.NET Web API fit? In the following article, I'll focus on a practical, by example introduction to ASP.NET Web API. All the code discussed in this article is available in GitHub: https://github.com/RickStrahl/AspNetWebApiArticle [republished from my Code Magazine Article and updated for RTM release of ASP.NET Web API] Getting Started To start I’ll create a new empty ASP.NET application to demonstrate that Web API can work with any kind of ASP.NET project. Although you can create a new project based on the ASP.NET MVC/Web API template to quickly get up and running, I’ll take you through the manual setup process, because one common use case is to add Web API functionality to an existing ASP.NET application. This process describes the steps needed to hook up Web API to any ASP.NET 4.0 application. Start by creating an ASP.NET Empty Project. Then create a new folder in the project called Controllers. Add a Web API Controller Class Once you have any kind of ASP.NET project open, you can add a Web API Controller class to it. Web API Controllers are very similar to MVC Controller classes, but they work in any kind of project. Add a new item to this folder by using the Add New Item option in Visual Studio and choose Web API Controller Class, as shown in Figure 1. Figure 1: This is how you create a new Controller Class in Visual Studio   Make sure that the name of the controller class includes Controller at the end of it, which is required in order for Web API routing to find it. Here, the name for the class is AlbumApiController. For this example, I’ll use a Music Album model to demonstrate basic behavior of Web API. The model consists of albums and related songs where an album has properties like Name, Artist and YearReleased and a list of songs with a SongName and SongLength as well as an AlbumId that links it to the album. You can find the code for the model (and the rest of these samples) on Github. To add the file manually, create a new folder called Model, and add a new class Album.cs and copy the code into it. There’s a static AlbumData class with a static CreateSampleAlbumData() method that creates a short list of albums on a static .Current that I’ll use for the examples. Before we look at what goes into the controller class though, let’s hook up routing so we can access this new controller. Hooking up Routing in Global.asax To start, I need to perform the one required configuration task in order for Web API to work: I need to configure routing to the controller. Like MVC, Web API uses routing to provide clean, extension-less URLs to controller methods. Using an extension method to ASP.NET’s static RouteTable class, you can use the MapHttpRoute() (in the System.Web.Http namespace) method to hook-up the routing during Application_Start in global.asax.cs shown in Listing 1.using System; using System.Web.Routing; using System.Web.Http; namespace AspNetWebApi { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { RouteTable.Routes.MapHttpRoute( name: "AlbumVerbs", routeTemplate: "albums/{title}", defaults: new { symbol = RouteParameter.Optional, controller="AlbumApi" } ); } } } This route configures Web API to direct URLs that start with an albums folder to the AlbumApiController class. Routing in ASP.NET is used to create extensionless URLs and allows you to map segments of the URL to specific Route Value parameters. A route parameter, with a name inside curly brackets like {name}, is mapped to parameters on the controller methods. Route parameters can be optional, and there are two special route parameters – controller and action – that determine the controller to call and the method to activate respectively. HTTP Verb Routing Routing in Web API can route requests by HTTP Verb in addition to standard {controller},{action} routing. For the first examples, I use HTTP Verb routing, as shown Listing 1. Notice that the route I’ve defined does not include an {action} route value or action value in the defaults. Rather, Web API can use the HTTP Verb in this route to determine the method to call the controller, and a GET request maps to any method that starts with Get. So methods called Get() or GetAlbums() are matched by a GET request and a POST request maps to a Post() or PostAlbum(). Web API matches a method by name and parameter signature to match a route, query string or POST values. In lieu of the method name, the [HttpGet,HttpPost,HttpPut,HttpDelete, etc] attributes can also be used to designate the accepted verbs explicitly if you don’t want to follow the verb naming conventions. Although HTTP Verb routing is a good practice for REST style resource APIs, it’s not required and you can still use more traditional routes with an explicit {action} route parameter. When {action} is supplied, the HTTP verb routing is ignored. I’ll talk more about alternate routes later. When you’re finished with initial creation of files, your project should look like Figure 2.   Figure 2: The initial project has the new API Controller Album model   Creating a small Album Model Now it’s time to create some controller methods to serve data. For these examples, I’ll use a very simple Album and Songs model to play with, as shown in Listing 2. public class Song { public string AlbumId { get; set; } [Required, StringLength(80)] public string SongName { get; set; } [StringLength(5)] public string SongLength { get; set; } } public class Album { public string Id { get; set; } [Required, StringLength(80)] public string AlbumName { get; set; } [StringLength(80)] public string Artist { get; set; } public int YearReleased { get; set; } public DateTime Entered { get; set; } [StringLength(150)] public string AlbumImageUrl { get; set; } [StringLength(200)] public string AmazonUrl { get; set; } public virtual List<Song> Songs { get; set; } public Album() { Songs = new List<Song>(); Entered = DateTime.Now; // Poor man's unique Id off GUID hash Id = Guid.NewGuid().GetHashCode().ToString("x"); } public void AddSong(string songName, string songLength = null) { this.Songs.Add(new Song() { AlbumId = this.Id, SongName = songName, SongLength = songLength }); } } Once the model has been created, I also added an AlbumData class that generates some static data in memory that is loaded onto a static .Current member. The signature of this class looks like this and that's what I'll access to retrieve the base data:public static class AlbumData { // sample data - static list public static List<Album> Current = CreateSampleAlbumData(); /// <summary> /// Create some sample data /// </summary> /// <returns></returns> public static List<Album> CreateSampleAlbumData() { … }} You can check out the full code for the data generation online. Creating an AlbumApiController Web API shares many concepts of ASP.NET MVC, and the implementation of your API logic is done by implementing a subclass of the System.Web.Http.ApiController class. Each public method in the implemented controller is a potential endpoint for the HTTP API, as long as a matching route can be found to invoke it. The class name you create should end in Controller, which is how Web API matches the controller route value to figure out which class to invoke. Inside the controller you can implement methods that take standard .NET input parameters and return .NET values as results. Web API’s binding tries to match POST data, route values, form values or query string values to your parameters. Because the controller is configured for HTTP Verb based routing (no {action} parameter in the route), any methods that start with Getxxxx() are called by an HTTP GET operation. You can have multiple methods that match each HTTP Verb as long as the parameter signatures are different and can be matched by Web API. In Listing 3, I create an AlbumApiController with two methods to retrieve a list of albums and a single album by its title .public class AlbumApiController : ApiController { public IEnumerable<Album> GetAlbums() { var albums = AlbumData.Current.OrderBy(alb => alb.Artist); return albums; } public Album GetAlbum(string title) { var album = AlbumData.Current .SingleOrDefault(alb => alb.AlbumName.Contains(title)); return album; }} To access the first two requests, you can use the following URLs in your browser: http://localhost/aspnetWebApi/albumshttp://localhost/aspnetWebApi/albums/Dirty%20Deeds Note that you’re not specifying the actions of GetAlbum or GetAlbums in these URLs. Instead Web API’s routing uses HTTP GET verb to route to these methods that start with Getxxx() with the first mapping to the parameterless GetAlbums() method and the latter to the GetAlbum(title) method that receives the title parameter mapped as optional in the route. Content Negotiation When you access any of the URLs above from a browser, you get either an XML or JSON result returned back. The album list result for Chrome 17 and Internet Explorer 9 is shown Figure 3. Figure 3: Web API responses can vary depending on the browser used, demonstrating Content Negotiation in action as these two browsers send different HTTP Accept headers.   Notice that the results are not the same: Chrome returns an XML response and IE9 returns a JSON response. Whoa, what’s going on here? Shouldn’t we see the same result in both browsers? Actually, no. Web API determines what type of content to return based on Accept headers. HTTP clients, like browsers, use Accept headers to specify what kind of content they’d like to see returned. Browsers generally ask for HTML first, followed by a few additional content types. Chrome (and most other major browsers) ask for: Accept: text/html, application/xhtml+xml,application/xml; q=0.9,*/*;q=0.8 IE9 asks for: Accept: text/html, application/xhtml+xml, */* Note that Chrome’s Accept header includes application/xml, which Web API finds in its list of supported media types and returns an XML response. IE9 does not include an Accept header type that works on Web API by default, and so it returns the default format, which is JSON. This is an important and very useful feature that was missing from any previous Microsoft REST tools: Web API automatically switches output formats based on HTTP Accept headers. Nowhere in the server code above do you have to explicitly specify the output format. Rather, Web API determines what format the client is requesting based on the Accept headers and automatically returns the result based on the available formatters. This means that a single method can handle both XML and JSON results.. Using this simple approach makes it very easy to create a single controller method that can return JSON, XML, ATOM or even OData feeds by providing the appropriate Accept header from the client. By default you don’t have to worry about the output format in your code. Note that you can still specify an explicit output format if you choose, either globally by overriding the installed formatters, or individually by returning a lower level HttpResponseMessage instance and setting the formatter explicitly. More on that in a minute. Along the same lines, any content sent to the server via POST/PUT is parsed by Web API based on the HTTP Content-type of the data sent. The same formats allowed for output are also allowed on input. Again, you don’t have to do anything in your code – Web API automatically performs the deserialization from the content. Accessing Web API JSON Data with jQuery A very common scenario for Web API endpoints is to retrieve data for AJAX calls from the Web browser. Because JSON is the default format for Web API, it’s easy to access data from the server using jQuery and its getJSON() method. This example receives the albums array from GetAlbums() and databinds it into the page using knockout.js.$.getJSON("albums/", function (albums) { // make knockout template visible $(".album").show(); // create view object and attach array var view = { albums: albums }; ko.applyBindings(view); }); Figure 4 shows this and the next example’s HTML output. You can check out the complete HTML and script code at http://goo.gl/Ix33C (.html) and http://goo.gl/tETlg (.js). Figu Figure 4: The Album Display sample uses JSON data loaded from Web API.   The result from the getJSON() call is a JavaScript object of the server result, which comes back as a JavaScript array. In the code, I use knockout.js to bind this array into the UI, which as you can see, requires very little code, instead using knockout’s data-bind attributes to bind server data to the UI. Of course, this is just one way to use the data – it’s entirely up to you to decide what to do with the data in your client code. Along the same lines, I can retrieve a single album to display when the user clicks on an album. The response returns the album information and a child array with all the songs. The code to do this is very similar to the last example where we pulled the albums array:$(".albumlink").live("click", function () { var id = $(this).data("id"); // title $.getJSON("albums/" + id, function (album) { ko.applyBindings(album, $("#divAlbumDialog")[0]); $("#divAlbumDialog").show(); }); }); Here the URL looks like this: /albums/Dirty%20Deeds, where the title is the ID captured from the clicked element’s data ID attribute. Explicitly Overriding Output Format When Web API automatically converts output using content negotiation, it does so by matching Accept header media types to the GlobalConfiguration.Configuration.Formatters and the SupportedMediaTypes of each individual formatter. You can add and remove formatters to globally affect what formats are available and it’s easy to create and plug in custom formatters.The example project includes a JSONP formatter that can be plugged in to provide JSONP support for requests that have a callback= querystring parameter. Adding, removing or replacing formatters is a global option you can use to manipulate content. It’s beyond the scope of this introduction to show how it works, but you can review the sample code or check out my blog entry on the subject (http://goo.gl/UAzaR). If automatic processing is not desirable in a particular Controller method, you can override the response output explicitly by returning an HttpResponseMessage instance. HttpResponseMessage is similar to ActionResult in ASP.NET MVC in that it’s a common way to return an abstract result message that contains content. HttpResponseMessage s parsed by the Web API framework using standard interfaces to retrieve the response data, status code, headers and so on[MS2] . Web API turns every response – including those Controller methods that return static results – into HttpResponseMessage instances. Explicitly returning an HttpResponseMessage instance gives you full control over the output and lets you mostly bypass WebAPI’s post-processing of the HTTP response on your behalf. HttpResponseMessage allows you to customize the response in great detail. Web API’s attention to detail in the HTTP spec really shows; many HTTP options are exposed as properties and enumerations with detailed IntelliSense comments. Even if you’re new to building REST-based interfaces, the API guides you in the right direction for returning valid responses and response codes. For example, assume that I always want to return JSON from the GetAlbums() controller method and ignore the default media type content negotiation. To do this, I can adjust the output format and headers as shown in Listing 4.public HttpResponseMessage GetAlbums() { var albums = AlbumData.Current.OrderBy(alb => alb.Artist); // Create a new HttpResponse with Json Formatter explicitly var resp = new HttpResponseMessage(HttpStatusCode.OK); resp.Content = new ObjectContent<IEnumerable<Album>>( albums, new JsonMediaTypeFormatter()); // Get Default Formatter based on Content Negotiation //var resp = Request.CreateResponse<IEnumerable<Album>>(HttpStatusCode.OK, albums); resp.Headers.ConnectionClose = true; resp.Headers.CacheControl = new CacheControlHeaderValue(); resp.Headers.CacheControl.Public = true; return resp; } This example returns the same IEnumerable<Album> value, but it wraps the response into an HttpResponseMessage so you can control the entire HTTP message result including the headers, formatter and status code. In Listing 4, I explicitly specify the formatter using the JsonMediaTypeFormatter to always force the content to JSON.  If you prefer to use the default content negotiation with HttpResponseMessage results, you can create the Response instance using the Request.CreateResponse method:var resp = Request.CreateResponse<IEnumerable<Album>>(HttpStatusCode.OK, albums); This provides you an HttpResponse object that's pre-configured with the default formatter based on Content Negotiation. Once you have an HttpResponse object you can easily control most HTTP aspects on this object. What's sweet here is that there are many more detailed properties on HttpResponse than the core ASP.NET Response object, with most options being explicitly configurable with enumerations that make it easy to pick the right headers and response codes from a list of valid codes. It makes HTTP features available much more discoverable even for non-hardcore REST/HTTP geeks. Non-Serialized Results The output returned doesn’t have to be a serialized value but can also be raw data, like strings, binary data or streams. You can use the HttpResponseMessage.Content object to set a number of common Content classes. Listing 5 shows how to return a binary image using the ByteArrayContent class from a Controller method. [HttpGet] public HttpResponseMessage AlbumArt(string title) { var album = AlbumData.Current.FirstOrDefault(abl => abl.AlbumName.StartsWith(title)); if (album == null) { var resp = Request.CreateResponse<ApiMessageError>( HttpStatusCode.NotFound, new ApiMessageError("Album not found")); return resp; } // kinda silly - we would normally serve this directly // but hey - it's a demo. var http = new WebClient(); var imageData = http.DownloadData(album.AlbumImageUrl); // create response and return var result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new ByteArrayContent(imageData); result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); return result; } The image retrieval from Amazon is contrived, but it shows how to return binary data using ByteArrayContent. It also demonstrates that you can easily return multiple types of content from a single controller method, which is actually quite common. If an error occurs - such as a resource can’t be found or a validation error – you can return an error response to the client that’s very specific to the error. In GetAlbumArt(), if the album can’t be found, we want to return a 404 Not Found status (and realistically no error, as it’s an image). Note that if you are not using HTTP Verb-based routing or not accessing a method that starts with Get/Post etc., you have to specify one or more HTTP Verb attributes on the method explicitly. Here, I used the [HttpGet] attribute to serve the image. Another option to handle the error could be to return a fixed placeholder image if no album could be matched or the album doesn’t have an image. When returning an error code, you can also return a strongly typed response to the client. For example, you can set the 404 status code and also return a custom error object (ApiMessageError is a class I defined) like this:return Request.CreateResponse<ApiMessageError>( HttpStatusCode.NotFound, new ApiMessageError("Album not found") );   If the album can be found, the image will be returned. The image is downloaded into a byte[] array, and then assigned to the result’s Content property. I created a new ByteArrayContent instance and assigned the image’s bytes and the content type so that it displays properly in the browser. There are other content classes available: StringContent, StreamContent, ByteArrayContent, MultipartContent, and ObjectContent are at your disposal to return just about any kind of content. You can create your own Content classes if you frequently return custom types and handle the default formatter assignments that should be used to send the data out . Although HttpResponseMessage results require more code than returning a plain .NET value from a method, it allows much more control over the actual HTTP processing than automatic processing. It also makes it much easier to test your controller methods as you get a response object that you can check for specific status codes and output messages rather than just a result value. Routing Again Ok, let’s get back to the image example. Using the original routing we have setup using HTTP Verb routing there's no good way to serve the image. In order to return my album art image I’d like to use a URL like this: http://localhost/aspnetWebApi/albums/Dirty%20Deeds/image In order to create a URL like this, I have to create a new Controller because my earlier routes pointed to the AlbumApiController using HTTP Verb routing. HTTP Verb based routing is great for representing a single set of resources such as albums. You can map operations like add, delete, update and read easily using HTTP Verbs. But you cannot mix action based routing into a an HTTP Verb routing controller - you can only map HTTP Verbs and each method has to be unique based on parameter signature. You can't have multiple GET operations to methods with the same signature. So GetImage(string id) and GetAlbum(string title) are in conflict in an HTTP GET routing scenario. In fact, I was unable to make the above Image URL work with any combination of HTTP Verb plus Custom routing using the single Albums controller. There are number of ways around this, but all involve additional controllers.  Personally, I think it’s easier to use explicit Action routing and then add custom routes if you need to simplify your URLs further. So in order to accommodate some of the other examples, I created another controller – AlbumRpcApiController – to handle all requests that are explicitly routed via actions (/albums/rpc/AlbumArt) or are custom routed with explicit routes defined in the HttpConfiguration. I added the AlbumArt() method to this new AlbumRpcApiController class. For the image URL to work with the new AlbumRpcApiController, you need a custom route placed before the default route from Listing 1.RouteTable.Routes.MapHttpRoute( name: "AlbumRpcApiAction", routeTemplate: "albums/rpc/{action}/{title}", defaults: new { title = RouteParameter.Optional, controller = "AlbumRpcApi", action = "GetAblums" } ); Now I can use either of the following URLs to access the image: Custom route: (/albums/rpc/{title}/image)http://localhost/aspnetWebApi/albums/PowerAge/image Action route: (/albums/rpc/action/{title})http://localhost/aspnetWebAPI/albums/rpc/albumart/PowerAge Sending Data to the Server To send data to the server and add a new album, you can use an HTTP POST operation. Since I’m using HTTP Verb-based routing in the original AlbumApiController, I can implement a method called PostAlbum()to accept a new album from the client. Listing 6 shows the Web API code to add a new album.public HttpResponseMessage PostAlbum(Album album) { if (!this.ModelState.IsValid) { // my custom error class var error = new ApiMessageError() { message = "Model is invalid" }; // add errors into our client error model for client foreach (var prop in ModelState.Values) { var modelError = prop.Errors.FirstOrDefault(); if (!string.IsNullOrEmpty(modelError.ErrorMessage)) error.errors.Add(modelError.ErrorMessage); else error.errors.Add(modelError.Exception.Message); } return Request.CreateResponse<ApiMessageError>(HttpStatusCode.Conflict, error); } // update song id which isn't provided foreach (var song in album.Songs) song.AlbumId = album.Id; // see if album exists already var matchedAlbum = AlbumData.Current .SingleOrDefault(alb => alb.Id == album.Id || alb.AlbumName == album.AlbumName); if (matchedAlbum == null) AlbumData.Current.Add(album); else matchedAlbum = album; // return a string to show that the value got here var resp = Request.CreateResponse(HttpStatusCode.OK, string.Empty); resp.Content = new StringContent(album.AlbumName + " " + album.Entered.ToString(), Encoding.UTF8, "text/plain"); return resp; } The PostAlbum() method receives an album parameter, which is automatically deserialized from the POST buffer the client sent. The data passed from the client can be either XML or JSON. Web API automatically figures out what format it needs to deserialize based on the content type and binds the content to the album object. Web API uses model binding to bind the request content to the parameter(s) of controller methods. Like MVC you can check the model by looking at ModelState.IsValid. If it’s not valid, you can run through the ModelState.Values collection and check each binding for errors. Here I collect the error messages into a string array that gets passed back to the client via the result ApiErrorMessage object. When a binding error occurs, you’ll want to return an HTTP error response and it’s best to do that with an HttpResponseMessage result. In Listing 6, I used a custom error class that holds a message and an array of detailed error messages for each binding error. I used this object as the content to return to the client along with my Conflict HTTP Status Code response. If binding succeeds, the example returns a string with the name and date entered to demonstrate that you captured the data. Normally, a method like this should return a Boolean or no response at all (HttpStatusCode.NoConent). The sample uses a simple static list to hold albums, so once you’ve added the album using the Post operation, you can hit the /albums/ URL to see that the new album was added. The client jQuery code to call the POST operation from the client with jQuery is shown in Listing 7. var id = new Date().getTime().toString(); var album = { "Id": id, "AlbumName": "Power Age", "Artist": "AC/DC", "YearReleased": 1977, "Entered": "2002-03-11T18:24:43.5580794-10:00", "AlbumImageUrl": http://ecx.images-amazon.com/images/…, "AmazonUrl": http://www.amazon.com/…, "Songs": [ { "SongName": "Rock 'n Roll Damnation", "SongLength": 3.12}, { "SongName": "Downpayment Blues", "SongLength": 4.22 }, { "SongName": "Riff Raff", "SongLength": 2.42 } ] } $.ajax( { url: "albums/", type: "POST", contentType: "application/json", data: JSON.stringify(album), processData: false, beforeSend: function (xhr) { // not required since JSON is default output xhr.setRequestHeader("Accept", "application/json"); }, success: function (result) { // reload list of albums page.loadAlbums(); }, error: function (xhr, status, p3, p4) { var err = "Error"; if (xhr.responseText && xhr.responseText[0] == "{") err = JSON.parse(xhr.responseText).message; alert(err); } }); The code in Listing 7 creates an album object in JavaScript to match the structure of the .NET Album class. This object is passed to the $.ajax() function to send to the server as POST. The data is turned into JSON and the content type set to application/json so that the server knows what to convert when deserializing in the Album instance. The jQuery code hooks up success and failure events. Success returns the result data, which is a string that’s echoed back with an alert box. If an error occurs, jQuery returns the XHR instance and status code. You can check the XHR to see if a JSON object is embedded and if it is, you can extract it by de-serializing it and accessing the .message property. REST standards suggest that updates to existing resources should use PUT operations. REST standards aside, I’m not a big fan of separating out inserts and updates so I tend to have a single method that handles both. But if you want to follow REST suggestions, you can create a PUT method that handles updates by forwarding the PUT operation to the POST method:public HttpResponseMessage PutAlbum(Album album) { return PostAlbum(album); } To make the corresponding $.ajax() call, all you have to change from Listing 7 is the type: from POST to PUT. Model Binding with UrlEncoded POST Variables In the example in Listing 7 I used JSON objects to post a serialized object to a server method that accepted an strongly typed object with the same structure, which is a common way to send data to the server. However, Web API supports a number of different ways that data can be received by server methods. For example, another common way is to use plain UrlEncoded POST  values to send to the server. Web API supports Model Binding that works similar (but not the same) as MVC's model binding where POST variables are mapped to properties of object parameters of the target method. This is actually quite common for AJAX calls that want to avoid serialization and the potential requirement of a JSON parser on older browsers. For example, using jQUery you might use the $.post() method to send a new album to the server (albeit one without songs) using code like the following:$.post("albums/",{AlbumName: "Dirty Deeds", YearReleased: 1976 … },albumPostCallback); Although the code looks very similar to the client code we used before passing JSON, here the data passed is URL encoded values (AlbumName=Dirty+Deeds&YearReleased=1976 etc.). Web API then takes this POST data and maps each of the POST values to the properties of the Album object in the method's parameter. Although the client code is different the server can both handle the JSON object, or the UrlEncoded POST values. Dynamic Access to POST Data There are also a few options available to dynamically access POST data, if you know what type of data you're dealing with. If you have POST UrlEncoded values, you can dynamically using a FormsDataCollection:[HttpPost] public string PostAlbum(FormDataCollection form) { return string.Format("{0} - released {1}", form.Get("AlbumName"),form.Get("RearReleased")); } The FormDataCollection is a very simple object, that essentially provides the same functionality as Request.Form[] in ASP.NET. Request.Form[] still works if you're running hosted in an ASP.NET application. However as a general rule, while ASP.NET's functionality is always available when running Web API hosted inside of an  ASP.NET application, using the built in classes specific to Web API makes it possible to run Web API applications in a self hosted environment outside of ASP.NET. If your client is sending JSON to your server, and you don't want to map the JSON to a strongly typed object because you only want to retrieve a few simple values, you can also accept a JObject parameter in your API methods:[HttpPost] public string PostAlbum(JObject jsonData) { dynamic json = jsonData; JObject jalbum = json.Album; JObject juser = json.User; string token = json.UserToken; var album = jalbum.ToObject<Album>(); var user = juser.ToObject<User>(); return String.Format("{0} {1} {2}", album.AlbumName, user.Name, token); } There quite a few options available to you to receive data with Web API, which gives you more choices for the right tool for the job. Unfortunately one shortcoming of Web API is that POST data is always mapped to a single parameter. This means you can't pass multiple POST parameters to methods that receive POST data. It's possible to accept multiple parameters, but only one can map to the POST content - the others have to come from the query string or route values. I have a couple of Blog POSTs that explain what works and what doesn't here: Passing multiple POST parameters to Web API Controller Methods Mapping UrlEncoded POST Values in ASP.NET Web API   Handling Delete Operations Finally, to round out the server API code of the album example we've been discussin, here’s the DELETE verb controller method that allows removal of an album by its title:public HttpResponseMessage DeleteAlbum(string title) { var matchedAlbum = AlbumData.Current.Where(alb => alb.AlbumName == title) .SingleOrDefault(); if (matchedAlbum == null) return new HttpResponseMessage(HttpStatusCode.NotFound); AlbumData.Current.Remove(matchedAlbum); return new HttpResponseMessage(HttpStatusCode.NoContent); } To call this action method using jQuery, you can use:$(".removeimage").live("click", function () { var $el = $(this).parent(".album"); var txt = $el.find("a").text(); $.ajax({ url: "albums/" + encodeURIComponent(txt), type: "Delete", success: function (result) { $el.fadeOut().remove(); }, error: jqError }); }   Note the use of the DELETE verb in the $.ajax() call, which routes to DeleteAlbum on the server. DELETE is a non-content operation, so you supply a resource ID (the title) via route value or the querystring. Routing Conflicts In all requests with the exception of the AlbumArt image example shown so far, I used HTTP Verb routing that I set up in Listing 1. HTTP Verb Routing is a recommendation that is in line with typical REST access to HTTP resources. However, it takes quite a bit of effort to create REST-compliant API implementations based only on HTTP Verb routing only. You saw one example that didn’t really fit – the return of an image where I created a custom route albums/{title}/image that required creation of a second controller and a custom route to work. HTTP Verb routing to a controller does not mix with custom or action routing to the same controller because of the limited mapping of HTTP verbs imposed by HTTP Verb routing. To understand some of the problems with verb routing, let’s look at another example. Let’s say you create a GetSortableAlbums() method like this and add it to the original AlbumApiController accessed via HTTP Verb routing:[HttpGet] public IQueryable<Album> SortableAlbums() { var albums = AlbumData.Current; // generally should be done only on actual queryable results (EF etc.) // Done here because we're running with a static list but otherwise might be slow return albums.AsQueryable(); } If you compile this code and try to now access the /albums/ link, you get an error: Multiple Actions were found that match the request. HTTP Verb routing only allows access to one GET operation per parameter/route value match. If more than one method exists with the same parameter signature, it doesn’t work. As I mentioned earlier for the image display, the only solution to get this method to work is to throw it into another controller. Because I already set up the AlbumRpcApiController I can add the method there. First, I should rename the method to SortableAlbums() so I’m not using a Get prefix for the method. This also makes the action parameter look cleaner in the URL - it looks less like a method and more like a noun. I can then create a new route that handles direct-action mapping:RouteTable.Routes.MapHttpRoute( name: "AlbumRpcApiAction", routeTemplate: "albums/rpc/{action}/{title}", defaults: new { title = RouteParameter.Optional, controller = "AlbumRpcApi", action = "GetAblums" } ); As I am explicitly adding a route segment – rpc – into the route template, I can now reference explicit methods in the Web API controller using URLs like this: http://localhost/AspNetWebApi/rpc/SortableAlbums Error Handling I’ve already done some minimal error handling in the examples. For example in Listing 6, I detected some known-error scenarios like model validation failing or a resource not being found and returning an appropriate HttpResponseMessage result. But what happens if your code just blows up or causes an exception? If you have a controller method, like this:[HttpGet] public void ThrowException() { throw new UnauthorizedAccessException("Unauthorized Access Sucka"); } You can call it with this: http://localhost/AspNetWebApi/albums/rpc/ThrowException The default exception handling displays a 500-status response with the serialized exception on the local computer only. When you connect from a remote computer, Web API throws back a 500  HTTP Error with no data returned (IIS then adds its HTML error page). The behavior is configurable in the GlobalConfiguration:GlobalConfiguration .Configuration .IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Never; If you want more control over your error responses sent from code, you can throw explicit error responses yourself using HttpResponseException. When you throw an HttpResponseException the response parameter is used to generate the output for the Controller action. [HttpGet] public void ThrowError() { var resp = Request.CreateResponse<ApiMessageError>( HttpStatusCode.BadRequest, new ApiMessageError("Your code stinks!")); throw new HttpResponseException(resp); } Throwing an HttpResponseException stops the processing of the controller method and immediately returns the response you passed to the exception. Unlike other Exceptions fired inside of WebAPI, HttpResponseException bypasses the Exception Filters installed and instead just outputs the response you provide. In this case, the serialized ApiMessageError result string is returned in the default serialization format – XML or JSON. You can pass any content to HttpResponseMessage, which includes creating your own exception objects and consistently returning error messages to the client. Here’s a small helper method on the controller that you might use to send exception info back to the client consistently:private void ThrowSafeException(string message, HttpStatusCode statusCode = HttpStatusCode.BadRequest) { var errResponse = Request.CreateResponse<ApiMessageError>(statusCode, new ApiMessageError() { message = message }); throw new HttpResponseException(errResponse); } You can then use it to output any captured errors from code:[HttpGet] public void ThrowErrorSafe() { try { List<string> list = null; list.Add("Rick"); } catch (Exception ex) { ThrowSafeException(ex.Message); } }   Exception Filters Another more global solution is to create an Exception Filter. Filters in Web API provide the ability to pre- and post-process controller method operations. An exception filter looks at all exceptions fired and then optionally creates an HttpResponseMessage result. Listing 8 shows an example of a basic Exception filter implementation.public class UnhandledExceptionFilter : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { HttpStatusCode status = HttpStatusCode.InternalServerError; var exType = context.Exception.GetType(); if (exType == typeof(UnauthorizedAccessException)) status = HttpStatusCode.Unauthorized; else if (exType == typeof(ArgumentException)) status = HttpStatusCode.NotFound; var apiError = new ApiMessageError() { message = context.Exception.Message }; // create a new response and attach our ApiError object // which now gets returned on ANY exception result var errorResponse = context.Request.CreateResponse<ApiMessageError>(status, apiError); context.Response = errorResponse; base.OnException(context); } } Exception Filter Attributes can be assigned to an ApiController class like this:[UnhandledExceptionFilter] public class AlbumRpcApiController : ApiController or you can globally assign it to all controllers by adding it to the HTTP Configuration's Filters collection:GlobalConfiguration.Configuration.Filters.Add(new UnhandledExceptionFilter()); The latter is a great way to get global error trapping so that all errors (short of hard IIS errors and explicit HttpResponseException errors) return a valid error response that includes error information in the form of a known-error object. Using a filter like this allows you to throw an exception as you normally would and have your filter create a response in the appropriate output format that the client expects. For example, an AJAX application can on failure expect to see a JSON error result that corresponds to the real error that occurred rather than a 500 error along with HTML error page that IIS throws up. You can even create some custom exceptions so you can differentiate your own exceptions from unhandled system exceptions - you often don't want to display error information from 'unknown' exceptions as they may contain sensitive system information or info that's not generally useful to users of your application/site. This is just one example of how ASP.NET Web API is configurable and extensible. Exception filters are just one example of how you can plug-in into the Web API request flow to modify output. Many more hooks exist and I’ll take a closer look at extensibility in Part 2 of this article in the future. Summary Web API is a big improvement over previous Microsoft REST and AJAX toolkits. The key features to its usefulness are its ease of use with simple controller based logic, familiar MVC-style routing, low configuration impact, extensibility at all levels and tight attention to exposing and making HTTP semantics easily discoverable and easy to use. Although none of the concepts used in Web API are new or radical, Web API combines the best of previous platforms into a single framework that’s highly functional, easy to work with, and extensible to boot. I think that Microsoft has hit a home run with Web API. Related Resources Where does ASP.NET Web API fit? Sample Source Code on GitHub Passing multiple POST parameters to Web API Controller Methods Mapping UrlEncoded POST Values in ASP.NET Web API Creating a JSONP Formatter for ASP.NET Web API Removing the XML Formatter from ASP.NET Web API Applications© Rick Strahl, West Wind Technologies, 2005-2012Posted in Web Api   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

  • jQuery doesn't work in IE8?

    - by Wade D Ouellet
    Hi, I am working on a site here: mfm.treethink.net All the jquery works fine in Firefox, Chrome and Safari but on IE8 it gives me errors and the banner at the top doesn't work (which uses the crossSlide jQuery plugin) and as well the image rollovers don't work with the colour change. IE8 is telling me that the errors are on lines 53, 134 and 149 in the source, all of those lines are where the jquery function is declared. $(document).ready(function(){ I am running jquery 1.4. Oddly enough, the other piece of jQuery I have on that page works, the artist browse/select menu on the right. But the banner and image rollovers don't. Here are all the scripts I'm running: 1: the banner - doesn't work in IE8 <script type="text/javascript"> $(function() { $('#banner').crossSlide({ sleep: 5, fade: 1 }, [ <?php $pages = get_posts('numberposts=2000&post_type=artist&post_status=publish'); $i = 1; foreach( $pages as $page ) { $content = $page->post_title; if( empty($content) ) continue; $content = apply_filters('the_content', $content); ?> { src: '/wp-content/uploads/<?php echo $page->post_name ?>.jpg' }, <?php $i++; } ?> ]); }); </script> 2 - image rollovers - doesn't work in IE8 <script type="text/javascript"> $(function(){ $("ul#artists li").hover(function() { /* On hover */ var thumbOver = $(this).find("img").attr("src"); /* Find image source */ /* Swap background */ $(this).find("a.thumb").css({'background' : 'url(' + thumbOver + ') center bottom no-repeat'}); $(this).find("span").stop().fadeTo('fast', 0 , function() { $(this).hide() }); } , function() { $(this).find("span").stop().fadeTo('fast', 1).show(); }); }); </script> 3 - the artist select - works in IE 8 <script> $("#browse-select").change(function() { window.location.href = $(this).val(); }); </script> These scripts were done by referencing previously made scripts, like I said I'm still new to jQuery. The second works in IE8 and the first one is the one that doesn't. I noticed the third one, the only one working, is written differently than the first two non-working ones without a function declaration at the top. Could this have anything to do with it? Any help figuring out this problem would be so appreciated. Thanks a lot, Wade

    Read the article

  • jquery data selector

    - by Tauren
    I need to select elements based on values stored in an element's .data() object. At a minimum, I'd like to select top-level data properties using selectors, perhaps like this: $('a').data("category","music"); $('a:data(category=music)'); Or perhaps the selector would be in regular attribute selector format: $('a[category=music]'); Or in attribute format, but with a specifier to indicate it is in .data(): $('a[:category=music]'); I've found James Padolsey's implementation to look simple, yet good. The selector formats above mirror methods shown on that page. There is also this Sizzle patch. For some reason, I recall reading a while back that jQuery 1.4 would include support for selectors on values in the jquery .data() object. However, now that I'm looking for it, I can't find it. Maybe it was just a feature request that I saw. Is there support for this and I'm just not seeing it? Ideally, I'd like to support sub-properties in data() using dot notation. Like this: $('a').data("user",{name: {first:"Tom",last:"Smith"},username: "tomsmith"}); $('a[:user.name.first=Tom]'); I also would like to support multiple data selectors, where only elements with ALL specified data selectors are found. The regular jquery multiple selector does an OR operation. For instance, $('a.big, a.small') selects a tags with either class big or small). I'm looking for an AND, perhaps like this: $('a').data("artist",{id: 3281, name: "Madonna"}); $('a').data("category","music"); $('a[:category=music && :artist.name=Madonna]'); Lastly, it would be great if comparison operators and regex features were available on data selectors. So $(a[:artist.id>5000]) would be possible. I realize I could probably do much of this using filter(), but it would be nice to have a simple selector format. What solutions are available to do this? Is Jame's Padolsey's the best solution at this time? My concern is primarily in regards to performance, but also in the extra features like sub-property dot-notation and multiple data selectors. Are there other implementations that support these things or are better in some way?

    Read the article

  • Writing JSON with XSLT

    - by JP
    Hi, I'm trying to write XSLT to transform a specific web page to JSON. The following code demonstrates how Ruby would do this conversion, but the XSLT doesn't generate valid JSON (there's one too many commas inside the array) - anyone know how to write XSLT to generate valid JSON? require 'rubygems' require 'nokogiri' require 'open-uri' doc = Nokogiri::HTML(open('http://bbc.co.uk/radio1/playlist')) xslt = Nokogiri::XSLT(DATA.read) puts out = xslt.transform(doc) # Now follows the XSLT __END__ <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml"> <xsl:output method="text" encoding="UTF-8" media-type="text/plain"/> <xsl:template match="/"> [ <xsl:for-each select="//*[@id='playlist_a']//div[@class='artists_and_songs']//ul[@class='clearme']"> {'artist':'<xsl:value-of select="li[@class='artist']" />','track':'<xsl:value-of select="li[@class='song']" />'}, </xsl:for-each> ] </xsl:template> </xsl:stylesheet>

    Read the article

  • Prolog Program for a recordings database

    - by RP
    I have three types of facts: album(code, artist, title, date). songs(code, songlist). musicians(code, list). Example: album(123, 'Rolling Stones', 'Beggars Banquet', 1968). songs(123, ['Sympathy for the Devil', 'Street Fighting Man']). musicians(123, [[vocals, 'Mick Jagger'], [guitar, 'Keith Richards', 'Brian Jones']]. I need to create these 4 rules: together(X,Y) This succeeds if X and Y have played on the same album. artistchain(X,Y) This succeeds if a chain of albums exists from X to Y; two musicians are linked in the chain by 'together'. role(X,Y) This succeeds if X had role Y (e.g. guitar) ever. song(X,Y) This succeeds if artist X recorded song Y. Any help?

    Read the article

  • Reason for Null pointer Exception

    - by Rahul Varma
    Hi, I cant figure out why my program is showing null pointer exception. Plz help me...Here's the program... public class MusicListActivity extends Activity { List<HashMap<String, String>> songNodeDet = new ArrayList<HashMap<String,String>>(); HashMap<?,?>[] songNodeWeb; XMLRPCClient client; String logInSess; ArrayList<String> paths=new ArrayList<String>(); public ListAdapter adapter ; Object[] websongListObject; List<SongsList> SngList=new ArrayList<SongsList>(); Runnable r; ProgressDialog p; ListView lv; String s; @Override public void onCreate(Bundle si){ super.onCreate(si); setContentView(R.layout.openadiuofile); lv=(ListView)findViewById(R.id.list1); r=new Runnable(){ public void run(){ try{ getSongs(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XMLRPCException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; Thread t=new Thread(r,"background"); t.start(); Log.e("***","process over"); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); } private Runnable returnRes = new Runnable() { @Override public void run() { Log.d("handler","handler"); removeDialog(0); p.dismiss(); list(); } }; public void list() { Log.d("#####","#####"); LayoutInflater inflater=getLayoutInflater(); String[] from={}; int[] n={}; adapter=new SongsAdapter(getApplicationContext(),songNodeDet,R.layout.row,from,n,inflater); lv.setAdapter(adapter);} private Handler handler = new Handler() { public void handleMessage(Message msg){ Log.d("*****","handler"); removeDialog(0); p.dismiss(); } }; public void webObjectList(Object[] imgListObj,String logInSess) throws XMLRPCException{ songNodeWeb = new HashMap<?,?>[imgListObj.length]; if(imgListObj!=null){ Log.e("completed","completed"); for(int i=0;i<imgListObj.length;i++){ //imgListObj.length songNodeWeb[i]=(HashMap<?,?>)imgListObj[i]; String nodeid=(String) songNodeWeb[i].get("nid"); break; Log.e("img",i+"completed"); HashMap<String,String> nData=new HashMap<String,String>(); nData.put("nid",nodeid); Object nodeget=client.call("node.get",logInSess,nodeid); HashMap<?,?> imgNode=(HashMap<?,?>)nodeget; String titleName=(String) imgNode.get("titles"); String movieName=(String) imgNode.get("album"); String singerName=(String) imgNode.get("artist"); nData.put("titles", titleName); nData.put("album", movieName); nData.put("artist", singerName); Object[] imgObject=(Object[])imgNode.get("field_image"); HashMap<?,?>[] imgDetails=new HashMap<?,?>[imgObject.length]; imgDetails[0]=(HashMap<?, ?>)imgObject[0]; String path=(String) imgDetails[0].get("filepath"); if(path.contains(" ")){ path=path.replace(" ", "%20"); } String imgPath="http://www.gorinka.com/"+path; paths.add(imgPath); nData.put("path", imgPath); Log.e("my path",path); String mime=(String)imgDetails[0].get("filemime"); nData.put("mime", mime); SongsList songs=new SongsList(titleName,movieName,singerName,imgPath,imgPath); SngList.add(i,songs); songNodeDet.add(i,nData); } Log.e("paths values",paths.toString()); // return imgNodeDet; handler.sendEmptyMessage(0); } } public void getSongs() throws MalformedURLException, XMLRPCException { String ur="http://www.gorinka.com/?q=services/xmlrpc"; URL u=new URL(ur); client = new XMLRPCClient(u); //Connecting to the website HashMap<?, ?> siteConn =(HashMap<?, ?>) client.call("system.connect"); // Getting initial sessio id String initSess=(String)siteConn.get("sessid"); //Login to the site using session id HashMap<?, ?> logInConn =(HashMap<?, ?>) client.call("user.login",initSess,"prakash","stellentsoft2009"); //Getting Login sessid logInSess=(String)logInConn.get("sessid"); websongListObject =(Object[]) client.call("nodetype.get",logInSess,""); webObjectList(websongListObject,logInSess); Log.d("webObjectList","webObjectList"); runOnUiThread(returnRes); } } Here's the Adapter associated... public class SongsAdapter extends SimpleAdapter{ static List<HashMap<String,String>> songsList; Context context; LayoutInflater inflater; public SongsAdapter(Context context,List<HashMap<String,String>> imgListWeb,int layout,String[] from,int[] to,LayoutInflater inflater) { super(context,songsList,layout,from,to); this.songsList=songsList; this.context=context; this.inflater=inflater; // TODO Auto-generated constructor stub } @Override public View getView(int postition,View convertView,ViewGroup parent)throws java.lang.OutOfMemoryError{ try { View v = ((LayoutInflater) inflater).inflate(R.layout.row,null); ImageView images=(ImageView)v.findViewById(R.id.image); TextView tvTitle=(TextView)v.findViewById(R.id.text1); TextView tvAlbum=(TextView)v.findViewById(R.id.text2); TextView tvArtist=(TextView)v.findViewById(R.id.text3); HashMap<String,String> songsHash=songsList.get(postition); String path=songsHash.get("path"); String title=songsHash.get("title"); String album=songsHash.get("album"); String artist=songsHash.get("artist"); String imgPath=path; final ImageView imageView = (ImageView) v.findViewById(R.id.image); AsyncImageLoaderv asyncImageLoader=new AsyncImageLoaderv(); Bitmap cachedImage = asyncImageLoader.loadDrawable(imgPath, new AsyncImageLoaderv.ImageCallback() { public void imageLoaded(Bitmap imageDrawable, String imageUrl) { imageView.setImageBitmap(imageDrawable); } }); imageView.setImageBitmap(cachedImage); tvTitle.setText(title); tvAlbum.setText(album); tvArtist.setText(artist); return v; } catch(Exception e){ Log.e("error",e.toString()); } return null; } public static Bitmap loadImageFromUrl(String url) { InputStream inputStream;Bitmap b; try { inputStream = (InputStream) new URL(url).getContent(); BitmapFactory.Options bpo= new BitmapFactory.Options(); bpo.inSampleSize=2; b=BitmapFactory.decodeStream(inputStream, null,bpo ); return b; } catch (IOException e) { throw new RuntimeException(e); } } } Here is what logcat is showing... 04-23 16:02:02.211: ERROR/completed(1450): completed 04-23 16:02:02.211: ERROR/paths values(1450): [] 04-23 16:02:02.211: DEBUG/*****(1450): handler 04-23 16:02:02.211: DEBUG/AndroidRuntime(1450): Shutting down VM 04-23 16:02:02.211: WARN/dalvikvm(1450): threadid=3: thread exiting with uncaught exception (group=0x4001aa28) 04-23 16:02:02.222: ERROR/AndroidRuntime(1450): Uncaught handler: thread main exiting due to uncaught exception 04-23 16:02:02.241: DEBUG/webObjectList(1450): webObjectList 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): java.lang.NullPointerException 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at com.stellent.gorinka.MusicListActivity$2.handleMessage(MusicListActivity.java:81) 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at android.os.Handler.dispatchMessage(Handler.java:99) 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at android.os.Looper.loop(Looper.java:123) 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at android.app.ActivityThread.main(ActivityThread.java:4203) 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at java.lang.reflect.Method.invokeNative(Native Method) 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at java.lang.reflect.Method.invoke(Method.java:521) 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549) 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at dalvik.system.NativeStart.main(Native Method) I have declared the getter and setter methods in a seperate claa named SongsList. Plz help me determine the problem...

    Read the article

  • How can I stop sorl thumbnail from breaking with very long filenames?

    - by bitbutter
    I've noticed that when working with SORL thumbnail, sometimes a user will upload an image with a very long filename, longer than the varfield in the database can hold. The name gets truncated in the database and the project gives errors whenever the image is requested. Is there a smart and safe way to have django automatically truncate long filenames in sorl uploads (prior to saving them in the database) to prevent this sort of thing? As reference, here's how the relevant model from my current project looks: class ArtistImage(models.Model): artist = models.ForeignKey(Artist) position = models.IntegerField() image = ThumbnailField( thumbnail_tag='<span class="artistimagewrapper"><img class="artistimage" src="%(src)s" width="%(width)s" height="%(height)s"></span>', upload_to='uploaded_images/artistimages', size=(900,900), quality=100, options={'crop': 'center'}, extra_thumbnails={ 'small':{ 'size':(92,92), 'quality':100, 'options':{'crop': 'center'}, } } ) class Meta: ordering = ('image',) def __unicode__(self): return (u"%s" % self.image)

    Read the article

  • Using only alphanumeric characters(a-z) inside toCharArray

    - by Aaron
    Below you will find me using toCharArray in order to send a string to array. I then MOVE the value of the letter using a for statement... for(i = 0; i < letter.length; i++){ letter[i] += (shiftCode); System.out.print(letter[i]); } However, when I use shiftCode to move the value such as... a shifted by -1; I get a symbol @. Is there a way to send the string to shiftCode or tell shiftCode to ONLY use letters? I need it to see my text, like "aaron", and when I use the for statement iterate through a-z only and ignore all symbols and numbers. I THINK it is as simple as... letter=codeWord.toCharArray(a,z); But trying different forms of that and googling it didn't give me any results. Perhaps it has to do with regex or something? Below you will find a complete copy of my program; it works exactly how I want it to do; but it iterates through letters and symbols. I also tried finding instructions online for toCharArray but if there exists any arguments I can't locate them. My program... import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /* * Aaron L. Jones * CS219 * AaronJonesProg3 * * This program is designed to - * Work as a Ceasar Cipher */ /** * * Aaron Jones */ public class AaronJonesProg3 { static String codeWord; static int shiftCode; static int i; static char[] letter; /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { // Instantiating that Buffer Class // We are going to use this to read data from the user; in buffer // For performance related reasons BufferedReader reader; // Building the reader variable here // Just a basic input buffer (Holds things for us) reader = new BufferedReader(new InputStreamReader(System.in)); // Java speaks to us here / We get it to query our user System.out.print("Please enter text to encrypt: "); // Try to get their input here try { // Get their codeword using the reader codeWord = reader.readLine(); // Make that input upper case codeWord = codeWord.toUpperCase(); // Cut the white space out codeWord = codeWord.replaceAll("\\s",""); // Make it all a character array letter = codeWord.toCharArray(); } // If they messed up the input we let them know here and end the prog. catch(Throwable t) { System.out.println(t.toString()); System.out.println("You broke it. But you impressed me because" + "I don't know how you did it!"); } // Java Speaks / Lets get their desired shift value System.out.print("Please enter the shift value: "); // Try for their input try { // We get their number here shiftCode = Integer.parseInt(reader.readLine()); } // Again; if the user broke it. We let them know. catch(java.lang.NumberFormatException ioe) { System.out.println(ioe.toString()); System.out.println("How did you break this? Use a number next time!"); } for(i = 0; i < letter.length; i++){ letter[i] += (shiftCode); System.out.print(letter[i]); } System.out.println(); /**************************************************************** **************************************************************** ***************************************************************/ // Java speaks to us here / We get it to query our user System.out.print("Please enter text to decrypt: "); // Try to get their input here try { // Get their codeword using the reader codeWord = reader.readLine(); // Make that input upper case codeWord = codeWord.toUpperCase(); // Cut the white space out codeWord = codeWord.replaceAll("\\s",""); // Make it all a character array letter = codeWord.toCharArray(); } // If they messed up the input we let them know here and end the prog. catch(Throwable t) { System.out.println(t.toString()); System.out.println("You broke it. But you impressed me because" + "I don't know how you did it!"); } // Java Speaks / Lets get their desired shift value System.out.print("Please enter the shift value: "); // Try for their input try { // We get their number here shiftCode = Integer.parseInt(reader.readLine()); } // Again; if the user broke it. We let them know. catch(java.lang.NumberFormatException ioe) { System.out.println(ioe.toString()); System.out.println("How did you break this? Use a number next time!"); } for(i = 0; i < letter.length; i++){ letter[i] += (shiftCode); System.out.print(letter[i]); } System.out.println(); } }

    Read the article

  • AIR:- Desktop Application related to Window Component (Need some work around)

    - by Mahesh Parate
    Create custom component which contains Combobox and Datagrid. Application conations two button 1) Same Window and 2) New Window. (Label of two button) When you click on “Same Window” button your custom component should get added dynamically in your application. And when you click on “New Window” button your custom component should get open in different window (it should get shifted from application and should appear in Window component). Issue faced:- Clicking on Combobox, list is not getting open as change event doesn’t get fired in Native Window as it looses reference from main application. Issue with DataGrid in Native window (AIR). • DataGridEvent.COLUMN_STRETCH event get affected if try to open datagrid in Native Window. • DataGridEvent get fired but takes long time or even stuck while column stretch Note: Application is an Desktop Application. Only one instance is created in Application for your custom component to preserve current state on your custom component it can be Style, data, or other subcomponent state of your custom component (as above mentioned 2 component are just sample). Please find sample code below:- DataGridStretchIssue.mxml:- < ?xml version="1.0" encoding="utf-8"? < mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*" width="800" height="500" < mx:Script < ![CDATA[ import mx.events.FlexEvent; import mx.core.Window; private var dgComp:DataGridComp = new DataGridComp(); private var win:Window; private function clickHandler(event:Event):void{ dgComp.percentWidth = 100; dgComp.percentHeight = 100; dgComp.x = 50; dgComp.y = 100; if(win){ win.close(); } this.addChild(dgComp); } private function openClickHandler(event:MouseEvent):void{ dgComp.x = 50; dgComp.y = 100; win = new Window();; win.width = 800; win.height = 500; win.addChild(dgComp); dgComp.percentWidth = 100; dgComp.percentHeight = 100; dgComp.x = 50; dgComp.y = 100; win.open(true) } ]]> < /mx:Script < mx:HBox <mx:Button id="btnID" click="clickHandler(event)" label="Same Window"/> <mx:Button id="btnIDOpen" click="openClickHandler(event)" label="New Window"/> < /mx:HBox < /mx:WindowedApplication DataGridComp.mxml < ?xml version="1.0" encoding="utf-8"? < mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%" <mx:Script> <![CDATA[ import mx.events.DataGridEvent; import mx.collections.ArrayCollection; [Bindable] public var cards:ArrayCollection = new ArrayCollection( [ {label:"Visa", data:1}, {label:"MasterCard", data:2}, {label:"American Express", data:3} ]); private function stretchFn(event:DataGridEvent):void{ trace("--- Stretched---") } ]]> </mx:Script> <mx:HBox> <mx:ComboBox dataProvider="{cards}" width="150"/> <mx:DataGrid columnStretch="stretchFn(event)" > <mx:ArrayCollection> <mx:Object> <mx:Artist>Pavement</mx:Artist> <mx:Price>11.99</mx:Price> <mx:Album>Slanted and Enchanted</mx:Album> </mx:Object> <mx:Object> <mx:Artist>Pavement</mx:Artist> <mx:Album>Brighten the Corners</mx:Album> <mx:Price>11.99</mx:Price> </mx:Object> </mx:ArrayCollection> </mx:DataGrid> </mx:HBox> < /mx:Canvas Can any one suggest me some work around to make my code workable... :)

    Read the article

  • Wordpress order/sort problem

    - by Spencer
    Hi, The Problem: I would like to sort my posts based on custom fields, when the user clicks on a link. I don't know if there is a parameter that can be passed via url to reorder posts. Comparison: I would like it to work similar to how you can sort songs in iTunes. The user simply clicks the "Artist" button and the songs are reorder alphabetically by artist's name. Example: The custom field could be the location where I was when I wrote the post. "Location = home" or "Location = office" etc. When the user click a links the page is reload with the posts reordered. Posts from home before ones from the office. Thanks for the help.

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >