Search Results

Search found 2037 results on 82 pages for 'khanna param'.

Page 6/82 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • What should I do if i have a factory method which requires different parameters for different implem

    - by Sam Holder
    I have an interface, IMessage and a class which have several methods for creating different types of message like so: class MessageService { IMessage TypeAMessage(param 1, param 2) IMessage TypeBMessage(param 1, param 2, param 3, param 4) IMessage TypeCMessage(param 1, param 2, param 3) IMessage TypeDMessage(param 1) } I don't want this class to do all the work for creating these messages so it simply delegates to a MessageCreatorFactory which produces an IMessageCreator depending on the type given (an enumeration based on the type of the message TypeA, TypeB, TypeC etc) interface IMessageCreator { IMessage Create(MessageParams params); } So I have 4 implementations of IMessageCreator: TypeAMessageCreator, TypeBMessageCreator, TypeCMessageCreator, TypeDMessageCreator I ok with this except for the fact that because each type requires different parameters I have had to create a MessageParams object which contains 4 properties for the 4 different params, but only some of them are used in each IMessageCreator. Is there an alternative to this? One other thought I had was to have a param array as the parameter in the Create emthod, but this seems even worse as you don't have any idea what the params are. Or to create several overloads of Create in the interface and have some of them throw an exception if they are not suitable for that particular implementation (ie you called a method which needs more params, so you should have called one of the other overloads.) Does this seem ok? Is there a better solution?

    Read the article

  • Debugging Tips for Skinning

    - by Christian David Straub
    Another guest post by Jeanne Waldman.If you are developing a skin for your Fusion Application in JDeveloper you should know these tips.   1. Firebug is your friend 2. Uncompress the css style classes 3. CHECK_FILE_MODIFICATION so that you see your skinning changes right away 4. View the generated CSS File   1. Firebug is your friend Install Firebug (http://getfirebug.com/layout) into Firefox and use it to view your rendered jspx page in the browser. You can select the HTML dom nodes on your page and you can see the css styles applied to each dom node.   2. Uncompress the css style classes By default the styleclasses that are rendered are compressed. You may see style classes like class="x10" and class="x2e". But in your skin css file you have styleclasses like: af|inputText::content or af|panelBox::header   It is easier for you to develop a skin and debug a skin with Firebug if you see the uncompressed styleclasses. To do this, a. open web.xml b. add   <context-param>     <param-name>org.apache.myfaces.trinidad.DISABLE_CONTENT_COMPRESSION</param-name>     <param-value>true</param-value>   </context-param> c. save d. restart the server and re-run your page.   3. CHECK_FILE_MODIFICATION so that you see your skinning changes right away   For performance sake the ADF Faces framework does not check if you skin .css file has changed on every render. But this is exactly what you want to happen when you are developing or debugging a skin. You want your changes to get noticed right away, without restarting the server.   To do this, a. open web.xml b. add   <context-param>     <description>If this parameter is true, there will be an automatic check of the modification date of your JSPs, and saved state will be discarded when JSP's change. It will also automatically check if your skinning css files have changed without you having to restart the server. This makes development easier, but adds overhead. For this reason this parameter should be set to false when your application is deployed.</description>     <param-name>org.apache.myfaces.trinidad.CHECK_FILE_MODIFICATION</param-name>     <param-value>false</param-value>   </context-param> c. save d. restart the server and re-run your page. e. from then on, you can change your skin's .css file, save it and refresh your page and you should see the changes right away   4. View the generated CSS File   There are different ways to view the generated CSS File which is your skin's css file merged in with all the skins it extends and processed and generated to the filesystem and linked to your generated html page. One way is to view it with Firebug. The problem with this approach is you might see something that is a little different than the actual css file because Firebug may do some extra processing. I like to view the generated css file by: Right click on your page in the browser 

    Read the article

  • Download a .asp / .asx video file (Ubuntu)

    - by Adam Matan
    Hi, My local TV station offers streaming video of recorded documentaries, using a XML-like file with a.asx extension. Is there a way (preferably Ubuntu CLI) to download the file? Thanks, Adam PS - the file contents: <asx version="3.0"> <!-- GMX --> <param name="encoding" value="utf-8" /> <title>CastUP: V0109-msheni-Hayim_Hefer-120510 </title> <MOREINFO HREF = "" /> <PARAM NAME="Prebuffer" VALUE="true" /> <entry> <ref href="http://s3awm.castup.net/server12/31/176/17607833-61.wmv?ct=IL&rg=BZ&aid=31&ts=0&cu=91A297E2-5359-416A-912B-2D9BC106E491" /> <ref href="http://s0dwm.castup.net/server12/31/176/17607833-61.wmv?ct=IL&rg=BZ&aid=31&ts=0&cu=91A297E2-5359-416A-912B-2D9BC106E491" /> <ref href="http://s0ewm.castup.net/server12/31/176/17607833-61.wmv?ct=IL&rg=BZ&aid=31&ts=0&cu=91A297E2-5359-416A-912B-2D9BC106E491" /> <ref href="http://s0fwm.castup.net/server12/31/176/17607833-61.wmv?ct=IL&rg=BZ&aid=31&ts=0&cu=91A297E2-5359-416A-912B-2D9BC106E491" /> <ref href="http://s0gwm.castup.net/server12/31/176/17607833-61.wmv?ct=IL&rg=BZ&aid=31&ts=0&cu=91A297E2-5359-416A-912B-2D9BC106E491" /> <PARAM NAME="CanSkipBack" VALUE="No"/> <PARAM NAME="CanSkipForward" VALUE="No"/> <PARAM NAME="CanSeek" VALUE="No"/> <title>mondial_2010 </title> <PARAM NAME="Prebuffer" VALUE="true" /> <PARAM NAME="CastUP_Content_Config" VALUE="" /> </entry> <entry> <PARAM NAME="EntryType" VALUE="Content" /> <param name="encoding" value="utf-8" /> <PARAM NAME="CastUP_AssociatedURL" VALUE="" /> <PARAM NAME="CastUP_Content_Config" VALUE="" /> <PARAM NAME="CastUP_Content_ClipMediaID" VALUE="5382858" /> <author>iba</author> <title>CastUP: V0109-msheni-Hayim_Hefer-120510 </title> <PARAM NAME="Prebuffer" VALUE="true" /> <ref href="mms://s3awm.castup.net/server12/31/174/17482045-61.wmv?ct=IL&rg=BZ&aid=31&ts=0&cu=91A297E2-5359-416A-912B-2D9BC106E491" /> <ref href="mms://s0dwm.castup.net/server12/31/174/17482045-61.wmv?ct=IL&rg=BZ&aid=31&ts=0&cu=91A297E2-5359-416A-912B-2D9BC106E491" /> <ref href="mms://s0ewm.castup.net/server12/31/174/17482045-61.wmv?ct=IL&rg=BZ&aid=31&ts=0&cu=91A297E2-5359-416A-912B-2D9BC106E491" /> <ref href="mms://s0fwm.castup.net/server12/31/174/17482045-61.wmv?ct=IL&rg=BZ&aid=31&ts=0&cu=91A297E2-5359-416A-912B-2D9BC106E491" /> <ref href="mms://s0gwm.castup.net/server12/31/174/17482045-61.wmv?ct=IL&rg=BZ&aid=31&ts=0&cu=91A297E2-5359-416A-912B-2D9BC106E491" /> </entry> </asx>

    Read the article

  • Creating a dynamic proxy generator – Part 1 – Creating the Assembly builder, Module builder and cach

    - by SeanMcAlinden
    I’ve recently started a project with a few mates to learn the ins and outs of Dependency Injection, AOP and a number of other pretty crucial patterns of development as we’ve all been using these patterns for a while but have relied totally on third part solutions to do the magic. We thought it would be interesting to really get into the details by rolling our own IoC container and hopefully learn a lot on the way, and you never know, we might even create an excellent framework. The open source project is called Rapid IoC and is hosted at http://rapidioc.codeplex.com/ One of the most interesting tasks for me is creating the dynamic proxy generator for enabling Aspect Orientated Programming (AOP). In this series of articles, I’m going to track each step I take for creating the dynamic proxy generator and I’ll try my best to explain what everything means - mainly as I’ll be using Reflection.Emit to emit a fair amount of intermediate language code (IL) to create the proxy types at runtime which can be a little taxing to read. It’s worth noting that building the proxy is without a doubt going to be slightly painful so I imagine there will be plenty of areas I’ll need to change along the way. Anyway lets get started…   Part 1 - Creating the Assembly builder, Module builder and caching mechanism Part 1 is going to be a really nice simple start, I’m just going to start by creating the assembly, module and type caches. The reason we need to create caches for the assembly, module and types is simply to save the overhead of recreating proxy types that have already been generated, this will be one of the important steps to ensure that the framework is fast… kind of important as we’re calling the IoC container ‘Rapid’ – will be a little bit embarrassing if we manage to create the slowest framework. The Assembly builder The assembly builder is what is used to create an assembly at runtime, we’re going to have two overloads, one will be for the actual use of the proxy generator, the other will be mainly for testing purposes as it will also save the assembly so we can use Reflector to examine the code that has been created. Here’s the code: DynamicAssemblyBuilder using System; using System.Reflection; using System.Reflection.Emit; namespace Rapid.DynamicProxy.Assembly {     /// <summary>     /// Class for creating an assembly builder.     /// </summary>     internal static class DynamicAssemblyBuilder     {         #region Create           /// <summary>         /// Creates an assembly builder.         /// </summary>         /// <param name="assemblyName">Name of the assembly.</param>         public static AssemblyBuilder Create(string assemblyName)         {             AssemblyName name = new AssemblyName(assemblyName);               AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(                     name, AssemblyBuilderAccess.Run);               DynamicAssemblyCache.Add(assembly);               return assembly;         }           /// <summary>         /// Creates an assembly builder and saves the assembly to the passed in location.         /// </summary>         /// <param name="assemblyName">Name of the assembly.</param>         /// <param name="filePath">The file path.</param>         public static AssemblyBuilder Create(string assemblyName, string filePath)         {             AssemblyName name = new AssemblyName(assemblyName);               AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(                     name, AssemblyBuilderAccess.RunAndSave, filePath);               DynamicAssemblyCache.Add(assembly);               return assembly;         }           #endregion     } }   So hopefully the above class is fairly explanatory, an AssemblyName is created using the passed in string for the actual name of the assembly. An AssemblyBuilder is then constructed with the current AppDomain and depending on the overload used, it is either just run in the current context or it is set up ready for saving. It is then added to the cache.   DynamicAssemblyCache using System.Reflection.Emit; using Rapid.DynamicProxy.Exceptions; using Rapid.DynamicProxy.Resources.Exceptions;   namespace Rapid.DynamicProxy.Assembly {     /// <summary>     /// Cache for storing the dynamic assembly builder.     /// </summary>     internal static class DynamicAssemblyCache     {         #region Declarations           private static object syncRoot = new object();         internal static AssemblyBuilder Cache = null;           #endregion           #region Adds a dynamic assembly to the cache.           /// <summary>         /// Adds a dynamic assembly builder to the cache.         /// </summary>         /// <param name="assemblyBuilder">The assembly builder.</param>         public static void Add(AssemblyBuilder assemblyBuilder)         {             lock (syncRoot)             {                 Cache = assemblyBuilder;             }         }           #endregion           #region Gets the cached assembly                  /// <summary>         /// Gets the cached assembly builder.         /// </summary>         /// <returns></returns>         public static AssemblyBuilder Get         {             get             {                 lock (syncRoot)                 {                     if (Cache != null)                     {                         return Cache;                     }                 }                   throw new RapidDynamicProxyAssertionException(AssertionResources.NoAssemblyInCache);             }         }           #endregion     } } The cache is simply a static property that will store the AssemblyBuilder (I know it’s a little weird that I’ve made it public, this is for testing purposes, I know that’s a bad excuse but hey…) There are two methods for using the cache – Add and Get, these just provide thread safe access to the cache.   The Module Builder The module builder is required as the create proxy classes will need to live inside a module within the assembly. Here’s the code: DynamicModuleBuilder using System.Reflection.Emit; using Rapid.DynamicProxy.Assembly; namespace Rapid.DynamicProxy.Module {     /// <summary>     /// Class for creating a module builder.     /// </summary>     internal static class DynamicModuleBuilder     {         /// <summary>         /// Creates a module builder using the cached assembly.         /// </summary>         public static ModuleBuilder Create()         {             string assemblyName = DynamicAssemblyCache.Get.GetName().Name;               ModuleBuilder moduleBuilder = DynamicAssemblyCache.Get.DefineDynamicModule                 (assemblyName, string.Format("{0}.dll", assemblyName));               DynamicModuleCache.Add(moduleBuilder);               return moduleBuilder;         }     } } As you can see, the module builder is created on the assembly that lives in the DynamicAssemblyCache, the module is given the assembly name and also a string representing the filename if the assembly is to be saved. It is then added to the DynamicModuleCache. DynamicModuleCache using System.Reflection.Emit; using Rapid.DynamicProxy.Exceptions; using Rapid.DynamicProxy.Resources.Exceptions; namespace Rapid.DynamicProxy.Module {     /// <summary>     /// Class for storing the module builder.     /// </summary>     internal static class DynamicModuleCache     {         #region Declarations           private static object syncRoot = new object();         internal static ModuleBuilder Cache = null;           #endregion           #region Add           /// <summary>         /// Adds a dynamic module builder to the cache.         /// </summary>         /// <param name="moduleBuilder">The module builder.</param>         public static void Add(ModuleBuilder moduleBuilder)         {             lock (syncRoot)             {                 Cache = moduleBuilder;             }         }           #endregion           #region Get           /// <summary>         /// Gets the cached module builder.         /// </summary>         /// <returns></returns>         public static ModuleBuilder Get         {             get             {                 lock (syncRoot)                 {                     if (Cache != null)                     {                         return Cache;                     }                 }                   throw new RapidDynamicProxyAssertionException(AssertionResources.NoModuleInCache);             }         }           #endregion     } }   The DynamicModuleCache is very similar to the assembly cache, it is simply a statically stored module with thread safe Add and Get methods.   The DynamicTypeCache To end off this post, I’m going to create the cache for storing the generated proxy classes. I’ve spent a fair amount of time thinking about the type of collection I should use to store the types and have finally decided that for the time being I’m going to use a generic dictionary. This may change when I can actually performance test the proxy generator but the time being I think it makes good sense in theory, mainly as it pretty much maintains it’s performance with varying numbers of items – almost constant (0)1. Plus I won’t ever need to loop through the items which is not the dictionaries strong point. Here’s the code as it currently stands: DynamicTypeCache using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; namespace Rapid.DynamicProxy.Types {     /// <summary>     /// Cache for storing proxy types.     /// </summary>     internal static class DynamicTypeCache     {         #region Declarations           static object syncRoot = new object();         public static Dictionary<string, Type> Cache = new Dictionary<string, Type>();           #endregion           /// <summary>         /// Adds a proxy to the type cache.         /// </summary>         /// <param name="type">The type.</param>         /// <param name="proxy">The proxy.</param>         public static void AddProxyForType(Type type, Type proxy)         {             lock (syncRoot)             {                 Cache.Add(GetHashCode(type.AssemblyQualifiedName), proxy);             }         }           /// <summary>         /// Tries the type of the get proxy for.         /// </summary>         /// <param name="type">The type.</param>         /// <returns></returns>         public static Type TryGetProxyForType(Type type)         {             lock (syncRoot)             {                 Type proxyType;                 Cache.TryGetValue(GetHashCode(type.AssemblyQualifiedName), out proxyType);                 return proxyType;             }         }           #region Private Methods           private static string GetHashCode(string fullName)         {             SHA1CryptoServiceProvider provider = new SHA1CryptoServiceProvider();             Byte[] buffer = Encoding.UTF8.GetBytes(fullName);             Byte[] hash = provider.ComputeHash(buffer, 0, buffer.Length);             return Convert.ToBase64String(hash);         }           #endregion     } } As you can see, there are two public methods, one for adding to the cache and one for getting from the cache. Hopefully they should be clear enough, the Get is a TryGet as I do not want the dictionary to throw an exception if a proxy doesn’t exist within the cache. Other than that I’ve decided to create a key using the SHA1CryptoServiceProvider, this may change but my initial though is the SHA1 algorithm is pretty fast to put together using the provider and it is also very unlikely to have any hashing collisions. (there are some maths behind how unlikely this is – here’s the wiki if you’re interested http://en.wikipedia.org/wiki/SHA_hash_functions)   Anyway, that’s the end of part 1 – although I haven’t started any of the fun stuff (by fun I mean hairpulling, teeth grating Relfection.Emit style fun), I’ve got the basis of the DynamicProxy in place so all we have to worry about now is creating the types, interceptor classes, method invocation information classes and finally a really nice fluent interface that will abstract all of the hard-core craziness away and leave us with a lightning fast, easy to use AOP framework. Hope you find the series interesting. All of the source code can be viewed and/or downloaded at our codeplex site - http://rapidioc.codeplex.com/ Kind Regards, Sean.

    Read the article

  • Creating ASP.NET MVC Negotiated Content Results

    - by Rick Strahl
    In a recent ASP.NET MVC application I’m involved with, we had a late in the process request to handle Content Negotiation: Returning output based on the HTTP Accept header of the incoming HTTP request. This is standard behavior in ASP.NET Web API but ASP.NET MVC doesn’t support this functionality directly out of the box. Another reason this came up in discussion is last week’s announcements of ASP.NET vNext, which seems to indicate that ASP.NET Web API is not going to be ported to the cloud version of vNext, but rather be replaced by a combined version of MVC and Web API. While it’s not clear what new API features will show up in this new framework, it’s pretty clear that the ASP.NET MVC style syntax will be the new standard for all the new combined HTTP processing framework. Why negotiated Content? Content negotiation is one of the key features of Web API even though it’s such a relatively simple thing. But it’s also something that’s missing in MVC and once you get used to automatically having your content returned based on Accept headers it’s hard to go back to manually having to create separate methods for different output types as you’ve had to with Microsoft server technologies all along (yes, yes I know other frameworks – including my own – have done this for years but for in the box features this is relatively new from Web API). As a quick review,  Accept Header content negotiation works off the request’s HTTP Accept header:POST http://localhost/mydailydosha/Editable/NegotiateContent HTTP/1.1 Content-Type: application/json Accept: application/json Host: localhost Content-Length: 76 Pragma: no-cache { ElementId: "header", PageName: "TestPage", Text: "This is a nice header" } If I make this request I would expect to get back a JSON result based on my application/json Accept header. To request XML  I‘d just change the accept header:Accept: text/xml and now I’d expect the response to come back as XML. Now this only works with media types that the server can process. In my case here I need to handle JSON, XML, HTML (using Views) and Plain Text. HTML results might need more than just a data return – you also probably need to specify a View to render the data into either by specifying the view explicitly or by using some sort of convention that can automatically locate a view to match. Today ASP.NET MVC doesn’t support this sort of automatic content switching out of the box. Unfortunately, in my application scenario we have an application that started out primarily with an AJAX backend that was implemented with JSON only. So there are lots of JSON results like this:[Route("Customers")] public ActionResult GetCustomers() { return Json(repo.GetCustomers(),JsonRequestBehavior.AllowGet); } These work fine, but they are of course JSON specific. Then a couple of weeks ago, a requirement came in that an old desktop application needs to also consume this API and it has to use XML to do it because there’s no JSON parser available for it. Ooops – stuck with JSON in this case. While it would have been easy to add XML specific methods I figured it’s easier to add basic content negotiation. And that’s what I show in this post. Missteps – IResultFilter, IActionFilter My first attempt at this was to use IResultFilter or IActionFilter which look like they would be ideal to modify result content after it’s been generated using OnResultExecuted() or OnActionExecuted(). Filters are great because they can look globally at all controller methods or individual methods that are marked up with the Filter’s attribute. But it turns out these filters don’t work for raw POCO result values from Action methods. What we wanted to do for API calls is get back to using plain .NET types as results rather than result actions. That is  you write a method that doesn’t return an ActionResult, but a standard .NET type like this:public Customer UpdateCustomer(Customer cust) { … do stuff to customer :-) return cust; } Unfortunately both OnResultExecuted and OnActionExecuted receive an MVC ContentResult instance from the POCO object. MVC basically takes any non-ActionResult return value and turns it into a ContentResult by converting the value using .ToString(). Ugh. The ContentResult itself doesn’t contain the original value, which is lost AFAIK with no way to retrieve it. So there’s no way to access the raw customer object in the example above. Bummer. Creating a NegotiatedResult This leaves mucking around with custom ActionResults. ActionResults are MVC’s standard way to return action method results – you basically specify that you would like to render your result in a specific format. Common ActionResults are ViewResults (ie. View(vn,model)), JsonResult, RedirectResult etc. They work and are fairly effective and work fairly well for testing as well as it’s the ‘standard’ interface to return results from actions. The problem with the this is mainly that you’re explicitly saying that you want a specific result output type. This works well for many things, but sometimes you do want your result to be negotiated. My first crack at this solution here is to create a simple ActionResult subclass that looks at the Accept header and based on that writes the output. I need to support JSON and XML content and HTML as well as text – so effectively 4 media types: application/json, text/xml, text/html and text/plain. Everything else is passed through as ContentResult – which effecively returns whatever .ToString() returns. Here’s what the NegotiatedResult usage looks like:public ActionResult GetCustomers() { return new NegotiatedResult(repo.GetCustomers()); } public ActionResult GetCustomer(int id) { return new NegotiatedResult("Show", repo.GetCustomer(id)); } There are two overloads of this method – one that returns just the raw result value and a second version that accepts an optional view name. The second version returns the Razor view specified only if text/html is requested – otherwise the raw data is returned. This is useful in applications where you have an HTML front end that can also double as an API interface endpoint that’s using the same model data you send to the View. For the application I mentioned above this was another actual use-case we needed to address so this was a welcome side effect of creating a custom ActionResult. There’s also an extension method that directly attaches a Negotiated() method to the controller using the same syntax:public ActionResult GetCustomers() { return this.Negotiated(repo.GetCustomers()); } public ActionResult GetCustomer(int id) { return this.Negotiated("Show",repo.GetCustomer(id)); } Using either of these mechanisms now allows you to return JSON, XML, HTML or plain text results depending on the Accept header sent. Send application/json you get just the Customer JSON data. Ditto for text/xml and XML data. Pass text/html for the Accept header and the "Show.cshtml" Razor view is rendered passing the result model data producing final HTML output. While this isn’t as clean as passing just POCO objects back as I had intended originally, this approach fits better with how MVC action methods are intended to be used and we get the bonus of being able to specify a View to render (optionally) for HTML. How does it work An ActionResult implementation is pretty straightforward. You inherit from ActionResult and implement the ExecuteResult method to send your output to the ASP.NET output stream. ActionFilters are an easy way to effectively do post processing on ASP.NET MVC controller actions just before the content is sent to the output stream, assuming your specific action result was used. Here’s the full code to the NegotiatedResult class (you can also check it out on GitHub):/// <summary> /// Returns a content negotiated result based on the Accept header. /// Minimal implementation that works with JSON and XML content, /// can also optionally return a view with HTML. /// </summary> /// <example> /// // model data only /// public ActionResult GetCustomers() /// { /// return new NegotiatedResult(repo.Customers.OrderBy( c=> c.Company) ) /// } /// // optional view for HTML /// public ActionResult GetCustomers() /// { /// return new NegotiatedResult("List", repo.Customers.OrderBy( c=> c.Company) ) /// } /// </example> public class NegotiatedResult : ActionResult { /// <summary> /// Data stored to be 'serialized'. Public /// so it's potentially accessible in filters. /// </summary> public object Data { get; set; } /// <summary> /// Optional name of the HTML view to be rendered /// for HTML responses /// </summary> public string ViewName { get; set; } public static bool FormatOutput { get; set; } static NegotiatedResult() { FormatOutput = HttpContext.Current.IsDebuggingEnabled; } /// <summary> /// Pass in data to serialize /// </summary> /// <param name="data">Data to serialize</param> public NegotiatedResult(object data) { Data = data; } /// <summary> /// Pass in data and an optional view for HTML views /// </summary> /// <param name="data"></param> /// <param name="viewName"></param> public NegotiatedResult(string viewName, object data) { Data = data; ViewName = viewName; } public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); HttpResponseBase response = context.HttpContext.Response; HttpRequestBase request = context.HttpContext.Request; // Look for specific content types if (request.AcceptTypes.Contains("text/html")) { response.ContentType = "text/html"; if (!string.IsNullOrEmpty(ViewName)) { var viewData = context.Controller.ViewData; viewData.Model = Data; var viewResult = new ViewResult { ViewName = ViewName, MasterName = null, ViewData = viewData, TempData = context.Controller.TempData, ViewEngineCollection = ((Controller)context.Controller).ViewEngineCollection }; viewResult.ExecuteResult(context.Controller.ControllerContext); } else response.Write(Data); } else if (request.AcceptTypes.Contains("text/plain")) { response.ContentType = "text/plain"; response.Write(Data); } else if (request.AcceptTypes.Contains("application/json")) { using (JsonTextWriter writer = new JsonTextWriter(response.Output)) { var settings = new JsonSerializerSettings(); if (FormatOutput) settings.Formatting = Newtonsoft.Json.Formatting.Indented; JsonSerializer serializer = JsonSerializer.Create(settings); serializer.Serialize(writer, Data); writer.Flush(); } } else if (request.AcceptTypes.Contains("text/xml")) { response.ContentType = "text/xml"; if (Data != null) { using (var writer = new XmlTextWriter(response.OutputStream, new UTF8Encoding())) { if (FormatOutput) writer.Formatting = System.Xml.Formatting.Indented; XmlSerializer serializer = new XmlSerializer(Data.GetType()); serializer.Serialize(writer, Data); writer.Flush(); } } } else { // just write data as a plain string response.Write(Data); } } } /// <summary> /// Extends Controller with Negotiated() ActionResult that does /// basic content negotiation based on the Accept header. /// </summary> public static class NegotiatedResultExtensions { /// <summary> /// Return content-negotiated content of the data based on Accept header. /// Supports: /// application/json - using JSON.NET /// text/xml - Xml as XmlSerializer XML /// text/html - as text, or an optional View /// text/plain - as text /// </summary> /// <param name="controller"></param> /// <param name="data">Data to return</param> /// <returns>serialized data</returns> /// <example> /// public ActionResult GetCustomers() /// { /// return this.Negotiated( repo.Customers.OrderBy( c=> c.Company) ) /// } /// </example> public static NegotiatedResult Negotiated(this Controller controller, object data) { return new NegotiatedResult(data); } /// <summary> /// Return content-negotiated content of the data based on Accept header. /// Supports: /// application/json - using JSON.NET /// text/xml - Xml as XmlSerializer XML /// text/html - as text, or an optional View /// text/plain - as text /// </summary> /// <param name="controller"></param> /// <param name="viewName">Name of the View to when Accept is text/html</param> /// /// <param name="data">Data to return</param> /// <returns>serialized data</returns> /// <example> /// public ActionResult GetCustomers() /// { /// return this.Negotiated("List", repo.Customers.OrderBy( c=> c.Company) ) /// } /// </example> public static NegotiatedResult Negotiated(this Controller controller, string viewName, object data) { return new NegotiatedResult(viewName, data); } } Output Generation – JSON and XML Generating output for XML and JSON is simple – you use the desired serializer and off you go. Using XmlSerializer and JSON.NET it’s just a handful of lines each to generate serialized output directly into the HTTP output stream. Please note this implementation uses JSON.NET for its JSON generation rather than the default JavaScriptSerializer that MVC uses which I feel is an additional bonus to implementing this custom action. I’d already been using a custom JsonNetResult class previously, but now this is just rolled into this custom ActionResult. Just keep in mind that JSON.NET outputs slightly different JSON for certain things like collections for example, so behavior may change. One addition to this implementation might be a flag to allow switching the JSON serializer. Html View Generation Html View generation actually turned out to be easier than anticipated. Initially I used my generic ASP.NET ViewRenderer Class that can render MVC views from any ASP.NET application. However it turns out since we are executing inside of an active MVC request there’s an easier way: We can simply create a custom ViewResult and populate its members and then execute it. The code in text/html handling code that renders the view is simply this:response.ContentType = "text/html"; if (!string.IsNullOrEmpty(ViewName)) { var viewData = context.Controller.ViewData; viewData.Model = Data; var viewResult = new ViewResult { ViewName = ViewName, MasterName = null, ViewData = viewData, TempData = context.Controller.TempData, ViewEngineCollection = ((Controller)context.Controller).ViewEngineCollection }; viewResult.ExecuteResult(context.Controller.ControllerContext); } else response.Write(Data); which is a neat and easy way to render a Razor view assuming you have an active controller that’s ready for rendering. Sweet – dependency removed which makes this class self-contained without any external dependencies other than JSON.NET. Summary While this isn’t exactly a new topic, it’s the first time I’ve actually delved into this with MVC. I’ve been doing content negotiation with Web API and prior to that with my REST library. This is the first time it’s come up as an issue in MVC. But as I have worked through this I find that having a way to specify both HTML Views *and* JSON and XML results from a single controller certainly is appealing to me in many situations as we are in this particular application returning identical data models for each of these operations. Rendering content negotiated views is something that I hope ASP.NET vNext will provide natively in the combined MVC and WebAPI model, but we’ll see how this actually will be implemented. In the meantime having a custom ActionResult that provides this functionality is a workable and easily adaptable way of handling this going forward. Whatever ends up happening in ASP.NET vNext the abstraction can probably be changed to support the native features of the future. Anyway I hope some of you found this useful if not for direct integration then as insight into some of the rendering logic that MVC uses to get output into the HTTP stream… Related Resources Latest Version of NegotiatedResult.cs on GitHub Understanding Action Controllers Rendering ASP.NET Views To String© Rick Strahl, West Wind Technologies, 2005-2014Posted in MVC  ASP.NET  HTTP   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • How to resize YouTube player when Window Resize

    - by Permana
    I want to show Popup window contain YouTube video. My question is how to resize YouTube Player when user resize the Popup Window ? Head section of Popup windows PHP/HTML code <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Wavin Video</title> <script src="jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript" charset="utf-8"> $(document).ready(function(){ //If the User resizes the window //$(window).bind("resize", resizeWindow); $(window).resize(resizeWindow).resize() function resizeWindow( e ) { var target = "#youtubebox2"; var newWindowHeight = $(window).height(); var newWindowWidth = $(window).width(); console.log("Width : "+newWindowWidth); console.log("Height: "+newWindowHeight); console.log("---------"); $(target).html("<object width=\""+newWindowWidth+"\" height=\""+newWindowHeight+"\" id=\"youtubebox\"><param name=\"movie\" value=\"http://www.youtube.com/v/<?php echo $_GET['filename'];?>\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"http://www.youtube.com/v/<?php echo $_GET['filename'];?>\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\""+newWindowWidth+"\" height=\""+newWindowHeight+"\"></embed></object>"); } }); </script> </head> <body> <div align="center" style="padding:6px 0px 0px 0px;background-color: #ccc;" id="youtubebox2"> <object width="480" height="385" id="youtubebox"> <param name="movie" value="http://www.youtube.com/v/<?php echo $_GET['filename'];?>"></param> <param name="allowFullScreen" value="true"></param> <param name="allowscriptaccess" value="always"></param> <embed src="http://www.youtube.com/v/<?php echo $_GET['filename'];?>" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"> </embed> </object> </div> </body> </html> the page receive youtube video ID through $_GET variable. the code above didn't work, the YouTUbe Player is not resized. Is there something I miss ?

    Read the article

  • Reslet with GWT and Tomcat Error

    - by Holograham
    I am getting this error on startup I am using GWT 2.0.3 and Reslet RC3 type Exception report message description The server encountered an internal error () that prevented it from fulfilling this request. exception javax.servlet.ServletException: Servlet.init() for servlet adapter threw exception org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) java.lang.Thread.run(Thread.java:619) root cause java.lang.NoSuchMethodError: org.restlet.Client.handle(Lorg/restlet/Request;)Lorg/restlet/Response; org.restlet.ext.servlet.ServerServlet.createComponent(ServerServlet.java:423) org.restlet.ext.servlet.ServerServlet.getComponent(ServerServlet.java:763) org.restlet.ext.servlet.ServerServlet.init(ServerServlet.java:881) javax.servlet.GenericServlet.init(GenericServlet.java:212) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) java.lang.Thread.run(Thread.java:619) My web XML is as follows: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> <context-param> <param-name>org.restlet.clients</param-name> <param-value>CLAP FILE WAR</param-value> </context-param> <servlet> <servlet-name>adapter</servlet-name> <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class> <init-param> <param-name>org.restlet.application</param-name> <param-value>com.tdc.Propspace.server.TestServerApplication</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>adapter</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app> Any ideas what would cause this?

    Read the article

  • Quartz.properties

    - by pandi-sus
    I developed an EAR using Quartz API. I have put my quartz.properties file in the classpath(WEB-INF/classes in war). Added following lines to web.xml file <context-param> <param-name>config-file</param-name> <param-value>/WEB-INF/classes/quartz.properties</param-value> </context-param> But Quartz still loads the default properties file from the quartz.jar

    Read the article

  • Enabling browser caching via java

    - by Franz See
    Good day, I am using CacheFilter to filter a certain path to my server (which outputs an image stream to the response stream). And I've configured it in my web.xml as follows: <filter> <filter-name>imagesCache</filter-name> <filter-class>com.samaxes.cachefilter.presentation.CacheFilter</filter-class> <init-param> <param-name>privacy</param-name> <param-value>public</param-value> </init-param> <init-param> <param-name>expirationTime</param-name> <param-value>2592000</param-value> </init-param> </filter> ... <filter-mapping> <filter-name>imagesCache</filter-name> <url-pattern>/my/path/*</url-pattern> </filter-mapping> Using my firefox, if I access my url via the address bar, it hits the server the first time but uses the cache during succeeding calls. However, if the url is inside my page ( i.e. <img src="..."/> ), it seems to hit the server all the time. [EDIT] After a few more testing, accessing my image via the address bar does not work all the time. But caching does seem to work more often with it than . As to whether it really, I am not sure. Additional Info: my path is something like /my/path?then=some&query=strings. Notice that it doesn't have an extension (i.e. gif, png, jpeg ) but it's mimetype is set properly ( image/gif, image/png, image/jpeg ). I am not sure if the lack of extension or the presence of the query strings have any impact. (Also, another note. though my url have query strings, I am using the same uri + query string over and over again with my tests). Any ideas why? Thanks

    Read the article

  • Is it possible to use .properties files in web.xml in conjunction with contextConfigLocation paramet

    - by Vladimir
    Here is part of my web.xml: <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:application-config.xml </param-value> </context-param> application-config.xml uses property placeholder: <context:property-placeholder location="classpath:properties/db.properties"/> Is it possible somehow to define which properties file to use in web.xml rather than in application-config.xml?

    Read the article

  • How to set the skin of a DotNetNuke page through code?

    - by ks78
    I'm working on a DNN module that creates DNN pages (tabs) and places DNN modules on them through code. So, far that's working very well. However, I'd like it to also be able to programmatically set the page's skin and place the modules in the appropriate pane. Does anyone know how to do this using code? Solution: I set SkinSrc and ContainerSrc as mika suggested. Here's my source, if you're interested. This is where I set SkinSrc. ''' <summary>Create new DNN tab/page.</summary> Private Function CreatePage(ByVal ParentID As Integer, ByVal PageName As String, ByVal PageTitle As String, ByVal Description As String, ByVal Keywords As String, ByVal Permissions As TabPermissionCollection, Optional ByVal SkinSrc As String = "", Optional ByVal isVisible As Boolean = True, Optional ByVal LoadDefaultModules As Boolean = True) As Tabs.TabInfo Try Dim tabCtrlr As New TabController Dim newTab As New Tabs.TabInfo Dim newPermissions As TabPermissionCollection = newTab.TabPermissions Dim permissionProvider As PermissionProvider = permissionProvider.Instance Dim infPermission As TabPermissionInfo ' set new page properties newTab.PortalID = PortalId newTab.TabName = PageName newTab.Title = PageTitle newTab.Description = Description newTab.KeyWords = Keywords newTab.IsDeleted = False newTab.IsSuperTab = False newTab.IsVisible = isVisible newTab.DisableLink = False newTab.IconFile = "" newTab.Url = "" newTab.ParentId = ParentID 'add skinsrc if specified If (SkinSrc.Length > 0) Then newTab.SkinSrc = SkinSrc ' create new page tabCtrlr.AddTab(newTab, LoadDefaultModules) ' copy permissions selected in Permissions collection For index As Integer = 0 To (Permissions.Count - 1) infPermission = New TabPermissionInfo infPermission.AllowAccess = Permissions(index).AllowAccess infPermission.RoleID = Permissions(index).RoleID infPermission.RoleName = Permissions(index).RoleName infPermission.TabID = Permissions(index).TabID infPermission.PermissionID = Permissions(index).PermissionID 'save permission info newPermissions.Add(infPermission, True) permissionProvider.SaveTabPermissions(newTab) Next index 'return TabInfo of new page Return newTab Catch ex As Exception 'failure Return New Tabs.TabInfo End Try End Function These next two functions were taken from the DNN source and tweaked slightly, so I can't take credit for much of them. Also, if you use these in your own modules there could be issues when upgrading DNN. Although the upgrade from 5.05 to 5.06 went smoothly for me. In the AddNewModule function, I used ContainerSrc to specify the custom container to use. PaneName is the property used to specify which panel the module should be placed in. #Region "From DNN Source --mostly" #Region "Enums" Private Enum ViewPermissionType View = 0 Edit = 1 End Enum #End Region ''' ----------------------------------------------------------------------------- ''' <summary>Adds a New Module to a Pane</summary> ''' <param name="align">The alignment for the Module</param> ''' <param name="desktopModuleId">The Id of the DesktopModule</param> ''' <param name="permissionType">The View Permission Type for the Module</param> ''' <param name="title">The Title for the resulting module</param> ''' <param name="paneName">The pane to add the module to</param> ''' <param name="position">The relative position within the pane for the module</param> ''' ----------------------------------------------------------------------------- Private Function AddNewModule(ByVal TabID As Integer, ByVal title As String, ByVal desktopModuleId As Integer, ByVal paneName As String, ByVal position As Integer, ByVal permissionType As ViewPermissionType, ByVal align As String) As Integer Dim objTabController As New TabController Dim objTabPermissions As TabPermissionCollection = objTabController.GetTab(TabID, PortalId, True).TabPermissions Dim objPermissionController As New PermissionController Dim objModules As New ModuleController Dim objModuleDefinition As ModuleDefinitionInfo Dim objEventLog As New Services.Log.EventLog.EventLogController Dim newModuleID As Integer Dim j As Integer Try Dim desktopModule As DesktopModuleInfo = Nothing If Not DesktopModuleController.GetDesktopModules(PortalSettings.PortalId).TryGetValue(desktopModuleId, desktopModule) Then Throw New ArgumentException("desktopModuleId") End If Catch ex As Exception LogException(ex) End Try Dim UserId As Integer = -1 If Request.IsAuthenticated Then Dim objUserInfo As Users.UserInfo = UserController.GetCurrentUserInfo UserId = objUserInfo.UserID End If For Each objModuleDefinition In ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModuleId).Values Dim objModule As New ModuleInfo objModule.Initialize(PortalSettings.PortalId) objModule.PortalID = PortalSettings.PortalId objModule.TabID = TabID objModule.ModuleOrder = position If title = "" Then objModule.ModuleTitle = objModuleDefinition.FriendlyName Else objModule.ModuleTitle = title End If objModule.PaneName = paneName objModule.ModuleDefID = objModuleDefinition.ModuleDefID If objModuleDefinition.DefaultCacheTime > 0 Then objModule.CacheTime = objModuleDefinition.DefaultCacheTime If Portals.PortalSettings.Current.DefaultModuleId > Null.NullInteger AndAlso Portals.PortalSettings.Current.DefaultTabId > Null.NullInteger Then Dim defaultModule As ModuleInfo = objModules.GetModule(Portals.PortalSettings.Current.DefaultModuleId, Portals.PortalSettings.Current.DefaultTabId, True) If Not defaultModule Is Nothing Then objModule.CacheTime = defaultModule.CacheTime End If End If End If Select Case permissionType Case ViewPermissionType.View objModule.InheritViewPermissions = True Case ViewPermissionType.Edit objModule.InheritViewPermissions = False End Select ' get the default module view permissions Dim arrSystemModuleViewPermissions As ArrayList = objPermissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "VIEW") ' get the permissions from the page For Each objTabPermission As TabPermissionInfo In objTabPermissions If objTabPermission.PermissionKey = "VIEW" AndAlso permissionType = ViewPermissionType.View Then 'Don't need to explicitly add View permisisons if "Same As Page" Continue For End If ' get the system module permissions for the permissionkey Dim arrSystemModulePermissions As ArrayList = objPermissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", objTabPermission.PermissionKey) ' loop through the system module permissions For j = 0 To arrSystemModulePermissions.Count - 1 ' create the module permission Dim objSystemModulePermission As PermissionInfo objSystemModulePermission = CType(arrSystemModulePermissions(j), PermissionInfo) If objSystemModulePermission.PermissionKey = "VIEW" AndAlso permissionType = ViewPermissionType.Edit AndAlso _ objTabPermission.PermissionKey <> "EDIT" Then 'Only Page Editors get View permissions if "Page Editors Only" Continue For End If Dim objModulePermission As ModulePermissionInfo = AddModulePermission(objModule, _ objSystemModulePermission, _ objTabPermission.RoleID, objTabPermission.UserID, _ objTabPermission.AllowAccess) ' ensure that every EDIT permission which allows access also provides VIEW permission If objModulePermission.PermissionKey = "EDIT" And objModulePermission.AllowAccess Then Dim objModuleViewperm As ModulePermissionInfo = AddModulePermission(objModule, _ CType(arrSystemModuleViewPermissions(0), PermissionInfo), _ objModulePermission.RoleID, objModulePermission.UserID, _ True) End If Next 'Get the custom Module Permissions, Assume that roles with Edit Tab Permissions 'are automatically assigned to the Custom Module Permissions If objTabPermission.PermissionKey = "EDIT" Then Dim arrCustomModulePermissions As ArrayList = objPermissionController.GetPermissionsByModuleDefID(objModule.ModuleDefID) ' loop through the custom module permissions For j = 0 To arrCustomModulePermissions.Count - 1 ' create the module permission Dim objCustomModulePermission As PermissionInfo objCustomModulePermission = CType(arrCustomModulePermissions(j), PermissionInfo) AddModulePermission(objModule, objCustomModulePermission, _ objTabPermission.RoleID, objTabPermission.UserID, _ objTabPermission.AllowAccess) Next End If Next objModule.AllTabs = False objModule.Alignment = align 'apply Custom Container to module objModule.ContainerSrc = CONTAINER_TRANSPARENT_PLAIN newModuleID = objModules.AddModule(objModule) Next Return newModuleID End Function ''' ----------------------------------------------------------------------------- ''' <summary>Adds a Module Permission</summary> ''' <param name="permission">The permission to add</param> ''' <param name="roleId">The Id of the role to add the permission for.</param> ''' ----------------------------------------------------------------------------- Private Function AddModulePermission(ByVal objModule As ModuleInfo, ByVal permission As PermissionInfo, ByVal roleId As Integer, ByVal userId As Integer, ByVal allowAccess As Boolean) As ModulePermissionInfo Dim objModulePermission As New ModulePermissionInfo objModulePermission.ModuleID = objModule.ModuleID objModulePermission.PermissionID = permission.PermissionID objModulePermission.RoleID = roleId objModulePermission.UserID = userId objModulePermission.PermissionKey = permission.PermissionKey objModulePermission.AllowAccess = allowAccess ' add the permission to the collection If Not objModule.ModulePermissions.Contains(objModulePermission) Then objModule.ModulePermissions.Add(objModulePermission) End If Return objModulePermission End Function #End Region

    Read the article

  • Is ResourceBundle fallback resolution broken in Resin3x?

    - by LES2
    Given the following ResourceBundle properties files: messages.properties messages_en.properties messages_es.properties messages_{some locale}.properties Note: messages.properties contains all the messages for the default locale. messages_en.properties is really empty - it's just there for correctness. messages_en.properties will fall back to messages.properties! And given the following config params in web.xml: <context-param> <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name> <param-value>messages</param-value> </context-param> <context-param> <param-name>javax.servlet.jsp.jstl.fmt.fallbackLocale</param-name> <param-value>en</param-value> </context-param> I would expect that if the chosen locale is 'es', and a resource is not translated in 'es', then it would fall back to 'en', and finally to 'messages.properties' (since messages_en.properties is empty). This is how things work in Jetty. I've also tested this on WebSphere. Resin Is the Problem The problem is when I get to Resin (3.0.23). Fallback resolution does not work at all! In order to get an messages to display, I must do the following: Rename messages.properties to messages_en.properties (essentially, swap the contents of messages.properties and messages_en.properties) Make sure ever key in messages_en.properties is also defined in messages_{every other locale}.properties (even if the exact same). If I don't do this, I get "???some.key???" in the JSPs. Please help! This is perplexing. -- LES SOLUTION Add following to pom.xml (if you're using maven) ... <properties> <taglibs.version>1.1.2</taglibs.version> </properties> ... <!-- Resin ships with a crappy JSTL implementation that doesn't work with fallback locales for resource bundles correctly; we therefore include our own JSTL implementation in the WAR, and avoid this problem. This can be removed if the target container is not resin. --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${taglibs.version}</version> <scope>compile</scope> </dependency>

    Read the article

  • Symfony 2.0 - routing

    - by Agares
    Hi! How can I set up routing in symfony to be like that(if one rule won't work, next should be grabbed): /controller/action/param/param/param/... /admin/controller/action/param/param/param/... ("admin" is constant here - name of the bundle) I tried that: homepage: pattern: / defaults: { _bundle: HelloBundle, _controller: Hello, _action: index } default: pattern: /:controller/:action/* defaults: { _bundle: HelloBundle } But it doesn't work, even for the first rule. Sorry for my English, and thanks for any future help ;.

    Read the article

  • Play Video File in Asp. Net 3.5 in IIS

    - by Sneha Joshi
    I have developed an application to upload a video on the server and then play it. It runs well when i execute it in Visual Studio 2008 in-built web server.. But when I configure it on IIS, the video does not play... Is there any settings needed in IIS to play video ?? The code of Button Click event - **protected void btnPlayVideo_Click(object sender, EventArgs e) { try { string himaSagarURL = this.lnkbtnVideo.Text; bool isFullSize = false; this.Literal1.Text = this.Play_Video(himaSagarURL, isFullSize); } catch (Exception ex) { this.Response.Write(ex.ToString()); } } This button click event calls the Play_Video method which is given below.. The code I used for embedding - private string Play_Video(string sagarURL, bool isFullSize) { string himaSagarObject = ""; sagarURL = sagarURL + ""; sagarURL = sagarURL.Trim(); if (sagarURL.Length > 0) { //Continue. } else { throw new System.ArgumentNullException("sagarURL"); } string himaSagarWidthAndHeight = ""; if (isFullSize) { himaSagarWidthAndHeight = ""; } else { himaSagarWidthAndHeight = "width='640' height='480'"; } himaSagarObject = himaSagarObject + "<object classid='CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95' id='player' " + himaSagarWidthAndHeight + " standby='Please wait while the object is loaded...'>"; himaSagarObject = himaSagarObject + "<param name='url' value='" + sagarURL + "' />"; himaSagarObject = himaSagarObject + "<param name='src' value='" + sagarURL + "' />"; himaSagarObject = himaSagarObject + "<param name='AutoStart' value='true' />"; himaSagarObject = himaSagarObject + "<param name='Balance' value='0' />"; //-100 is fully left, 100 is fully right. himaSagarObject = himaSagarObject + "<param name='CurrentPosition' value='0' />"; //Position in seconds when starting. himaSagarObject = himaSagarObject + "<param name='showcontrols' value='true' />"; //Show play/stop/pause controls. himaSagarObject = himaSagarObject + "<param name='enablecontextmenu' value='true' />"; //Allow right-click. himaSagarObject = himaSagarObject + "<param name='fullscreen' value='" + isFullSize.ToString() + "' />"; //Start in full screen or not. himaSagarObject = himaSagarObject + "<param name='mute' value='false' />"; himaSagarObject = himaSagarObject + "<param name='PlayCount' value='1' />"; //Number of times the content will play. himaSagarObject = himaSagarObject + "<param name='rate' value='1.0' />"; //0.5=Slow, 1.0=Normal, 2.0=Fast himaSagarObject = himaSagarObject + "<param name='uimode' value='full' />"; // full, mini, custom, none, invisible himaSagarObject = himaSagarObject + "<param name='showdisplay' value='true' />"; //Show or hide the name of the file. himaSagarObject = himaSagarObject + "<param name='volume' value='50' />"; // 0=lowest, 100=highest himaSagarObject = himaSagarObject + "</object>"; return himaSagarObject; }**

    Read the article

  • Insert Error:CREATE DATABASE permission denied in database 'master'. cannot attach the file

    - by user1300580
    i have a register page on my website I am creating and it saves the data entered by the user into a database however when I click the register button i am coming across the following error: Insert Error:CREATE DATABASE permission denied in database 'master'. Cannot attach the file 'C:\Users\MyName\Documents\MyName\Docs\Project\SJ\App_Data\SJ-Database.mdf' as database 'SJ-Database'. These are my connection strings: <connectionStrings> <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/> <add name="MyConsString" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|SJ-Database.mdf; Initial Catalog=SJ-Database; Integrated Security=SSPI;" providerName="System.Data.SqlClient" /> </connectionStrings> Register page code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; public partial class About : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } public string GetConnectionString() { //sets the connection string from your web config file "ConnString" is the name of your Connection String return System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString; } private void ExecuteInsert(string name, string gender, string age, string address, string email) { SqlConnection conn = new SqlConnection(GetConnectionString()); string sql = "INSERT INTO Register (Name, Gender, Age, Address, Email) VALUES " + " (@Name,@Gender,@Age,@Address,@Email)"; try { conn.Open(); SqlCommand cmd = new SqlCommand(sql, conn); SqlParameter[] param = new SqlParameter[6]; //param[0] = new SqlParameter("@id", SqlDbType.Int, 20); param[0] = new SqlParameter("@Name", SqlDbType.VarChar, 50); param[1] = new SqlParameter("@Gender", SqlDbType.Char, 10); param[2] = new SqlParameter("@Age", SqlDbType.Int, 100); param[3] = new SqlParameter("@Address", SqlDbType.VarChar, 50); param[4] = new SqlParameter("@Email", SqlDbType.VarChar, 50); param[0].Value = name; param[1].Value = gender; param[2].Value = age; param[3].Value = address; param[4].Value = email; for (int i = 0; i < param.Length; i++) { cmd.Parameters.Add(param[i]); } cmd.CommandType = CommandType.Text; cmd.ExecuteNonQuery(); } catch (System.Data.SqlClient.SqlException ex) { string msg = "Insert Error:"; msg += ex.Message; throw new Exception(msg); } finally { conn.Close(); } } protected void cmdRegister_Click(object sender, EventArgs e) { if (txtRegEmail.Text == txtRegEmailCon.Text) { //call the method to execute insert to the database ExecuteInsert(txtRegName.Text, txtRegAge.Text, ddlRegGender.SelectedItem.Text, txtRegAddress.Text, txtRegEmail.Text); Response.Write("Record was successfully added!"); ClearControls(Page); } else { Response.Write("Email did not match"); txtRegEmail.Focus(); } } public static void ClearControls(Control Parent) { if (Parent is TextBox) { (Parent as TextBox).Text = string.Empty; } else { foreach (Control c in Parent.Controls) ClearControls(c); } } }

    Read the article

  • Using pointers in PHP.

    - by Babiker
    I ask this question because i learned that in programming and designing, you must have a good reason for decisions. I am php learner and i am at a crossroad here, i am using simple incrementation to try to get what im askin across. I am certainly not here to start a debate about the pros/cons of pointers but when it comes to php, which is the better programming practice: function increment(&$param) { $param++; } Or function increment($param){ return $param++; } $param = increment($param);

    Read the article

  • facescontext.getcurrentinstance returns nullpointerexception

    - by mvg
    I am creating a Spring based JSF application, where I am getting FacesContext.getCurrentInstance which returns null. Here is my Java code public static ServletContext getServletContext() { return (ServletContext) FacesContext.getCurrentInstance() .getExternalContext().getContext(); } This is the stack trace of my error SEVERE: Exception sending context initialized event to listener instance of class org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dbSettingsServiceTarget' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.baytalkitec.smartcall.service.impl.DbSettingsServiceImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:883) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:839) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:440) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:729) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:381) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3972) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4467) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardHost.start(StandardHost.java:785) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:519) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:581) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414) Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.baytalkitec.smartcall.service.impl.DbSettingsServiceImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:115) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:61) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:877) ... 31 more Caused by: java.lang.NullPointerException at com.smartcall.util.FacesUtil.getServletContext(FacesUtil.java:21) at com.smartcall.util.SpringApplicationContextUtil.init(SpringApplicationContextUtil.java:21) at com.smartcall.util.SpringApplicationContextUtil.<init>(SpringApplicationContextUtil.java:16) at com.smartcall.service.impl.DbSettingsServiceImpl.init(DbSettingsServiceImpl.java:17) at com.smartcall.service.impl.DbSettingsServiceImpl.<init>(DbSettingsServiceImpl.java:12) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:100) ... 33 more and hence due to this error Server console in Eclipse reports that application failed to startup due to previous errors My web.xml file <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>smartcall2.0</display-name> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>server</param-value> </context-param> <context-param> <param-name>javax.faces.CONFIG_FILES</param-name> <param-value> /WEB-INF/faces-config.xml,/WEB-INF/faces-managed-bean.xml,/WEB-INF/faces-navigation.xml </param-value> </context-param> <listener> <listener-class> com.sun.faces.config.ConfigureListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <filter> <display-name>RichFaces Filter</display-name> <filter-name>richfaces</filter-name> <filter-class>org.ajax4jsf.Filter</filter-class> </filter> <filter-mapping> <filter-name>richfaces</filter-name> <servlet-name>Faces Servlet</servlet-name> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> </filter-mapping> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <context-param> <param-name>javax.faces.DEFAULT_SUFFIX</param-name> <param-value>.xhtml</param-value> </context-param> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> <session-config> <session-timeout>180</session-timeout> </session-config> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> I am not clear whether this error belongs to Spring or JSF or Eclipse. I am using Eclipse Galileo, JSF 1.2,Spring 3 Please help Thanks in advance

    Read the article

  • Using properties in web.xml

    - by Pich
    Hi, I would like to control the settings in web.xml and using different once for different environments. Is it possible to use a property, from a property file on classpath, in web.xml? Something like this: <context-param> <param-name>myparam</param-name> <param-value>classpath:mypropertyfile.properties['myproperty']</param-value> </context-param> Best regards P

    Read the article

  • c++ / c confusion

    - by mrbuxley
    Im trying to make a small app in c++ that saves midifiles with this library. http://musicnote.sourceforge.net/docs/html/index.html The sample code that is given on the homepage looks like this. #include "MusicNoteLib.h" void main() { MusicNoteLib::Player player; // Create the Player Object player.Play("C D E F G A B"); // Play the Music Notes on the default MIDI output port } This piece of code won't compile in Visual studio 2008, I get many errors like MusicNoteLib.h(22) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int I don't understand the error or where to start looking... There also was some dll files that can be used instead of this h file. #ifndef __MUSICNOTE_LIB_H__EBEE094C_FF6E_43a1_A6CE_D619564F9C6A__ #define __MUSICNOTE_LIB_H__EBEE094C_FF6E_43a1_A6CE_D619564F9C6A__ /** @file MusicNoteLib.h * \brief Main header file for accessing the MusicNote Library */ /// <Summary> /// This header file can be included directly in your project or through /// MusicNoteLib.h of the MusicNoteDll project. If included directly, this /// will be built directly as a satic library. If included through MusicNoteDll /// this will use dllImports through MUSICNOTELIB_API /// </Summary> #ifndef MUSICNOTELIB_API #define MUSICNOTELIB_API #endif // MUSICNOTELIB_API //#include "Player.h" namespace MusicNoteLib /// Music Programming Library { typedef void (__stdcall *LPFNTRACEPROC)(void* pUserData, const TCHAR* szTraceMsg); typedef void (__stdcall *LPFNERRORPROC)(void* pUserData, long lErrCode, const TCHAR* szErrorMsg, const TCHAR* szToken); extern "C" { MUSICNOTELIB_API typedef void MStringPlayer; MUSICNOTELIB_API void* GetCarnaticMusicNoteReader(); /// <Summary> /// Creates a MusicString Player object. /// </Summary> MUSICNOTELIB_API MStringPlayer* CreateMusicStringPlayer(); /// <Summary> /// Plays Music string notes on the default MIDI Output device with the default Timer Resolution. /// Use PlayMusicStringWithOpts() to use custom values. /// @param szMusicNotes the Music string to be played on the MIDI output device /// @return True if the notes were played successfully, False otherwise /// </Summary> MUSICNOTELIB_API bool PlayMusicString(const TCHAR* szMusicNotes); /// <Summary> /// Same as PlayMusicString() except that this method accepts Callbacks. /// The Trace and Error callbacks will be used during the Parse of the Music Notes. /// @param szMusicNotes the Music string to be played on the MIDI output device /// @param traceCallbackProc the Callback to used to report Trace messages /// @param errorCallbackProc the Callback to used to report Error messages /// @param pUserData any user supplied data that should be sent to the Callback /// @return True if the notes were played successfully, False otherwise /// </Summary> MUSICNOTELIB_API bool PlayMusicStringCB(const TCHAR* szMusicNotes, LPFNTRACEPROC traceCallbackProc, LPFNERRORPROC errorCallbackProc, void* pUserData); /// <Summary> /// Plays Music string notes on the given MIDI Output device using the given Timer Resolution. /// Use PlayMusicString() to use default values. /// @param szMusicNotes the Music notes to be played /// @param nMidiOutPortID the device ID of the MIDI output port to be used for the play /// @param nTimerResMS preferred MIDI timer resolution, in MilliSeconds /// @return True if Play was successful, False otherwise /// </Summary> MUSICNOTELIB_API bool PlayMusicStringWithOpts(const TCHAR* szMusicNotes, int nMidiOutPortID, unsigned int nTimerResMS); /// <Summary> /// Same as PlayMusicStringWithOpts() except that this method accepts Callbacks. /// The Trace and Error callbacks will be used during the Parse of the Music Notes. /// @param szMusicNotes the Music notes to be played /// @param nMidiOutPortID the device ID of the MIDI output port to be used for the play /// @param nTimerResMS preferred MIDI timer resolution, in MilliSeconds /// @param traceCallbackProc the Callback to used to report Trace messages /// @param errorCallbackProc the Callback to used to report Error messages /// @param pUserData any user supplied data that should be sent to the Callback /// @return True if Play was successful, False otherwise /// </Summary> MUSICNOTELIB_API bool PlayMusicStringWithOptsCB(const TCHAR* szMusicNotes, int nMidiOutPortID, unsigned int nTimerResMS, LPFNTRACEPROC traceCallbackProc, LPFNERRORPROC errorCallbackProc, void* pUserData); /// <Summary> /// Save the given MusicString content into a MIDI output file /// @param szMusicNotes Music Notes to be converted to MIDI output /// @param szOutputFilePath path of the MIDI output file /// @return True if the the content was saved successfully, False otherwise /// </Summary> MUSICNOTELIB_API bool SaveAsMidiFile(const TCHAR* szMusicNotes, const char* szOutputFilePath); //MUSICNOTELIB_API typedef void (*ParseErrorProc)(const MusicNoteLib::CParser*, MusicNoteLib::CParser::ErrorEventHandlerArgs* pEvArgs); //MUSICNOTELIB_API typedef void (*ParseTraceProc)(const MusicNoteLib::CParser*, MusicNoteLib::CParser::TraceEventHandlerArgs* pEvArgs); MUSICNOTELIB_API void Parse(const TCHAR* szNotes, LPFNTRACEPROC traceCallbackProc, void* pUserData); } // extern "C" } // namespace MusicNoteLib #endif // __MUSICNOTE_LIB_H__EBEE094C_FF6E_43a1_A6CE_D619564F9C6A__

    Read the article

  • Windows Media Player on top other DIV

    - by HP
    I have an embed window media player which is always on top of other DIV tags. I used wmode = opaque; WindowlessVideo = -1 but it does not help. Does anyone know how to make it appear below a certain element of the page. <object type="application/x-oleobject" classid="CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6" codebase= "http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" width="345" height="45"><param name="URL" value= "http://nhacso.net/Music/nghe_song.aspx?id=100004995" /> <param name="EnableContextMenu" value="0" /> <param name="uiMode" value="full" /> <param name="stretchToFit" value="True" /> <param name="AnimationAtStart" value="false" /> <param name="playcount" value="10" /> <param name="Volume" value="100" /> <param name="autostart" value="0" /> <param name="wmode" value="opaque" /> <param name="WindowlessVideo" value="-1" /> <embed src="http://nhacso.net/Music/nghe_song.aspx?id=100004995" type="application/x-mplayer2" width="345" height="45" align= "center" border="0" autostart="0" transparentatstart="1" animationatstart="1" showcontrols="true" showaudiocontrols="1" showpositioncontrols="0" enablecontextmenu="0" autosize="0" showstatusbar="1" displaysize="false" playcount="10" wmode="opaque" windowlessvideo="-1" /></object> Thanks

    Read the article

  • jquery ui popup a YouTube Video modally

    - by BahaiResearch.com
    Is there a way to use jQueryUI to popup a YouTube video modally? Here's the YouTube code I have: <object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/DIuXtsaUDmM?fs=1&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/DIuXtsaUDmM?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>

    Read the article

  • Media player hide control

    - by Geetha
    Hi All, I am using the following code to play video in asp.net application. I want to hide the mediaplayer default controls. Code: <object id="mediaPlayer" classid="clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" width="480" height="270" standby="Loading Microsoft Windows Media Player components..." type="application/x-oleobject"> <param name="fileName" value="" /> <param name="animationatStart" value="true" /> <param name="transparentatStart" value="true" /> <param name="autoStart" value="true" /> <param name="showControls" value="true" /> <param name="volume" value="150" /> <param name="loop" value="false" /> <param name="windowlessVideo" value="true" /> </object>

    Read the article

  • Using RIA DomainServices with ASP.NET and MVC 2

    - by Bobby Diaz
    Recently, I started working on a new ASP.NET MVC 2 project and I wanted to reuse the data access (LINQ to SQL) and business logic methods (WCF RIA Services) that had been developed for a previous project that used Silverlight for the front-end.  I figured that I would be able to instantiate the various DomainService classes from within my controller’s action methods, because after all, the code for those services didn’t look very complicated.  WRONG!  I didn’t realize at first that some of the functionality is handled automatically by the framework when the domain services are hosted as WCF services.  After some initial searching, I came across an invaluable post by Joe McBride, which described how to get RIA Service .svc files to work in an MVC 2 Web Application, and another by Brad Abrams.  Unfortunately, Brad’s solution was for an earlier preview release of RIA Services and no longer works with the version that I am running (PDC Preview). I have not tried the RC version of WCF RIA Services, so I am not sure if any of the issues I am having have been resolved, but I wanted to come up with a way to reuse the shared libraries so I wouldn’t have to write a non-RIA version that basically did the same thing.  The classes I came up with work with the scenarios I have encountered so far, but I wanted to go ahead and post the code in case someone else is having the same trouble I had.  Hopefully this will save you a few headaches! 1. Querying When I first tried to use a DomainService class to perform a query inside one of my controller’s action methods, I got an error stating that “This DomainService has not been initialized.”  To solve this issue, I created an extension method for all DomainServices that creates the required DomainServiceContext and passes it to the service’s Initialize() method.  Here is the code for the extension method; notice that I am creating a sort of mock HttpContext for those cases when the service is running outside of IIS, such as during unit testing!     public static class ServiceExtensions     {         /// <summary>         /// Initializes the domain service by creating a new <see cref="DomainServiceContext"/>         /// and calling the base DomainService.Initialize(DomainServiceContext) method.         /// </summary>         /// <typeparam name="TService">The type of the service.</typeparam>         /// <param name="service">The service.</param>         /// <returns></returns>         public static TService Initialize<TService>(this TService service)             where TService : DomainService         {             var context = CreateDomainServiceContext();             service.Initialize(context);             return service;         }           private static DomainServiceContext CreateDomainServiceContext()         {             var provider = new ServiceProvider(new HttpContextWrapper(GetHttpContext()));             return new DomainServiceContext(provider, DomainOperationType.Query);         }           private static HttpContext GetHttpContext()         {             var context = HttpContext.Current;   #if DEBUG             // create a mock HttpContext to use during unit testing...             if ( context == null )             {                 var writer = new StringWriter();                 var request = new SimpleWorkerRequest("/", "/",                     String.Empty, String.Empty, writer);                   context = new HttpContext(request)                 {                     User = new GenericPrincipal(new GenericIdentity("debug"), null)                 };             } #endif               return context;         }     }   With that in place, I can use it almost as normally as my first attempt, except with a call to Initialize():     public ActionResult Index()     {         var service = new NorthwindService().Initialize();         var customers = service.GetCustomers();           return View(customers);     } 2. Insert / Update / Delete Once I got the records showing up, I was trying to insert new records or update existing data when I ran into the next issue.  I say issue because I wasn’t getting any kind of error, which made it a little difficult to track down.  But once I realized that that the DataContext.SubmitChanges() method gets called automatically at the end of each domain service submit operation, I could start working on a way to mimic the behavior of a hosted domain service.  What I came up with, was a base class called LinqToSqlRepository<T> that basically sits between your implementation and the default LinqToSqlDomainService<T> class.     [EnableClientAccess()]     public class NorthwindService : LinqToSqlRepository<NorthwindDataContext>     {         public IQueryable<Customer> GetCustomers()         {             return this.DataContext.Customers;         }           public void InsertCustomer(Customer customer)         {             this.DataContext.Customers.InsertOnSubmit(customer);         }           public void UpdateCustomer(Customer currentCustomer)         {             this.DataContext.Customers.TryAttach(currentCustomer,                 this.ChangeSet.GetOriginal(currentCustomer));         }           public void DeleteCustomer(Customer customer)         {             this.DataContext.Customers.TryAttach(customer);             this.DataContext.Customers.DeleteOnSubmit(customer);         }     } Notice the new base class name (just change LinqToSqlDomainService to LinqToSqlRepository).  I also added a couple of DataContext (for Table<T>) extension methods called TryAttach that will check to see if the supplied entity is already attached before attempting to attach it, which would cause an error! 3. LinqToSqlRepository<T> Below is the code for the LinqToSqlRepository class.  The comments are pretty self explanatory, but be aware of the [IgnoreOperation] attributes on the generic repository methods, which ensures that they will be ignored by the code generator and not available in the Silverlight client application.     /// <summary>     /// Provides generic repository methods on top of the standard     /// <see cref="LinqToSqlDomainService&lt;TContext&gt;"/> functionality.     /// </summary>     /// <typeparam name="TContext">The type of the context.</typeparam>     public abstract class LinqToSqlRepository<TContext> : LinqToSqlDomainService<TContext>         where TContext : System.Data.Linq.DataContext, new()     {         /// <summary>         /// Retrieves an instance of an entity using it's unique identifier.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <param name="keyValues">The key values.</param>         /// <returns></returns>         [IgnoreOperation]         public virtual TEntity GetById<TEntity>(params object[] keyValues) where TEntity : class         {             var table = this.DataContext.GetTable<TEntity>();             var mapping = this.DataContext.Mapping.GetTable(typeof(TEntity));               var keys = mapping.RowType.IdentityMembers                 .Select((m, i) => m.Name + " = @" + i)                 .ToArray();               return table.Where(String.Join(" && ", keys), keyValues).FirstOrDefault();         }           /// <summary>         /// Creates a new query that can be executed to retrieve a collection         /// of entities from the <see cref="DataContext"/>.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <returns></returns>         [IgnoreOperation]         public virtual IQueryable<TEntity> GetEntityQuery<TEntity>() where TEntity : class         {             return this.DataContext.GetTable<TEntity>();         }           /// <summary>         /// Inserts the specified entity.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <param name="entity">The entity.</param>         /// <returns></returns>         [IgnoreOperation]         public virtual bool Insert<TEntity>(TEntity entity) where TEntity : class         {             //var table = this.DataContext.GetTable<TEntity>();             //table.InsertOnSubmit(entity);               return this.Submit(entity, null, DomainOperation.Insert);         }           /// <summary>         /// Updates the specified entity.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <param name="entity">The entity.</param>         /// <returns></returns>         [IgnoreOperation]         public virtual bool Update<TEntity>(TEntity entity) where TEntity : class         {             return this.Update(entity, null);         }           /// <summary>         /// Updates the specified entity.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <param name="entity">The entity.</param>         /// <param name="original">The original.</param>         /// <returns></returns>         [IgnoreOperation]         public virtual bool Update<TEntity>(TEntity entity, TEntity original)             where TEntity : class         {             if ( original == null )             {                 original = GetOriginal(entity);             }               var table = this.DataContext.GetTable<TEntity>();             table.TryAttach(entity, original);               return this.Submit(entity, original, DomainOperation.Update);         }           /// <summary>         /// Deletes the specified entity.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <param name="entity">The entity.</param>         /// <returns></returns>         [IgnoreOperation]         public virtual bool Delete<TEntity>(TEntity entity) where TEntity : class         {             //var table = this.DataContext.GetTable<TEntity>();             //table.TryAttach(entity);             //table.DeleteOnSubmit(entity);               return this.Submit(entity, null, DomainOperation.Delete);         }           protected virtual bool Submit(Object entity, Object original, DomainOperation operation)         {             var entry = new ChangeSetEntry(0, entity, original, operation);             var changes = new ChangeSet(new ChangeSetEntry[] { entry });             return base.Submit(changes);         }           private TEntity GetOriginal<TEntity>(TEntity entity) where TEntity : class         {             var context = CreateDataContext();             var table = context.GetTable<TEntity>();             return table.FirstOrDefault(e => e == entity);         }     } 4. Conclusion So there you have it, a fully functional Repository implementation for your RIA Domain Services that can be consumed by your ASP.NET and MVC applications.  I have uploaded the source code along with unit tests and a sample web application that queries the Customers table from inside a Controller, as well as a Silverlight usage example. As always, I welcome any comments or suggestions on the approach I have taken.  If there is enough interest, I plan on contacting Colin Blair or maybe even the man himself, Brad Abrams, to see if this is something worthy of inclusion in the WCF RIA Services Contrib project.  What do you think? Enjoy!

    Read the article

  • Movement and Collision with AABB

    - by Jeremy Giberson
    I'm having a little difficulty figuring out the following scenarios. http://i.stack.imgur.com/8lM6i.png In scenario A, the moving entity has fallen to (and slightly into the floor). The current position represents the projected position that will occur if I apply the acceleration & velocity as usual without worrying about collision. The Next position, represents the corrected projection position after collision check. The resulting end position is the falling entity now rests ON the floor--that is, in a consistent state of collision by sharing it's bottom X axis with the floor's top X axis. My current update loop looks like the following: // figure out forces & accelerations and project an objects next position // check collision occurrence from current position -> projected position // if a collision occurs, adjust projection position Which seems to be working for the scenario of my object falling to the floor. However, the situation becomes sticky when trying to figure out scenario's B & C. In scenario B, I'm attempt to move along the floor on the X axis (player is pressing right direction button) additionally, gravity is pulling the object into the floor. The problem is, when the object attempts to move the collision detection code is going to recognize that the object is already colliding with the floor to begin with, and auto correct any movement back to where it was before. In scenario C, I'm attempting to jump off the floor. Again, because the object is already in a constant collision with the floor, when the collision routine checks to make sure moving from current position to projected position doesn't result in a collision, it will fail because at the beginning of the motion, the object is already colliding. How do you allow movement along the edge of an object? How do you allow movement away from an object you are already colliding with. Extra Info My collision routine is based on AABB sweeping test from an old gamasutra article, http://www.gamasutra.com/view/feature/3383/simple_intersection_tests_for_games.php?page=3 My bounding box implementation is based on top left/bottom right instead of midpoint/extents, so my min/max functions are adjusted. Otherwise, here is my bounding box class with collision routines: public class BoundingBox { public XYZ topLeft; public XYZ bottomRight; public BoundingBox(float x, float y, float z, float w, float h, float d) { topLeft = new XYZ(); bottomRight = new XYZ(); topLeft.x = x; topLeft.y = y; topLeft.z = z; bottomRight.x = x+w; bottomRight.y = y+h; bottomRight.z = z+d; } public BoundingBox(XYZ position, XYZ dimensions, boolean centered) { topLeft = new XYZ(); bottomRight = new XYZ(); topLeft.x = position.x; topLeft.y = position.y; topLeft.z = position.z; bottomRight.x = position.x + (centered ? dimensions.x/2 : dimensions.x); bottomRight.y = position.y + (centered ? dimensions.y/2 : dimensions.y); bottomRight.z = position.z + (centered ? dimensions.z/2 : dimensions.z); } /** * Check if a point lies inside a bounding box * @param box * @param point * @return */ public static boolean isPointInside(BoundingBox box, XYZ point) { if(box.topLeft.x <= point.x && point.x <= box.bottomRight.x && box.topLeft.y <= point.y && point.y <= box.bottomRight.y && box.topLeft.z <= point.z && point.z <= box.bottomRight.z) return true; return false; } /** * Check for overlap between two bounding boxes using separating axis theorem * if two boxes are separated on any axis, they cannot be overlapping * @param a * @param b * @return */ public static boolean isOverlapping(BoundingBox a, BoundingBox b) { XYZ dxyz = new XYZ(b.topLeft.x - a.topLeft.x, b.topLeft.y - a.topLeft.y, b.topLeft.z - a.topLeft.z); // if b - a is positive, a is first on the axis and we should use its extent // if b -a is negative, b is first on the axis and we should use its extent // check for x axis separation if ((dxyz.x >= 0 && a.bottomRight.x-a.topLeft.x < dxyz.x) // negative scale, reverse extent sum, flip equality ||(dxyz.x < 0 && b.topLeft.x-b.bottomRight.x > dxyz.x)) return false; // check for y axis separation if ((dxyz.y >= 0 && a.bottomRight.y-a.topLeft.y < dxyz.y) // negative scale, reverse extent sum, flip equality ||(dxyz.y < 0 && b.topLeft.y-b.bottomRight.y > dxyz.y)) return false; // check for z axis separation if ((dxyz.z >= 0 && a.bottomRight.z-a.topLeft.z < dxyz.z) // negative scale, reverse extent sum, flip equality ||(dxyz.z < 0 && b.topLeft.z-b.bottomRight.z > dxyz.z)) return false; // not separated on any axis, overlapping return true; } public static boolean isContactEdge(int xyzAxis, BoundingBox a, BoundingBox b) { switch(xyzAxis) { case XYZ.XCOORD: if(a.topLeft.x == b.bottomRight.x || a.bottomRight.x == b.topLeft.x) return true; return false; case XYZ.YCOORD: if(a.topLeft.y == b.bottomRight.y || a.bottomRight.y == b.topLeft.y) return true; return false; case XYZ.ZCOORD: if(a.topLeft.z == b.bottomRight.z || a.bottomRight.z == b.topLeft.z) return true; return false; } return false; } /** * Sweep test min extent value * @param box * @param xyzCoord * @return */ public static float min(BoundingBox box, int xyzCoord) { switch(xyzCoord) { case XYZ.XCOORD: return box.topLeft.x; case XYZ.YCOORD: return box.topLeft.y; case XYZ.ZCOORD: return box.topLeft.z; default: return 0f; } } /** * Sweep test max extent value * @param box * @param xyzCoord * @return */ public static float max(BoundingBox box, int xyzCoord) { switch(xyzCoord) { case XYZ.XCOORD: return box.bottomRight.x; case XYZ.YCOORD: return box.bottomRight.y; case XYZ.ZCOORD: return box.bottomRight.z; default: return 0f; } } /** * Test if bounding box A will overlap bounding box B at any point * when box A moves from position 0 to position 1 and box B moves from position 0 to position 1 * Note, sweep test assumes bounding boxes A and B's dimensions do not change * * @param a0 box a starting position * @param a1 box a ending position * @param b0 box b starting position * @param b1 box b ending position * @param aCollisionOut xyz of box a's position when/if a collision occurs * @param bCollisionOut xyz of box b's position when/if a collision occurs * @return */ public static boolean sweepTest(BoundingBox a0, BoundingBox a1, BoundingBox b0, BoundingBox b1, XYZ aCollisionOut, XYZ bCollisionOut) { // solve in reference to A XYZ va = new XYZ(a1.topLeft.x-a0.topLeft.x, a1.topLeft.y-a0.topLeft.y, a1.topLeft.z-a0.topLeft.z); XYZ vb = new XYZ(b1.topLeft.x-b0.topLeft.x, b1.topLeft.y-b0.topLeft.y, b1.topLeft.z-b0.topLeft.z); XYZ v = new XYZ(vb.x-va.x, vb.y-va.y, vb.z-va.z); // check for initial overlap if(BoundingBox.isOverlapping(a0, b0)) { // java pass by ref/value gotcha, have to modify value can't reassign it aCollisionOut.x = a0.topLeft.x; aCollisionOut.y = a0.topLeft.y; aCollisionOut.z = a0.topLeft.z; bCollisionOut.x = b0.topLeft.x; bCollisionOut.y = b0.topLeft.y; bCollisionOut.z = b0.topLeft.z; return true; } // overlap min/maxs XYZ u0 = new XYZ(); XYZ u1 = new XYZ(1,1,1); float t0, t1; // iterate axis and find overlaps times (x=0, y=1, z=2) for(int i = 0; i < 3; i++) { float aMax = max(a0, i); float aMin = min(a0, i); float bMax = max(b0, i); float bMin = min(b0, i); float vi = XYZ.getCoord(v, i); if(aMax < bMax && vi < 0) XYZ.setCoord(u0, i, (aMax-bMin)/vi); else if(bMax < aMin && vi > 0) XYZ.setCoord(u0, i, (aMin-bMax)/vi); if(bMax > aMin && vi < 0) XYZ.setCoord(u1, i, (aMin-bMax)/vi); else if(aMax > bMin && vi > 0) XYZ.setCoord(u1, i, (aMax-bMin)/vi); } // get times of collision t0 = Math.max(u0.x, Math.max(u0.y, u0.z)); t1 = Math.min(u1.x, Math.min(u1.y, u1.z)); // collision only occurs if t0 < t1 if(t0 <= t1 && t0 != 0) // not t0 because we already tested it! { // t0 is the normalized time of the collision // then the position of the bounding boxes would // be their original position + velocity*time aCollisionOut.x = a0.topLeft.x + va.x*t0; aCollisionOut.y = a0.topLeft.y + va.y*t0; aCollisionOut.z = a0.topLeft.z + va.z*t0; bCollisionOut.x = b0.topLeft.x + vb.x*t0; bCollisionOut.y = b0.topLeft.y + vb.y*t0; bCollisionOut.z = b0.topLeft.z + vb.z*t0; return true; } else return false; } }

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >