Search Results

Search found 10804 results on 433 pages for 'attribute keys'.

Page 173/433 | < Previous Page | 169 170 171 172 173 174 175 176 177 178 179 180  | Next Page >

  • Rails: keeping DRY with ActiveRecord models that share similar complex attributes

    - by Greg
    This seems like it should have a straightforward answer, but after much time on Google and SO I can't find it. It might be a case of missing the right keywords. In my RoR application I have several models that share a specific kind of string attribute that has special validation and other functionality. The closest similar example I can think of is a string that represents a URL. This leads to a lot of duplication in the models (and even more duplication in the unit tests), but I'm not sure how to make it more DRY. I can think of several possible directions... create a plugin along the lines of the "validates_url_format_of" plugin, but that would only make the validations DRY give this special string its own model, but this seems like a very heavy solution create a ruby class for this special string, but how do I get ActiveRecord to associate this class with the model attribute that is a string in the db Number 3 seems the most reasonable, but I can't figure out how to extend ActiveRecord to handle anything other than the base data types. Any pointers? Finally, if there is a way to do this, where in the folder hierarchy would you put the new class that is not a model? Many thanks.

    Read the article

  • Jquery Form ajaxSubmit not submitting

    - by Gazler
    Hi, I am using the JQuery Form extension to submit a form with AJAX. I have the following code: var options = { beforeSubmit: showRequest, // pre-submit callback success: showResponse, // post-submit callback // other available options: //url: url // override for form's 'action' attribute //type: 'post', // 'get' or 'post', override for form's 'method' attribute //dataType: null // 'xml', 'script', or 'json' (expected server response type) clearForm: true, // clear all form fields after successful submit //resetForm: true // reset the form after successful submit // $.ajax options can be used here too, for example: timeout: 3000 }; $('#composeForm').submit(function() { // inside event callbacks 'this' is the DOM element so we first // wrap it in a jQuery object and then invoke ajaxSubmit $(this).find(':disabled').removeAttr('disabled'); $(this).ajaxSubmit(options); // !!! Important !!! // always return false to prevent standard browser submit and page navigation return false; }); The problem is that the form doesn't appear to be submitting, or atleast the success function is not being called. If I remove the return false, then the submission works, but the page navigates away. Is there a problem in my code that could be causing this? Cheers, Gazler.

    Read the article

  • Django: Using 2 different AdminSite instances with different models registered

    - by omat
    Apart from the usual admin, I want to create a limited admin for non-staff users. This admin site will have different registered ModelAdmins. I created a folder /useradmin/ in my project directory and similar to contrib/admin/_init_.py I added an autodiscover() which will register models defined in useradmin.py modules instead of admin.py: # useradmin/__init__.py def autodiscover(): # Same as admin.autodiscover() but registers useradmin.py modules ... for app in settings.INSTALLED_APPS: mod = import_module(app) try: before_import_registry = copy.copy(site._registry) import_module('%s.useradmin' % app) except: site._registry = before_import_registry if module_has_submodule(mod, 'useradmin'): raise I also cretated sites.py under useradmin/ to override AdminSite similar to contrib/admin/sites: # useradmin/sites.py class UserAdminSite(AdminSite): def has_permission(self, request): # Don't care if the user is staff return request.user.is_active def login(self, request): # Do the login stuff but don't care if the user is staff if request.user.is_authenticated(): ... else: ... site = UserAdminSite(name='useradmin') In the project's URLs: # urls.py from django.contrib import admin import useradmin admin.autodiscover() useradmin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), (r'^useradmin/', include(useradmin.site.urls)), ) And I try to register different models in admin.py and useradmin.py modules under app directories: # products/useradmin.py import useradmin class ProductAdmin(useradmin.ModelAdmin): pass useradmin.site.register(Product, ProductAdmin) But when registering models in useradmin.py like useradmin.site.register(Product, ProductAdmin), I get 'module' object has no attribute 'ModelAdmin' exception. Though when I try this via shell; import useradmin from useradmin import ModelAdmin does not raise any exception. Any ideas what might be wrong? Edit: I tried going the @Luke way and arranged the code as follows as minimal as possible: (file paths are relative to the project root) # admin.py from django.contrib.admin import autodiscover from django.contrib.admin.sites import AdminSite user_site = AdminSite(name='useradmin') # urls.py (does not even have url patterns; just calls autodiscover()) import admin admin.autodiscover() # products/admin.py import admin from products.models import Product admin.user_site.register(Product) As a result I get an AttributeError: 'module' object has no attribute 'user_site' when admin.user_site.register(Product) in products/admin.py is called. Any ideas? Solution: I don't know if there are better ways but, renaming the admin.py in the project root to useradmin.py and updating the imports accordingly resolved the last case, which was a naming and import conflict.

    Read the article

  • Django forms, inheritance and order of form fields

    - by Hannson
    I'm using Django forms in my website and would like to control the order of the fields. Here's how I define my forms: class edit_form(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class create_form(edit_form): name = forms.CharField() The name is immutable and should only be listed when the entity is created. I use inheritance to add consistency and DRY principles. What happens which is not erroneous, in fact totally expected, is that the name field is listed last in the view/html but I'd like the name field to be on top of summary and description. I do realize that I could easily fix it by copying summary and description into create_form and loose the inheritance but I'd like to know if this is possible. Why? Imagine you've got 100 fields in edit_form and have to add 10 fields on the top in create_form - copying and maintaining the two forms wouldn't look so sexy then. (This is not my case, I'm just making up an example) So, how can I override this behavior? Edit: Apparently there's no proper way to do this without going through nasty hacks (fiddling with .field attribute). The .field attribute is a SortedDict (one of Django's internal datastructures) which doesn't provide any way to reorder key:value pairs. It does how-ever provide a way to insert items at a given index but that would move the items from the class members and into the constructor. This method would work, but make the code less readable. The only other way I see fit is to modify the framework itself which is less-than-optimal in most situations. In short the code would become something like this: class edit_form(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class create_form(edit_form): def __init__(self,*args,**kwargs): forms.Form.__init__(self,*args,**kwargs) self.fields.insert(0,'name',forms.CharField()) That shut me up :)

    Read the article

  • Need help with creating PDF from HTML using itextsharp

    - by Steven
    I'm trying to crate a PDF out of a HTML page. The CMS I'm using is EPiServer. This is my code so far: protected void Button1_Click(object sender, EventArgs e) { naaflib.pdfDocument(CurrentPage); } public static void pdfDocument(PageData pd) { //Extract data from Page (pd). string intro = pd["MainIntro"].ToString(); // Attribute string mainBody = pd["MainBody"].ToString(); // Attribute // makae ready HttpContext HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "application/pdf"; // Create PDF document Document pdfDocument = new Document(PageSize.A4, 80, 50, 30, 65); //PdfWriter pw = PdfWriter.GetInstance(pdfDocument, HttpContext.Current.Response.OutputStream); PdfWriter.GetInstance(pdfDocument, HttpContext.Current.Response.OutputStream); pdfDocument.Open(); pdfDocument.Add(new Paragraph(pd.PageName)); pdfDocument.Add(new Paragraph(intro)); pdfDocument.Add(new Paragraph(mainBody)); pdfDocument.Close(); HttpContext.Current.Response.End(); } This outputs the content of the article name, intro-text and main body. But it does not pars HTML which is in the article text and there is no layout. I've tried having a look at http://itextsharp.sourceforge.net/tutorial/index.html without becomming any wiser. Any pointers to the right direction is greatly appreciated :)

    Read the article

  • XML validation error when using multiple schema files/namespaces

    - by user129609
    Hi, I've been reading a ton about xml and learning a lot but I am stuck on one error. I have a schema defined in multiple files and I can't get it to work. Here is an example ================================== libraryBooks.xsd <?xml version="1.0" encoding="utf-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:MyNamespace" targetNamespace="urn:MyNamespace" elementFormDefault="qualified" > <xsd:element name="libraryBooks" type="libraryBooksType"/> <xsd:complexType name="libraryBooksType"> <xsd:sequence> <xsd:any minOccurs="0"/> </xsd:sequence> <xsd:attribute name="name" type="xsd:string"/> </xsd:complexType> </xsd:schema> ================================== book.xsd <?xml version="1.0" encoding="utf-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:MyNamespace2" targetNamespace="urn:MyNamespace2" elementFormDefault="qualified" > <xsd:element name="book" type="booksType"/> <xsd:complexType name="bookType"> <xsd:attribute name="title" type="xsd:string"/> </xsd:complexType> </xsd:schema> ================================== myXml.xml <?xml version="1.0" encoding="utf-8" ?> <libraryBooks xmlns="urn:MyNamespace" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:MyNamespace file:///C:/libraryBooks.xsd" name="CentralLibrary"> <mn2:book xmlns:mn2="file:///C:/book.xsd" title="How to make xml work the way I want"> </mn2:book> </libraryBooks> So the error I get would be "The 'file:///C:/book.xsd:book' element is not found". Any ideas? I'm almost certain it is something simple

    Read the article

  • Best pattern for storing (product) attributes in SQL Server

    - by EdH
    We are starting a new project where we need to store product and many product attributes in a database. The technology stack is MS SQL 2008 and Entity Framework 4.0 / LINQ for data access. The products (and Products Table) are pretty straightforward (a SKU, manufacturer, price, etc..). However there are also many attributes to store with each product (think industrial widgets). These may range from color to certification(s) to pipe size. Every product may have different attributes, and some may have multiples of the same attribute (Ex: Certifications). The current proposal is that we will basically have a name/value pair table with a FK back to the product ID in each row. An example of the attributes Table may look like this: ProdID AttributeName AttributeValue 123 Color Blue 123 FittingSize 1.25 123 Certification AS1111 123 Certification EE2212 123 Certification FM.3 456 Pipe 11 678 Color Red 999 Certification AE1111 ... Note: Attribute name would likely come from a lookup table or enum. So the main question here is: Is this the best pattern for doing something like this? How will the performance be? Queries will be based on a JOIN of the product and attributes table, and generally need many WHEREs to filter on specific attributes - the most common search will be to find a product based on a set of known/desired attributes. If anyone has any suggestions or a better pattern for this type of data, please let me know. Thanks! -Ed

    Read the article

  • Data loss when downloading data from LDAP server

    - by Ricky D'Amelio
    Hi there. This question comes from a previous one I asked about handling NSData objects: http://stackoverflow.com/questions/2453785/converting-nsdata-to-an-nsstring-representation-is-failing. I have reached the point where I am taking an NSImage, turning it into NSData and uploading those data bytes to the LDAP server. I am doing this like so; //connected successfully to LDAP server above... struct berval photo_berval; struct berval *jpegPhoto_values[2]; photo_berval.bv_len = [photo length]; photo_berval.bv_val = [photo bytes]; jpegPhoto_values[0] = &photo_berval; jpegPhoto_values[1] = NULL; mod.mod_type = "jpegPhoto"; mod.mod_op = LDAP_MOD_REPLACE|LDAP_MOD_BVALUES; mod.mod_bvalues = jpegPhoto_values; mods[0] = &mod; mods[1] = NULL; //perform the modify operation rc = ldap_modify_ext_s(ld, givenModifyEntry, mods, NULL, NULL); That happens with no errors, and you can see a big blob of data when you're in the command line. My problem is, when I go to access the same data at a later stage, I am getting an image file back that's about 120 times smaller than the original image. //find the jpegPhoto attribute photoA = ldap_first_attribute(ld, photoE, &photoBer); while (strcasecmp(photoA, "jpegphoto") != 0) { photoA = ldap_next_attribute(ld, photoE, photoBer); } //get the value of the attribute if ((list_of_photos = ldap_get_values_len(ld, photoE, photoA)) != NULL) { //get the first JPEG photo_data = *list_of_photos[0]; selectedPictureData = [NSData dataWithBytes:&photo_data length:sizeof(photo_data)]; [selectedPictureData writeToFile:@"/Users/username/Desktop/Photo 2.jpg" atomically:YES]; NSLog (@"%@", selectedPictureData); Has anyone successfully done this before or can anyone see what I might be doing wrong? I appreciate anyone's help. Sorry to post so many questions! Ricky.

    Read the article

  • MooTools Event Delegation using HTML5 data attributes.

    - by Anurag
    Is it possible to have event delegation using the HTML5 data attributes in MooTools? The HTML structure I have is: ?<div id="parent"> <div>not selectable</div> <div data-selectable="true">selectable</div> <div>not selectable either.</div> <div data-selectable="true">also selectable</div> </div>???????????????????????????????????????????????????????????????????????? And I want to setup <div id="parent"> to listen to all clicks only on child elements that have the data-selected attribute. Please let me know if I'm doing something wrong: The events are being setup as: $("parent").addEvent("click:relay([data-selectable])", function(event, el) { alert(this.get('text')); }); but the click callback is fired on clicking all div's, not just the ones with a data-selectable attribute defined. You can see this example on http://jsfiddle.net/NUGD4/ A workaround is to adding this as a CSS class, which works with delegation but I would prefer to be able to use data-attributes as it's used throughout the application.

    Read the article

  • Unusual request URL in ASP.NET health monitoring event

    - by Troy Hunt
    I’m seeing a rather strange occurrence in the request information section of an ASP.NET health monitoring email I hope someone can shed some light on. This is a publicly facing website which runs on infrastructure at an Indian hosting provider. Health monitoring is notifying us of server errors via automated email but every now and then the requested URL appears as a totally different website. For example: Request information: Request URL: http://www.baidu.com/Default.aspx Request path: /Default.aspx User host address: 221.13.128.175 User: Is authenticated: False Authentication Type: Thread account name: NT AUTHORITY\NETWORK SERVICE Obviously the site in question is not Baidu and obviously this attribute is not the referrer either; the “Request URL” value is the path which has generated the error. The IP address is located in Beijing (coincidental given the Baidu address?) and in this instance it looks like the SQL server backend was not accessible (I haven't included the entire error message for security's sake). What would cause the request URL attribute to be arbitrarily changed to that of another site? I’ve never seen this occur in a health monitoring event before. Thanks!

    Read the article

  • Possible to programatically access X-Mms-Content-Location?

    - by Brad Hein
    Is it possible to access the X-Mms-Content-Location attribute of a message from a MMS message programatically, using the Android SDK? This is one example of the error that I am investigating. If I can access that attribute, then I may be able to code an app which repairs it so the message retrieval succeeds. 04-26 19:11:35.573 V/RetrieveTransaction( 299): X-Mms-Content-Location: http://69.78.70..70/servlets/mms?message-id=<GUID_REMOVED_FOR_PRIVACY> <snip> 04-26 19:11:35.783 I/InetAddress( 299): Unknown host 69.78.70..70, throwing UnknownHostException 04-26 19:11:35.793 V/RetrieveTransaction( 299): Unexpected IOException. 04-26 19:11:35.793 V/RetrieveTransaction( 299): java.io.IOException: Cannot establish route for http://69.78.70..70/servlets/mms?message-id=<GUID_REMOVED_FOR_PRIVACY>: Unknown host 04-26 19:11:35.793 V/RetrieveTransaction( 299): at com.android.mms.transaction.Transaction.ensureRouteToHost(Transaction.java:206) 04-26 19:11:35.793 V/RetrieveTransaction( 299): at com.android.mms.transaction.Transaction.getPdu(Transaction.java:171) 04-26 19:11:35.793 V/RetrieveTransaction( 299): at com.android.mms.transaction.RetrieveTransaction.run(RetrieveTransaction.java:147) 04-26 19:11:35.793 V/RetrieveTransaction( 299): at java.lang.Thread.run(Thread.java:1058) 04-26 19:11:35.793 E/RetrieveTransaction( 299): Retrieval failed.

    Read the article

  • How do I manage application configuration in ASP.NET?

    - by GlennS
    I am having difficulty with managing configuration of an ASP.Net application to deploy for different clients. The sheer volume of different settings which need twiddling takes up large amounts of time, and the current configuration methods are too complicated to enable us to push this responsibility out to support partners. Any suggestions for better methods to handle this or good sources of information to research? How we do things at present: Various xml configuration files which are referenced in Web.Config, for example an AppSettings.xml. Configurations for specific sites are kept in duplicate configuration files. Text files containing lists of data specific to the site In some cases, manual one-off changes to the database C# configuration for Windsor IOC. The specific issues we are having: Different sites with different features enabled, different external services we have to talk to and different business rules. Different deployment types (live, test, training) Configuration keys change across versions (get added, remove), meaning we have to update all the duplicate files We still need to be able to alter keys while the application is running Our current thoughts on how we might approach this are: Move the configuration into dynamically compiled code (possibly Boo, Binsor or JavaScript) Have some form of diffing/merging configuration: combine a default config with a live/test/training config and a site-specific config

    Read the article

  • JAXB boolean handling oddities and JSF

    - by finrod
    There is a known bug in JAXB: https://jaxb.dev.java.net/issues/show_bug.cgi?id=733 JAXB does not properly generate boolean field getters and setters, this bug is left unfixed for backwards compatibility. A JAXB plugin exists and will ensure that the following getters and setters for boolean fields are generated: setXXX(Boolean value) is generated getXXX() is generated If the boolean attribute specifies default value in the XSD, then getXXX() returns boolean, If the boolean attribute does not specify default in the XSD, then getXXX() returns Boolean. Problem: trying to edit/view the XXX field in a JSF component (such as checkbox) does not work - the component is disabled. I have not traced this in depth but the assumption (backed by the workaround below) is that JSF EL resolver (or whathaveyou) looks for Boolean getXXX() method and since it does not find it, the component is disabled. Workaround: If I change the getXXX() method to always return Boolean, then everything goes. Questions: What are your ideas to address this problem? Have I missed some customization for the boolean-getter JAXB plugin? Is it possible (does it make sense) to alter JSF resolver (or whathaveyou) so that if Boolean getXXX() is not found, it will fall back to boolean getXXX()? I would prefer not to manually intervene and change all the generated getXXX() methods to return Boolean instead of boolean.

    Read the article

  • Android: How to get a custom view to redraw partially?

    - by Peterdk
    I have a custom view that fills my entire screen. (A piano keyboard) When a user touches the key, it would cause a invalidate() to be called and the whole keyboard gets redrawn to show the new state with a touched key. Currently the view is very simple, but I plan to add a bit more nice graphics. Since the whole keyboard is dynamically rendered this would make redrawing the entire keyboard more expensive. So I thought, let's look into partial redrawing. Now I call invalidate(Rect dirty) with the correct dirty region. I set my onDraw(Canvas canvas) method to only draw the keys in the dirty region if I do indeed want a partial redraw. This results in those keys being drawn, but the rest of the keyboard is totally black/not drawn at all. Am I wrong in expecting that calling invalidate(Rect dirty) would "cache" the current canvas, and only "allows" drawing in the dirty region? Is there any way I can achieve what I want? (A way to "cache" the canvas and only redraw the dirty area?"

    Read the article

  • xsd.exe - schema to class - for use with WCF

    - by NealWalters
    I have created a schema as an agreed upon interface between our company and an external company. I am now creating a WCF C# web service to handle the interface. I ran the XSD utility and it created a C# class. The schema was built in BizTalk, and references other schemas, so all-in-all there are over 15 classes being generated. I put [DataContract} attribute in front of each of the classes. Do I have to put the [DataMember] attribute on every single property? When I generate a test client program, the proxy does not have any code for any of these 15 classes. We used to use this technique when using .asmx services, but not sure if it will work the same with WCF. If we change the schema, we would want to regenerate the WCF class, and then we would haev to each time redecorate it with all the [DataMember] attributes? Is there an newer tool similar to XSD.exe that will work better with WCF? Thanks, Neal Walters SOLUTION (buried in one of Saunders answer/comments): Add the XmlSerializerFormat to the Interface definition: [OperationContract] [XmlSerializerFormat] // ADD THIS LINE Transaction SubmitTransaction(Transaction transactionIn); Two notes: 1) After I did this, I saw a lot more .xsds in the my proxy (Service Reference) test client program, but I didn't see the new classes in my intellisense. 2) For some reason, until I did a build on the project, I didn't get all the classes in the intellisense (not sure why).

    Read the article

  • Django DRY Feeds

    - by Mandx
    I'm using the Django Feeds Framework and it's really nice, very intuitive and easy to use. But, I think there is a problem when creating links to feeds in HTML. For example: <link rel="alternate" type="application/rss+xml" title="{{ feed_title }}" href="{{ url_of_feed }}" /> Link's HREF attribute can be easily found out, just use reverse() But, what about the TITLE attribute? Where the template engine should look for this? Even more, what if the feed is build up dinamically and the title depends on parameters (like this)? I can't come up with a solution that "seems" DRY to me... All that I can come up with is using context processors o template tags, but it gets messy when the context procesor/template tag has to find parameters to construct the Feed class, and writing this I realize I don't even know how to create a Feed instance myself within the view. If I put all this logic in the view, it would not be just one view. Also, the value for TITLE would be in the view AND in the feed.

    Read the article

  • GAE AttributeError

    - by awegawef
    My GAE app runs fine from my computer, but when I upload it, I start getting an AttributeError, specifically: AttributeError: 'dict' object has no attribute 'item' I am using the pylast interface (an API for last.fm--link). Specifically, I am accessing a list of variables of this type: SimilarItem = _namedtuple("SimilarItem", ["item", "match"]) I have a variable of this type, call it sim, and I am trying to access sim.item when I get the attribute error. I should note that I am using Python 2.6 on my computer, and I understand that GAE runs on Python 2.5. Would that make a difference here? I thought they were backwards-compatible. Lastly, I think it could be a possible problem with the modules that pylast imports--maybe they don't work with GAE or something? I did some research but I didn't get any results. Here are the imports: import hashlib import httplib import urllib import threading from xml.dom import minidom import xml.dom import time import shelve import tempfile import sys import htmlentitydefs I would appreciate any help with this frustrating issue. Thanks in advance.

    Read the article

  • issue in property file

    - by devuser
    I want to load the property file when tomcat is starting.so I'm using servletContextListener to do that and i can get values of property file to my web application. But i want to keep the same value after changing the property file once log into web application.But when i change the value of property file and log into system again it change the value to new one.I want to keep the same value that loaded when tomcat was starting.how can i implement this? My coding is as below import javax.servlet.*; import java.io.IOException; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import java.io.*; import java.util.ResourceBundle; public final class sysProperties implements javax.servlet.ServletContextListener { private static Properties props = new Properties(); private static String file_name = "com/util/contact.properties"; public addSystemProperties() { } public void contextInitialized(ServletContextEvent servletContextEvent) { // Get the context ServletContext servletContext = servletContextEvent.getServletContext(); // Set a context attribute try { // props.load(servletContext.getResourceAsStream(file_name)); props.load(getClass().getClassLoader().getResourceAsStream(file_name)); System.out.println(" Application X is starting"); servletContext.setAttribute("h1",props.getProperty("home.h1")); servletContext.setAttribute("h2",props.getProperty("home.h2")); System.out.println("h1"+servletContext.getAttribute("h1")); System.out.println("h2"+ servletContext.getAttribute("h2")); ; } catch (Exception e) { System.out.println(" Error setting context attribute: " + e.getMessage()); } } public void contextDestroyed(ServletContextEvent servletContextEvent) { // Get the context ServletContext servletContext = servletContextEvent.getServletContext(); // Output the context variable we set earlier System.out.println(" Application X is shutting down"); System.out.println(" Value of h1 is: " + servletContext.getAttribute("h1")); System.out.println(" Value of h2 is: " + servletContext.getAttribute("h2")); // Clean up (not really necessary as the context is being destroyed, but let's be neat) servletContext.removeAttribute(props.getProperty("h1")); servletContext.removeAttribute(props.getProperty("h2")); } }

    Read the article

  • How to Create Deterministic Guids

    - by desigeek
    In our application we are creating Xml files with an attribute that has a Guid value. This value needed to be consistent between file upgrades. So even if everything else in the file changes, the guid value for the attribute should remain the same. One obvious solution was to create a static dictionary with the filename and the Guids to be used for them. Then whenever we generate the file, we look up the dictionary for the filename and use the corresponding guid. But this is not feasible coz we might scale to 100's of files and didnt want to maintain big list of guids. So another approach was to make the Guid the same based on the path of the file. Since our file paths and application directory structure are unique, the Guid should be unique for that path. So each time we run an upgrade, the file gets the same guid based on its path. I found one cool way to generate such 'Deterministic Guids' (Thanks Elton Stoneman). It basically does this: private Guid GetDeterministicGuid(string input) { //use MD5 hash to get a 16-byte hash of the string: MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider(); byte[] inputBytes = Encoding.Default.GetBytes(input); byte[] hashBytes = provider.ComputeHash(inputBytes); //generate a guid from the hash: Guid hashGuid = new Guid(hashBytes); return hashGuid; } So given a string, the Guid will always be the same. Are there any other approaches or recommended ways to doing this? What are the pros or cons of that method?

    Read the article

  • Using Directives, Namespace and Assembly Reference - all jumbled up with StyleCop!

    - by Jack
    I like to adhere to StyleCop's formatting rules to make code nice and clear, but I've recently had a problem with one of its warnings: All using directives must be placed inside of the namespace. My problem is that I have using directives, an assembly reference (for mocking file deletion), and a namespace to juggle in one of my test classes: using System; using System.IO; using Microsoft.Moles.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting; [assembly: MoledType(typeof(System.IO.File))] namespace MyNamespace { //Some Code } The above allows tests to be run fine - but StyleCop complains about the using directives not being inside the namespace. Putting the usings inside the namespace gives the error that "MoledType" is not recognised. Putting both the usings and the assembly reference inside the namespace gives the error 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. It seems I've tried every layout I can but to no avail - either the solution won't build, the mocking won't work or StyleCop complains! Does anyone know a way to set these out so that everything's happy? Or am I going to have to ignore the StyleCop warning in this case?

    Read the article

  • classpath error when executing a jar by ant

    - by changed
    Hi I am trying to execute a jar file created using ant. But i am not able to find out why libraries are not available while executing jar. I am trying to load derby embedded database driver but some how i am not getting derby.jar in classpath. Error that i am getting is [java] Unable to load the JDBC driver org.apache.derby.jdbc.EmbeddedDriver [java] Please check your CLASSPATH. [java] java.lang.ClassNotFoundExcepApplication Started [java] tion: org.apache.derby.jdbc.EmbeddedDriver [java] at java.net.URLClassLoader$1.run(URLClassLoader.java:200) a <path id="jar.classpath"> <fileset dir="${lib.dir}" includes="*.jar" /> </path> <path id="compiled-src.jar.classpath"> <path refid="jar.classpath" /> <pathelement location="${build.classes.dir}" /> </path> <target name="jar" depends="compile-src" description="Create Jar"> <mkdir dir="${dist.dir}" /> <manifestclasspath property="lib.list" jarfile="${dist.dir}/"> <classpath refid="jar.classpath" /> </manifestclasspath> <jar destfile="${dist.dir}/${ant.project.name}.jar" basedir="${build.classes.dir}" > <manifest> <attribute name="Main-Class" value="${main-class}" /> <attribute name="Class-Path" value="${lib.list}" /> </manifest> </jar> </target> <target name="run" depends="jar" description="Run application from jar"> <java jar="${dist.dir}/${ant.project.name}.jar" fork="true" /> </target>

    Read the article

  • Alternative to array_shift function

    - by SoLoGHoST
    Ok, I need keys to be preserved within this array and I just want to shift the 1st element from this array. Actually I know that the first key of this array will always be 1 when I do this: // Sort it by 1st group and 1st layout. ksort($disabled_sections); foreach($disabled_sections as &$grouplayout) ksort($grouplayout); Basically I'd rather not have to ksort it in order to grab this array where the key = 1. And, honestly, I'm not a big fan of array_shift, it just takes to long IMO. Is there another way. Perhaps a way to extract the entire array where $disabled_sections[1] is found without having to do a foreach and sorting it, and array_shift. I just wanna add $disabled[1] to a different array and remove it from this array altogether. While keeping both arrays keys structured the way they are. Technically, it would even be fine to do this: $array = array(); $array = $disabled_sections[1]; But it needs to remove it from $disabled_sections. Can I use something like this approach... $array = array(); $array = $disabled_sections[1]; $disabled_sections -= $disabled_sections[1]; Is something like the above even possible?? Thanks.

    Read the article

  • How to transfer objects through the header in WCF

    - by Michael
    I'm trying to transfer some user information in the header of the message through message inspectors. I have created a behavior which adds the inspector to the service (both client and server). But when I try to communicate with the service I get the following error: XmlException: Name cannot begin with the '<' character, hexadecimal value 0x3C. I have also get exception telling me that DataContracts where unexpected. Type 'System.DelegateSerializationHolder+DelegateEntry' with data contract name 'DelegateSerializationHolder.DelegateEntry:http://schemas.datacontract.org/2004/07/System' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer. The thing is that my object contains other objects which are marked as DataContract and I'm not interested adding the KnownType attribute for those types. Another problem might be that my object to serialize is very restricted in form of internal class and internal properties etc. Can anyone guide me in the right direction. What I'm I doing wrong? Some code: public virtual object BeforeSendRequest(ref Message request, IClientChannel channel) { var header = MessageHeader.CreateHeader("<name>", "<namespace>", object); request.Headers.Add(header); return Guid.NewGuid(); }

    Read the article

  • XML parsing design using xmlpp and C++

    - by shagv
    I would like to use an xml format similar to the following: <CONFIG> <PROFILE NAME="foobar"> <PARAM ID="0" NAME="Foo" CLASS="BaseParam"/> <PARAM ID="2" NAME="Bar" CLASS="StrIntParam"> <VALUE TYPE="STRING">some String</VALUE> <VALUE TYPE="INT">1234</VALUE> </PARAM> </PROFILE> </CONFIG> CONFIG contains a list of PROFILEs which contain a list of PARAMs which themselves can be any structure (to be defined in the future). The idea was to define classes that parsed each PARAM type and to keep track of which class to use in the PARAM's CLASS attribute. In code I have a config class that manages the list of profiles and a profile class that manages the list of params. I would like the profile class to handle additional param types (that inherit BaseParam) without modification to the profile class (or at the very least with minimal modification). First of all, is this design viable? If so, what are some ways I could use different param classes and have their creation at run-time be automatic (the profile class sees the CLASS attribute and knows which type to create)?

    Read the article

  • Single Sign On for WebServices, WCS, WFS, WMS (Geoserver), etc.

    - by lajuette
    I'm trying to implement a Single Sign On (SSO) for a web application. Maybe you can help me find a proper solution, give me a direction or tell me, that solutions already exist. The scenario: A GeoExt (ExtJS for geodata/map based apps) webapp (JavaScript only) has a login form to let the user authenticate himself. The authentication is not implemented yet, so i'm flexible with respect to that. After authenticating to the main webapp the user indirectly accesses multiple 3rd-party services like WebServices, GeoServer WFS, Google Maps, etc. These services might require additional authentication like credentials or keys. We are (so far) not talking about additional login screens, just some kind of "machine to machine"-authentication. The main problem: I'm unable to modify the 3rd party services (e.g. Google) to add a SSO mechanism. I'd like to have a solution that allows the user to log in once to have access to all the services required. My first idea was a repository that stores all the required credentials or keys. The user logs in and can retrieve all required information to acces sthe other services. Does anybody know of existing implementations, papers, maybe implementations of such services? Other requirements: The communication between the JS application and the repository must be secure. The credentials must be stored in a secure manner. But the JS app must be able to use them to access the services (no chance to store a decryption key in a JS-app securely, eh? *g).

    Read the article

< Previous Page | 169 170 171 172 173 174 175 176 177 178 179 180  | Next Page >