Sunday, April 17, 2011

Using Castle for logging thrown exceptions in WCF (and otherwise)

Hello,

I'm writing a WCF web service and I'm wondering if there's an elegant (aspect-oriented) way to use Castle interceptor mechanism for logging exceptions thrown by my web methods? I know about the IInterceptor inteface, but I could not find any exception information there.

I've seen http://stackoverflow.com/questions/238755/castle-aop-and-logging-in-net, but it only covers method's parameters.

Is there a better (WCF or Castle's) mechanism for doing this? BTW I'm using log4net for logging.

UPDATE: I know about WCF's logging facilities, but I was looking more for a general solution, not just in WCF environment.

Thanks in advance.

From stackoverflow
  • You should use the build in WCF tracing and logging. Then you can use the WCF Trace Viewer which will piece together logs from service and client so that you can see the full message flow.

    http://www.devx.com/dotnet/Article/37389/0/page/6

    There is the IErrorHandler interface in WCF:

    public interface IErrorHandler
    {
        bool HandleError(Exception error, MessageFault fault);
        void ProvideFault(Exception error, ref MessageFault fault, ref string faultAction);
    }
    

    More details here: http://www.extremeexperts.com/Net/Articles/ExceptionHandlingInWCF.aspx

    Igor Brejc : Ok, but let's generalize the question: how would you do it in a non-WCF environment?
    Jonathan Parker : I've updated my answer.
  • If you want to use Castle Interceptors in general, you could do something like this:

    public void Intercept(IInvocation invocation)
    {
       //do some preprocessing here if needed
       try
       {
          invocation.Proceed()
       }
       catch(Exception e)
       {
          LogException(e);
          throw;
       }
       finally
       {
          //do some postprocessing jf needed
       }
    }
    

How do you create folders and specify access permissions on them at the same time?

I have a windows forms application which serves as a sort of administrative module for an ASP.NET web application. The web application serves multiple countries, and folders are created when new countries are added to the application data.

Unfortunately on the newly added countries I run into an exception with the web application when I go and try to write files in the folders:

System.UnauthorizedAccessException: Access to the path 'C:\...' is denied.

With the web application using ASP.NET impersonation, it's obvious that the default IIS user (MACHINENAME\IUSR_MACHINENAME) has no permissions to write into the folder.

How do I grant permission the the default IIS user upon folder creation?

I understand that

System.IO.Directory.CreateDirectory(string path, DirectorySecurity directorySecurity)

should do this, but I don't understand how to specify the log on name on the DirectorySecurity object.

From stackoverflow
  • Grant permission to create directories and files (read/write/modify/...) to the worker process group (sysname\iis_wpg) to the parent directory of where you want to create the new directories. Make sure that you've set the permissions to apply to this folder, subfolders, and files, then the permissions will be inherited for new folders you create and you won't need to apply them specifically. Rather than doing this for all of App_Data, I'd suggest creating a specific subdirectory and only granting permissions on that subdirectory. If you have multiple apps running on the box you might want to create a new user for the app to run as, change the id of the worker process group, and grant only permission to that specific user.

  • This is the solution I used eventually:

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
                DirectoryInfo info = new DirectoryInfo(path);
                DirectorySecurity security = info.GetAccessControl();
    
                security.AddAccessRule(new FileSystemAccessRule(logonName, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
                security.AddAccessRule(new FileSystemAccessRule(logonName, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
    
                info.SetAccessControl(security); 
            }
    
    Steven Sudit : This is not a great solution, as the directory initially has only default permissions, which are then replaced. In principle, it is possible to hijack the directory by changing its owner to lock the original creator out. For an example of how to specify DirectorySecurity as part of the CreateSubDirectory, see http://stackoverflow.com/questions/1532014/file-permissions-do-not-inherit-directory-permissions

Selenium browser detection

Good morning

I have been running a few tests over the past couple of weeks and I have come up against a bit of a wall.

I am testing in IE 7 and 8 and firefox.

Basically my problem is that IE 8 does not yet support a plug in and firefox does not support a referer in a frameset, so basically I want to do is detect which browser I am using and then if its ie 7 run the tests, else skip certain tests, is this possible?

Thanking everyone in advance for their help.

Cheers

Cameron

From stackoverflow
  • Hmmm one solution that came up in my mind... maybe it's a little bit odd, but I think it should work: let your Web app. read the HTTP UserAgent and save it as a hidden HTML input field. Then you can access it from your Selenium tests and decide whether you want to continue running them or not.

    Maybe there's a better solution, I don't know.

  • I might be missing something (probably!) but if all you're trying to do is target tests to IE then would conditional comments work?

    <!--[if ie 7]>
    
        The tests go here.
    
    <![endif]-->
    
  • Just a note for anyone else who reads this: the question is around using Selenium Core and the solution is designed to edit the HTML-based test suite file. If you're using Selenium RC, you obviously know which browser you launched :)

Clustered primary key on unique identifier ID column in SQL Server

If your ID column on a table is a unique identifier (Guid), is there any point creating a clustered primary key on the ID column?

Given that they are globally unique, how would the sorting work?

From stackoverflow
  • I strongly advise against using clustered Guid key... We had big performance issues on SQL server because of such poor design a few years ago.

    Also check out: http://stackoverflow.com/questions/583001/improving-performance-of-cluster-index-guid-primary-key

  • GUIDs as they are are terrible for performance since they are effectively random values (this "breaks" clustered index), and they are awful for indexes, since less entries fit on a single page/extent (SQL Server terms). SQL Server 2005 introduces newsequentialid() which helps solving first problem.

  • Putting a clustered index on a guid column is not such a good idea (unless you're making use of sequential guids).

    The clustered index determines the physical order of how the records are stored.
    This means that, if you put a clustered index on a column that does not sequentially grow, SQL Server will have some work making sure that the records are correctly ordered physically when you insert new records.

  • The idea of having a sorted index is very good in itself as searching then becomes very efficient.

    The problem however is that in case of a GUID one never searches with "WHERE GUID = xyz". So the whole concept is wasted. So I would suggest to rather have a clustered index on a column which is used most often as a SARG to increase the query efficiency.

    Henk Holterman : I think "WHERE GUID = xyz" is used a lot, in selecting single records. But ab "ORDER BY guid" would be very rare.

Why is this type variable ambiguous?

Cabbage.hs:

module Cabbage where 
class Cabbage a
  where foo :: a -> String      -- the parameter is only present for its type,
                                -- the parameter value will be ignored
        bar :: String -> a
quux :: Cabbage a => String -> a
quux s = bar (s ++ foo (undefined :: a))

When I compile (with ghc) I get this error message:

Cabbage.hs:7:19:
    Ambiguous type variable `a' in the constraint:
      `Cabbage a' arising from a use of `foo' at Cabbage.hs:7:19-38
    Probable fix: add a type signature that fixes these type variable(s)

I don't understand why a is ambiguous. Surely the a in line 7 is the same as the a in line 6? How do I fix this?

Alternatively, is there a better way of declaring a per-instance constant?

From stackoverflow
  • The problem is that Haskell doesn't know which instance of Cabbage that foo corresponds to there. So far as I know, it doesn't match the a in (undefined :: a) with the a in quux :: Cabbage a => String -> a

    Assuming that's what you want, you can do this:

    quux :: Cabbage a => String -> a
    quux s = result
        where result = bar (s ++ foo result)
    

    This ties foo and bar together so that it uses the same instance for both, and since you don't actually need the value of the input for foo, it bottoms out. I don't know of a better way of doing per-instance constants though. Hopefully someone else will come along who does.

  • Using scoped type variables you can let GHC know that the undefined :: a should be the same (otherwise a is just a shorthand for forall a. a). Scoped type variables must then be explicitly forall-qualified:

    {-# LANGUAGE ScopedTypeVariables #-}
    module Cabbage where 
    class Cabbage a
      where foo :: a -> String      -- the parameter is only present for its type,
                                    -- the parameter value will be ignored
            bar :: String -> a
    quux :: forall a. Cabbage a => String -> a
    quux s = bar (s ++ foo (undefined :: a))
    
  • you can extract out the polymorphic part as a function

    quux :: Cabbage a => String -> a
    quux s = quux' undefined
        where quux' :: Cabbage a => a -> a
              quux' x = bar (s ++ foo x)
    

Parsing an HTML table using Hpricot (Ruby)

I am trying to parse an HTML table using Hpricot but am stuck, not able to select a table element from the page which has a specified id.

Here is my ruby code:-

require 'rubygems'
require 'mechanize'
require 'hpricot'

agent = WWW::Mechanize.new

page = agent.get('http://www.indiapost.gov.in/pin/pinsearch.aspx')

form = page.forms.find {|f| f.name == 'form1'}
form.fields.find {|f| f.name == 'ddl_state'}.options[1].select
page = agent.submit(form, form.buttons[2])

doc = Hpricot(page.body)

puts doc.to_html # Here the doc contains the full HTML page

puts doc.search("//table[@id='gvw_offices']").first # This is NIL

Can anyone help me to identify what's wrong with this.

Thanks so much

From stackoverflow
  • Mechanize will use hpricot internally (it's mechanize's default parser). What's more, it'll pass the hpricot stuff on to the parser, so you don't have to do it yourself:

    require 'rubygems'
    require 'mechanize'
    
    #You don't really need this if you don't use hpricot directly
    require 'hpricot'
    
    agent = WWW::Mechanize.new
    
    page = agent.get('http://www.indiapost.gov.in/pin/pinsearch.aspx')
    
    form = page.forms.find {|f| f.name == 'form1'}
    form.fields.find {|f| f.name == 'ddl_state'}.options[1].select
    page = agent.submit(form, form.buttons[2])
    
    puts page.parser.to_html # page.parser returns the hpricot parser
    
    puts page.at("//table[@id='gvw_offices']") # This passes through to hpricot
    

    Also note that page.search("foo").first is equivalent to page.at("foo").

  • Note that Mechanize no longer uses Hpricot (it uses Nokogiri) by default in the later versions (0.9.0) and you have to explicitly specify Hpricot to continue using with:

      WWW::Mechanize.html_parser = Hpricot
    

    Just like that, no quotes or anything around Hpricot - there's probably a module you can specify for Hpricot, because it won't work if you put this statement inside your own module declaration. Here's the best way to do it at the top of your class (before opening module or class)

    require 'mechanize'
    require 'hpricot'
    
    # Later versions of Mechanize no longer use Hpricot by default
    # but have an attribute we can set to use it
    begin
      WWW::Mechanize.html_parser = Hpricot
    rescue NoMethodError
      # must be using an older version of Mechanize that doesn't
      # have the html_parser attribute - just ignore it since 
      # this older version will use Hpricot anyway
    end
    

    By using the rescue block you ensure that if they do have an older version of mechanize, it won't barf on the nonexistent html_parser attribute. (Otherwise you need to make your code dependent on the latest version of Mechanize)

    Also in the latest version, WWW::Mechanize::List was deprecated. Don't ask me why because it totally breaks backward compatibility for statements like

    page.forms.name('form1').first
    

    which used to be a common idiom that worked because Page#forms returned a mechanize List which had a "name" method. Now it returns a simple array of Forms.

    I found this out the hard way, but your usage will work because you're using find which is a method of array.

    But a better method for finding the first form with a given name is Page#form so your form finding line becomes

    form = page.form('form1')
    

    this method works with old an new versions.

Force javadoc to ignore an annotation

Hi all,

I'm trying to document an annotated interface and include a sample of how it's used in the javadoc. e.g.

/**
 * Here's an example usage:
 *
 * <PRE>
 * @IFaceAnnotation(value="")
 * public interface IFace {
 *
 *     @MethodAnnotation("")
 *     public String Method();
 * }
 * </PRE>
 */

However, Javadoc treats my annotations as javadoc instructions (like @param etc.) and as a result only prints:

Here's an example usage:

In the generated documentation. The only way i've been able to stop this is by adding an extra char before the annotation e.g.

/**
 * Here's an example usage:
 *
 * <PRE>
 * \@IFaceAnnotation(value="")
 * public interface IFace {
 *
 *     \@MethodAnnotation("")
 *     public String Method();
 * }
 * </PRE>
 */

but this looks a bit messy.

Just wondered if anyone had any suggestions, Thanks.

From stackoverflow
  • You can use '&#064;' instead of the @, but thats even more ugly.

  • Have you tried wrapping it in the {@code} notation?

How do you reference a C# project from a C++/CLi project in same solution

I have two projects in a solution, one is a C# library and the other is a C++/CLI library.

I have added a reference in the C++/CLI project using the references menu to the c# library. I then add the

#using <assembly.name.dll>

and try to reference the assembly with

using namespace namspace.subnamespace;

But i get the error that the assembly.name.dll cannot be found. I have tried matching the case and all lower case for the assembly name but to not avail. Amazingly there is not reference anywhere on the internet about how to reference assemblies you have created yourself.

What is the correct was to do this and if i'm doing it right, what course should i take to diagnose this.

From stackoverflow
  • I dont think you need the #using bit if you included a reference.

  • You need to add path to your C# assembly to C/C++ > General > Resolve #using References

When to close NSOutputStream?

I want to send the data of a UIImage to the server through a socket, so I:

a) open NSOutputStream


- (IBAction)send:(id)sender {
    NSURL *website = [NSURL URLWithString:str_IP];
    NSHost *host = [NSHost hostWithName:[website host]];
    [NSStream getStreamsToHost:host port:1100 inputStream:nil outputStream:&oStream];
    [oStream retain];
    [oStream setDelegate:self];
    [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [oStream open];
}

b) write data to oStream when space is available


- (void) stream: (NSStream *) stream handleEvent: (NSStreamEvent) eventCode
{
switch(eventCode)
    {
    case NSStreamEventHasSpaceAvailable:
    {
         if(stream == oStream)
         {
              NSData *data = UIImageJPEGRepresentation(drawImage.image, 90);
              //Convert from host to network endianness
              uint32_t length = (uint32_t)htonl([data length]);

              [oStream write:(uint8_t *)&length maxLength:4];
              [oStream write:[data bytes] maxLength:length];
         }
    }
    break;
}

The problem is that the data keeps writing to the oSream again and again. How to stop it when all the data is sent?

I send the length of the data before the Image data in order to let the server know when it reaches the end. Do I have to change the code in the server side to close the socket when it reaches the end? And where can I add [oStream close] to close the oStream in the client side?

From stackoverflow
  • The problem is that the data keeps writing to the oSream again and again. How to stop it when all the data is sent?

    See, this is the danger of thinking in the passive voice. Reword the question in the active voice:

    The problem is that the data keeps writing to the oSream again and again. How to stop it when I have sent all the data?

    And you have almost answered your own question.

    A large part of the problem is your HasSpaceAvailable handler. Here's what you're doing:

    1. Creating a complete JPEG representation of the image (every time)
    2. Sending the length of the representation (every time)
    3. Sending the first portion of the representation (every time)

    These are three problems and you need to solve all three.

    1. Create the JPEG representation once.
    2. Send the length of the representation only once.
    3. Keep track of what you have already sent and only send the first part of what you haven't.

    To do all three, put the length into an NSMutableData and append the JPEG representation to it. Then, retain this new data object, and have additional instance variables for the bytes pointer and the length remaining. You'll do all this before you get to the HasSpaceAvailable state.

    Then, when you do get to HasSpaceAvailable, don't separately send the length, because you've put it into the data object. You need only send the bytes from your pointer instance variable with the length remaining as the max length. After you check that the number of bytes sent was not 0 or -1 (see the documentation), add it to the pointer and subtract it from the length remaining.

    When the length remaining reaches zero, you have sent everything. Assuming you don't want to follow the JPEG data up with something, you can then close the stream.

Generic error when trying to save data

Hi all, we have just experienced a weird error on our applications connecting to a clustered Sql Server 2000: both our .NET applications (ADO.NET) and C++ (ADO) application get an error which we cannot explain. All the applications can connect to the database, can read data from it but cannot write data on it, receiving a "Generic network error" (I've translated from the Italian message). After several trials, we tried to switch the services from one node to the other, and this seems to have solved the problem. Still no one is able to figure out what happened and why; is there anybody who is able to explain to me? Thanks in advance Marco


EDIT: Just in case it happens to someone else: we found out that the computer didn't have the last version of MDAC (2.8 SP1). It's very likely that the customer reinstalled the computer and didn't update Windows: when we ran Windows Update, the problem magically (from the customer point of view...) was fixed. We don't know exactly which version of MDAC was installed, but could have been 2.6 or less, since I know our applications have problems with older versions of MDAC.

From stackoverflow
  • Applied any updates recently?

    I have seen something similar on later versions of SQLServer so I would have a look at the security access to the server etc as I don't think they all replicate from system to system.

    Turro : There SHOULD NOT have been any update lately, but I will check it out. Maybe I misunderstand your kind reply, but I already checked most common access issues (such as permissions), usng QueryAnalyzer to connect to the db with the same user/pwd and I succeeded.

Viewing a database over Collections, ORM Lists...

I've been researching to find out how and what to use to get say the name's of the fields in a class, then to invoke that class and get the properties of the class, as in the field values. Give you an example, Say if I one to get one value from one record from one table, I would create an object of that class as in;

DBTable<cars> cartable = new DBTable<cars>(1) //passing 1 is a dataset number
cartable.GetLastRec(); OR cartable.Attributes.Key.carIdx // record index
cartable.GetKeyRec();
// Now I print the value
Console.WriteLine("Car number: " + cartable.Attributes.Data.number;

It's easy to get one record, it's like an Object Orientated Database but not sure if it isn't, I don't have any knowledge of the database system, just that the classes are used to talk to a DLL file and pass some numbers.

so far I've been testing with collections, inheriting, ORM, and nothing seams to be able to describe the very simple process going on, Even dynamic invoking objects and iterating over it's attributes What I hope do is; Datagridview => Table Classes => DLL entry points => Database

If anyone has had the same challenge or maybe I have the wrong approach here, but completely lost at this stage, Any Idea's welcome Thanks in Advance

btw: I'm using VS2005, .NET 2.0

From stackoverflow
  • The only way to do this is by providing your own PropertyDescriptorCollection.

    A search here or on Google, should point you in the correct direction.

Timeout while Internet Explorer busy

During execution of tests on ccnet server. Some of the tests fails saying Timeout while Internet Explorer busy and hangs the system and at the end show the old results-xml file in nunit results even I am using a clean build.

From stackoverflow
  • I'm having the same issue with WatiN-tests. I can't write text to a TextField. I have no idea for how to solve it yet.

    Update: I downgraded from IE8 to IE6 and ran the WatiN-tests again without the timeout issue.

    egapotz : @Ola I am having the same issue, but I haven't downgraded IE again

MVC Views | How do *YOU* handle IsAuthenticated Scenarios?

Typically, in sites that allow membership, you want to offer your users a bit of data that is only visible when they're logged in.

For my site, if the logged in user is the data owner, I want to offer some tools to let them manage the data.

My question is this. Do you split this duty between two different views? One view that gets loaded for "regular" users, the other that gets loaded for "owner" users. The view that the regular users see simply shows the data. The owner sees the data and some tools to manage it.

Or, do you perform checks in a single view and hide/show blocks within it (similar to what you would have done in regular ASP.NET)?

It's probably by preference, but are there any technical reasons for splitting the duty between two views vs a single view?

From stackoverflow
  • Personally I would go for the single view option. That way you don't have to repeat code that'll appear in both views.

    Technically (or in regards to the MVC pattern) I can't think of any reasons to split it up.

    Chad : The only reasons I would think to split it up would be to remove any logic code from the view, or if you needed to split the work up to different designers.
  • I would also go for the single view option as well. Would provide specific properties on your viewdata to indicate what to do.

    <% if (Model.IsOwner) { %>
        //Html for owner
    <% } %>
    
    Chad : That is exactly what I do in my views, literally. IsOwner is the exact property I pass to the view as well. :D
  • I would be inclined to split the view into multiples as ideally you want to avoid conditional logic in a view (read: ideally).

    If you find that would cause some duplication between your views, then it's likely that you could move that duplicated content into shared partials.

Using CSV as a mutable database?

Yes, this is as stupid a situation as it sounds like. Due to some extremely annoying hosting restrictions and unresponsive tech support, I have to use a CSV file as a database.

While I can use MySQL with PHP, I can't use it with the Python backend of my program because of install issues with the host. I can't use SQLite with PHP because of more install issues, but can use it as it's a Python builtin.

Anyways, now, the question: is it possible to update values SQL-style in a CSV database? Or should I keep on calling the help desk?

From stackoverflow
  • I'd keep calling help desk. You don't want to use CSV for data if it's relational at all. It's going to be nightmare.

  • Keep calling on the help desk.

    While you can use a CSV as a database, it's generally a bad idea. You would have to implement you own locking, searching, updating, and be very careful with how you write it out to make sure that it isn't erased in case of a power outage or other abnormal shutdown. There will be no transactions, no query language unless you write your own, etc.

  • Don't walk, run to get a new host immediately. If your host won't even get you the most basic of free databases, it's time for a change. There are many fish in the sea.

    At the very least I'd recommend an xml data store rather than a csv. My blog uses an xml data provider and I haven't had any issues with performance at all.

    ojblass : +1 resovle this the right way.
  • I couldn't imagine this ever being a good idea. The current mess I've inherited writes vital billing information to CSV and updates it after projects are complete. It runs horribly and thousands of dollars are missed a month. For the current restrictions that you have, I'd consider finding better hosting.

  • Take a look at this: http://www.netpromi.com/kirbybase_python.html

  • I agree. Tell them that 5 random strangers agree that you being forced into a corner to use CSV is absurd and unacceptable.

  • You can probably used sqlite3 for more real database. It's hard to imagine hosting that won't allow you to install it as a python module.

    Don't even think of using CSV, your data will be corrupted and lost faster than you say "s#&t"

  • If I understand you correctly: you need to access the same database from both python and php, and you're screwed because you can only use mysql from php, and only sqlite from python?

    Could you further explain this? Maybe you could use xml-rpc or plain http requests with xml/json/... to get the php program to communicate with the python program (or the other way around?), so that only one of them directly accesses the db.

    If this is not the case, I'm not really sure what the problem.

  • "Anyways, now, the question: is it possible to update values SQL-style in a CSV database?"

    Technically, it's possible. However, it can be hard.

    If both PHP and Python are writing the file, you'll need to use OS-level locking to assure that they don't overwrite each other. Each part of your system will have to lock the file, rewrite it from scratch with all the updates, and unlock the file.

    This means that PHP and Python must load the entire file into memory before rewriting it.

    There are a couple of ways to handle the OS locking.

    1. Use the same file and actually use some OS lock module. Both processes have the file open at all times.

    2. Write to a temp file and do a rename. This means each program must open and read the file for each transaction. Very safe and reliable. A little slow.

    Or.

    You can rearchitect it so that only Python writes the file. The front-end reads the file when it changes, and drops off little transaction files to create a work queue for Python. In this case, you don't have multiple writers -- you have one reader and one writer -- and life is much, much simpler.

  • It's technically possible. For example, Perl has DBD::CSV that provides a driver that runs SQL queries on the CSV file.

    That being said, why not run off a SQLite database on your server?

  • What about postgresql? I've found that quite nice to work with, and python supports it well.

    But I really would look for another provider unless it's really not an option.

  • Disagreeing with the noble colleagues, I often use DBD::CSV from Perl. There are good reasons to do it. Foremost is data update made simple using a spreadsheet. As a bonus, since I am using SQL queries, the application can be easily upgraded to a real database engine. Bear in mind these were extremely small database in a single user application.

    So rephrasing the question: Is there a python module equivalent to Perl's DBD:CSV

How to write NSArray to NSOutputStream?

I want to send out an NSArray, so I have to write it to an NSOutputStream first. The method should be :

- (NSInteger)write:(const uint8_t *)buffer maxLength:(NSUInteger)length

I can convert the array's pointer to uint8 _ t using :

(uint8_t *)arr

But how to get the length of bytes of the array? Do I have to save the array to a file and read it out as NSData?

From stackoverflow
  • I can convert the array's pointer to uint8 _ t using :

    (uint8_t *)arr
    

    That's just a cast; it doesn't actually convert the array to a sequence of bytes. Even if you sent the private storage of the array over the wire, the contents of the array are just memory addresses to other objects. The memory addresses in your process are almost certainly not the same in the receiving process—and that's assuming that the receiving process is running Cocoa and would be expecting an NSArray!

    You need to serialize the array's contents to some external representation that the receiver will be able to handle. You can do that by converting to a plist, creating an NSXMLDocument and getting its data, or assembling a custom-format representation by hand—but not with a cast alone.

    But how to get the length of bytes of the array?

    The array isn't a series of bytes; it's an object. As such, it doesn't have length, only (as an array) the count of objects in it. You need a series of bytes before you can get the series's length.

    Do I have to save the array to a file and read it out as NSData?

    You need to get an external representation of the array, preferably in an NSData object. Telling it to write (a plist of) itself to a file and reading the file back in is one way, but there are much better ways, which I listed above.

Best way to secure data PHP + MYSQL

I'm building an app that will store some of our clients details, things like usernames / passwords, information that we need to remember and keep secure.

What's the best method for storing this information securely?

From stackoverflow
  • Devlounge have a very good article on security.

    http://www.devlounge.net/code/php-security

  • As far as passwords go you should store a hash of the password. Whenever you authenticate the user, you hash their inputted password and compare the result with what you've stored. This way you aren't storing the actual password.

  • Such an open-ended question with not a lot of detail to go on. I'd suggest reading Chris Shiflett's excellent "Essential PHP Security" before you go any further. It's short, to the point and very practical.

    There's also a reasonable amount of the advice available from the book's website too at http://phpsecurity.org/

  • Using a PHP framework for security

    If you want to get PHP security setup quickly without doing a load of research, a PHP framework would be a good idea.

    I am a fan of CodeIgniter but other options include CakePHP and Zend.

    Using a framework for security will mean you get a tried and tested method straight away, however there may be some time and effort needed to learn the framework.

    A total list of PHP frameworks can be found on wikipedia.

    Jacco : Using a framework will not prevent you from making insecure applications. You DO need to know about security best practices. Frameworks are no substitution for secure coding. Not educating yourself about security because you use a framework is a very ignorant way of digging your own security hole.
    Jon Winstanley : Fair enough. A framework is not a silver bullet. However, the built-in security classes which can clean up your data and help you avoid many XSS exploits can be very useful to someone with little experience.
    Jacco : They certainly can help you.
  • Pretty simple actually. Set up a quick MySQL database, and a user table. In that user table, store the usernames in a column and a hashed version of the password in another column.

    As added security, I like to generate a random 8 character string and store that as well in each row - I call that column the "Keycode". When the user signs in with a correct username / password, I store their authentication in session variables AS WELL as the matching "Keycode".

    That way, the session authentication can not only look for the right username / password, but quickly query the db, and check to see if the "Keycode" stored in the session variable is the same as the keycode in the row.

    It works well because not even the user knows their keycode.

  • johnnietheblack

    The user doesn't know their hash key either. You could have just as easily used that.

send message to a window handle

Hi,

I'm running an exe through which I get a handle of a control in another exe. Now what I want to do is send messages to the particular handle from my exe.

From stackoverflow
  • Here is the link which is same as above question but it is sending a message to Chrome window from C# application

  • Hello,

    You need to import the function using:

    [DllImport("user32.dll")]
    public static extern int SendMessage(
                      int hWnd,      // handle to destination window
                      uint Msg,       // message
                      long wParam,  // first message parameter
                      long lParam   // second message parameter
                      );
    

    and define the message that you want to send like:

    public const int <WM_YOURMESSAGE> = <yourvalue>;
    

    and then call SendMessage like any other function.

MySQL mysql_tzinfo_to_sql program

Hi,

I am using MySQL 5.0.51b on microsoft windows xp. I am trying to load data from zoneinfo files(generated by library downloaded from here) to database tables as described here.

Now i am not able to find where would i get this "mysql_tzinfo_to_sql" program for windows. I tried executing it on mysql command line client but no success. On linux you can directly execute this command on the shell.

Any help is appreciated.

From stackoverflow
  • For Windows, MySQL supplies an already loaded database for you to download and stick in your data directory: http://dev.mysql.com/downloads/timezones.html

    Copied from the user comments on the MySQl docs:

    Posted by Jyotsna Channagiri on November 20 2008 6:28pm

    Hi,

    I thought this information will helps somebody who are looking for changing mysql timezone.

    The steps are:

    1. Download the timezone table structure and data from http://dev.mysql.com/downloads/timezones.html

    2. Copy and paste the data in your Mysql/data/mysql folder

    3. Restart your mysql server.

    4. mysql> SET GLOBAL time_zone = 'America/Toronto';

    5. mysql> SET SESSION time_zone = 'America/Toronto';

    6. Check SELECT @ @global.time_zone , @ @session.time_zone ; It should give you the time zone you set just before.

    Comment:

    Yes, but the tables provided by MySQL are outdated (generated by 2006p version of D olson's timezone library). I need the latest timezones data, hence i downloaded the latest library and generated the binaries. Now i need a way to load these tables in mysql.But i don't know how to do it on windows.

    Ah, I see. Then you're going to need to do one of two things. 1) get the tool that does this and compile it (or whatever) on Windows. If you're lucky, it's a perl script.

    2) fill the database on linux, then copy it to Windows. [This guy][http://it-idiot.einsamsoldat.net/2008/01/moving-mysql-database-from-windows-to-linux-redhat/comment-page-1/2] says it can be done, at least for MyIsam.

Ruby on Rails Content Management Systems?

Is there a viable open source Ruby on Rails content management system out there?

I need a CMS with the ability to manage structured content, content relationships, classification (structured taxonomy and free tagging) and simple publishing workflow. I'd prefer the content ultimately be persisted as XML. Also content needs to be abstracted away from the page(s) it's published.

Thanks, Mike

From stackoverflow
  • You could try RadiantCMS.

  • Other choices are Mephisto and others listed at InfoQ. I've done fine by building on top of the Goldberg plugin, but that's because I anticipated writing a custom code with respect to classification of content.

    As you know, any CMS will have competing and variable requirements. That usually explains why everyone and their uncle has their own CMS.

  • I've heard good things about Comatose. If I recall correctly, you're not given a complete app in which you are given a few hooks where you add your customizations. Rather, you specify a few spots in your Rails app where you need CMS functionality, and everywhere else you keep complete control over your app.

    If you want a turnkey solution, I'll have to concur with others. Either RadiantCMS, Mephisto or Typo may be good choices.

    If worse comes to worse, check out the comparison on Wikipedia. It probably has much more CMSes than you ever wanted to hear about, as it's not Ruby specific :-)

  • I have to disagree with the suggestion of RadiantCMS. While it's a good CMS for some applications (and we use it at work), I don't think it meets the requirements specified (based on my experience using it, which admittedly is not all that extensive):

    • there's no classification system;
    • the publishing workflow is too simplistic -- i.e. a page is draft or published, and there's no approval workflow;
    • the content is plain HTML or one of a few markup languages, not XML;
    • you can abstract content away from published pages with snippets, but that quickly becomes unmanageable.

    There may be a suitable Ruby on Rails CMS for your requirements, but I don't think that RadiantCMS is it.

  • I have to agree with TimB. I implemented RadiantCMS when my company was first getting started and it worked great. However, it is focused on being simple to setup and use and is not a full featured CMS with workflow and such.

    We actually moved away from Radiant several months ago and are now very happy using SilverStripe. SS would do most if not all of what you requested, unfortunately it is based on PHP and not Ruby so I'm not sure how much help that is.

    Later...
    Richard

  • I have tried RadiantCMS and having worked with Drupal, I think RadiantCMS is nowhere near being a complete Content Management System. I have also been looking for a CMS like Drupal in RoR. Take a look at this: http://joshhuckabee.com/drupal-and-ruby-rails

  • There is also a plugin called Station. I have not used it yet, but it was featured on RubyInside.

  • Comatose is pretty good, and it integrates pretty unobtrusively into existing sites. The best thing about Comatose is that you can define your own text filters. For example, to use HAML in your pages, just drop this into an initializer:

    # HAML Text Filter
    TextFilters.define :haml, "HAML" do
      require 'haml'
      def render_text(text)
        engine = Haml::Engine.new(text)
        engine.render 
      end
    end
    
    Ryan Heneise : I should mention one caveat that HAML would give access to your Rails instance and your models. Depending on your site, this might be a security risk.
  • We develop an Open Source Item & Content Management system that has pretty good taxonomy(unlimited category descendants/depth). It's designed to list different items(these items can be pages, blog posts, vendors, etc.). Not sure if this will suit your needs, but you can try out a demo at:

    http://hulihanapplications.com/projects/opal

    Hope this helps.

SQL Server Prevent Scripts Being Run on the Wrong Instance...

This is less of a programming question and more of a suggestions for tools one :-)

I'm looking for a way to prevent scripts being accidentally run on the wrong sql server instance, ie so you don't run that script for clearing down customers in your development environment on the live/production environment.

What I'm basically after is a pluging for Enterprise Manager (or a different app for managing a sql server instance), that would allow me to define a list of connection details for SQL server instances, so that when the window is connected to a LIVE environment that it makes it quite clear, either by coloring the tab red, or by poping up a message box saying "This is connected to XXXX instance. Are you sure"

Asside form being really careful, does anyone have any ideas for tools/plugins that will do this or anything remotely simular?

Thanks for any help

From stackoverflow
  • You can set different (limited) access right on you live instance for the user you normally use. And then have a different user name for doing any serious stuff on the live system.

  • All my scripts start with this :

    if exists (select 1 from dbo.environment where value in('production', 'qa'))
      return
    

    Of course this means that I have an environment table and have 'production' , 'development' , 'qa' etc. in it depending on where it is hosted.

    Paul Suart : +1 good suggestion
    kristof : +1 Looks like a good idea. you could even use something like say IF not EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[present_only_in_test]') ) return. That way you would not need to modify the life system and only add present_only_in_test object in test/development env
    kristof : Seems that is not completely safe though, see answer by Andomar and comments about GO
  • This SQL code checks if you're on the right server:

    if @@servername <> 'testserver'
      RAISERROR ( 'Wrong server', 16, 1 );
    

    An error (or return for that matter), will prevent execution until the next GO statement. For example, the following will still print hello world, and delete the user table:

    RAISERROR ( 'Wrong server', 16, 1 );
    go
    drop table users
    print 'Hello world!'
    go
    
    kristof : Good point about the impact of GO
  • here you go: http://www.ssmstoolspack.com/

    this free SSMS addin provides windows coloring per server.

Need Information on what 'interface' actually is in ASP.NET...

I am having a 'learning' day and am delving into an ASP.NET solution to try and learn more advanced techniques for building apps (I'm still in novice stage so please can you answer as if I am stupid :)... lol).

And I have a couple of questions...

1.) Looking through the code I see this method

public interface Somthing()

I have never seen 'interface' before? What is it used for? And could you point me in the right direction to find out more about using it

2.) I keep seeing things like this in the comments

<see cref="CoComment"/>

I'm not sure what this means?

Any help greatly appreciated

From stackoverflow
  • I don't know of an interface modifier on a method, and have just Googled and can't see anything.

    Could it be a badly cased (and named!) return type?

    ie. should it have been:

    public Interface Something();
    

    as in it is returning an object of type Interface?

  • You can think of an interface as an abstract class that only provides constant and method prototype declarations. Classes can then implement interfaces in the same way they can inherit from other classes. When implementing an interface, a class must implement all methods defined in the interface:

    public interface MyInterface
    {
        void doSomething();
    }
    
    public class MyClass : MyInterface
    {
        public void doSomething()
        {
        }
    }
    
    MyInterface obj = new MyClass();
    obj.doSomething();
    

    One of the nice things about interfaces is that they support multiple inheritance, unlike classes in .NET. So you can implement several interfaces and interfaces can extend several other interfaces.

    The naming convention for interfaces in .NET is 'ISomething', so you can guess that a symbol is an interface if it starts with an 'I'. Moreover, many interfaces have names that end on '-able', like 'IDisposable' or 'ICloneable'.

    The concept is the same as in Java, you can read more about it on Wikipedia.

  • Sorry, missed your edit regarding comments.

    You can create XML documentation using the /// comment token.

    So you can have:

    /// <summary>
    /// Does something
    /// </summary>
    /// <see cref="something" />
    public void DoSomething()
    {
    }
    

    This can then be used to produce API documentation, much like MSDN format. It also comes through in Visual Studio Intellisense tooltips which I find very useful.

  • Here's the help for cref:

    http://msdn.microsoft.com/en-us/library/cc837134.aspx

  • 1) interface see: http://msdn.microsoft.com/en-us/library/87d83y5b(VS.80).aspx

    2) <see ...? XML Documentation markup see: http://msdn.microsoft.com/en-us/library/5ast78ax(VS.71).aspx

Is there any free to use XSD (DTD) for Rx documents (drug prescription)

I'd like to explore and possibly use (reuse) open XML formats/schemes (DTD/XSD) for drug (medication) prescription documents (Rx) issued by medical doctors and later processed by licenced pharmacists and health insurance companies.

Is there any such freely XSD available and what I have to take care when considering and incorporating into health-care information system?

What international standards (ISO, ISO/IEC, EN) should be used to acheeve maximum level of interoperability?

From stackoverflow
  • please provide more information about what you want to achieve

Problem with PNG image on top of an image in CSS?

I am using a jQuery content rotator and I want to place a PNG image on top of a image and on top of that text.

This is how my rotator looks like in HTML:

      <div id="testimonials">
    <div class="slides">

    <div class = "testimonialContainer">
    <div class ="leesmeer"> <a href ="http://site/link"><img src ="http://site/afbeeldingen/test.jpg" ><div class="caption">LORUM IPSUM DOLOR SIT AMET </div></a></div>
    </div>

    <div class = "testimonialContainer">
    <p class = "testimonial"> 2 </p>
    <div class ="leesmeer"> <a href ="http://site/link"><img src ="http://site/afbeeldingen/test.jpg" ></a></div>
    </div>

</div>
</div>

Here is the CSS:

.testimonialContainer {height: 123px}

    #testimonials{
    width: 210px;
    height: 125px;
    }

    .slides div{
    width: 210px;
    xheight:  25px;
    xpadding: 5px;

    .slides div.caption{
        background-image: url(../images/h_contentrotator_zwart.png);
        /*background-color:#000000;
        filter:alpha(opacity=60);
        -moz-opacity: 0.6;
        opacity: 0.6;*/
        color: #fff;
        width: 210px;
        height: 41px;
        position: relative;
        top: -24px;
        padding: 2px 20px 2px 10px;
        zbehavior: url("iepngfix.htc")
    }

The problem is that the PNG image doesn't appear and also the text doesn't appear.

Can someone help me out?

From stackoverflow
  • You need to add a dot (.) at last selector:

    .slides div.caption{
    

    Right now it's not there, but should be.

    If the problem is not solved after adding a dot then be more specific. Change

    .slides div.caption
    

    to this:

    #testimonials a div.caption
    

    And remove Z from behaviour.

    And even if it is not solved then give me a link of jQuery script homepage.

    sanders : thanks. I added the dot. But it didn't solve the problem ;-)
  • I did change it to this:

    .testimonialContainer {height: 123px}
    
    #testimonials{
    width: 210px;
    height: 125px;
    }
    
    .slides div{
        width: 210px;
        xheight:  25px;
        xpadding: 5px;
    
        /*.slides div.caption{*/
        #testimonials a div.caption{
            background-image: url(../images/h_contentrotator_zwart.png);
            /*background-color:#000000;
            filter:alpha(opacity=60);
            -moz-opacity: 0.6;
            opacity: 0.6;*/
            color: #fff;
            width: 210px;
            height: 41px;
            position: relative;
            top: -24px;
            padding: 2px 20px 2px 10px;
            behavior: url("iepngfix.htc")
    
    }
    

    But it still doesn't save the problem.

  • Make sure that you have the right path to the background image. If the style is in the <head> of the HTML page, then the path will be relative to the HTML page. If the style is within an external stylesheet, then the path will be relative to the file location of the stylesheet.

    You also might want to get it working without the Internet Explorer 6 PNG fixes first, and then add the fixes back in after you know the rest of the code is correct.