Sunday, February 13, 2011

Propagate Permissions to Javascript

I'm debating the best way to propagate fairly complex permissions from the server to an AJAX application, and I'm not sure the best approach to take.

Essentially, I want my permissions to be defined so I can request a whole set of permissions in one shot, and adjust the UI as appropriate (the UI changes can be as low level as disabling certain context menu items). Of course, I still need to enforce the permissions server side.

So, I was wondering if anyone has any suggestions for the best way to

-maintain the permissions and use them in server code -have easy access to the permissions in javascript -not have to make a round-trip request to the server for each individual permission

Thoughts?

-Jerod

  • Encode them as JSON.

    From Diodeus
  • If you transmit the permission structure to the client as a JSON object (or XML, if you prefer), you can manipulate that object with the client-side code, and send it back to the server, which can do whatever it needs to validate the data and persist it.

    From pkaeding
  • I don't necessarily see it as the most "correct" solution, but would it be possible to keep all the permission stuff on the server side, and just serve the updated UI rather than some kind of JSON permissions system?

    You'd have to make the decision based on how busy and intensive your app expects to be, but definitely a decision worth making either way

    CMPalmer : That would be the ASP.Net preferred approach, but at a certain granularity on any type system, there are advantages to having client side control as well.
    From Gareth
  • If you have a clear set of permissions, like a "user level" or "user type", you could just pass the value down in a hidden field and access the value through the DOM. You could still do this if your permissions were more granular, but you would either have a lot of hidden fields or you would have to encode the information into XML or JSON or some other format.

    You might set them as bit flags so that you could OR a single numeric value with a mask to see if the user had the permission for a specific activity. That would be very flexible and as long as you don't have more than 32 or so specific "rights", that would allow for any permutation of those rights in a very small package (basically an unsigned int).

    For example:

    0x00000001 //edit permission
    0x00000002 //create new thing permission
    0x00000004 //delete things permission
    0x00000008 //view hidden things permission
       .
       .
       .
    0x80000000 //total control of the server and everyone logged in
    

    Then a user with a permission of 0x000007 could edit, create, and delete, but nothing else.

    In either case, I think you're on the right track - make the request once per page invocation, store the permissions in a global JavaScript data structure, and go from there. AJAX is nice, but you don't want to query the server for every specific permission all over your page. You would do it once on the page load, set up the presentation of your page and save the value in a global variable, then reference the permission(s) locally for event functions.

    From CMPalmer

Dictionary<string, MyObject> or List<MyObject> with C# 3.5?

I often use Dictionary in C#2.0 with the first key as string that was containing a unique identifier.

I am learning C#3.0+ and it seems that I can now simply use a List and simply do LINQ on that object to get the specific object (with the .where()).

So, if I understand well, the Dictionary class has lost its purpose?

  • no, a dictionary is still more efficient for getting things back out given a key.

    a list you still have to iterate through the list to find what you want. A dictionary does a lookup.

  • IMHO the Dictionary approach will be MUCH faster than LINQ, so if you have an array with a lot of items, you should rather use Dictionary.

  • If you just have a List, then doing an LINQ select will scan through every item in the list comparing it against the one you are looking for.

    The Dictionary however computes a hash code of the string you are looking for (returned by the GetHashCode method). This value is then used to look up the string more efficiently. For more info on how this works see Wikipedia.

    If you have more than a few strings, the initial (List) method will start to get painfully slow.

  • Dictionary is implemented as a hashtable. Thus it should give constant time access for lookups. List is implemented as a dynamic array, giving you linear time access.

    Based on the underlying data structures, the Dictionary should still give you better performance.

    MSDN docs on Dictionary

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

    and List

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

    From biozinc

Can anyone help me convert this ANTLR 2.0 grammar file to ANTLR 3.0 syntax?

I've converted the 'easy' parts (fragment, @header and @member declerations etc.), but since I'm new to Antlr I have a really hard time converting the Tree statements etc.

I use the following migration guide.

The grammar file can be found here....

Below you can find some examples where I run into problems:

For instance, I have problems with:

n3Directive0!:
                d:AT_PREFIX ns:nsprefix u:uriref
                {directive(#d, #ns, #u);}
                ;

or

propertyList![AST subj]
        : NAME_OP! anonnode[subj] propertyList[subj]
        | propValue[subj] (SEMI propertyList[subj])?
        |               // void : allows for [ :a :b ] and empty list "; .".
        ;

propValue [AST subj]
        :  v1:verb objectList[subj, #v1]
                // Reverse the subject and object
        |  v2:verbReverse subjectList[subj, #v2]
        ;

subjectList![AST oldSub, AST prop]
        : obj:item { emitQuad(#obj, prop, oldSub) ; }
                (COMMA subjectList[oldSub, prop])? ;

objectList! [AST subj, AST prop]
        : obj:item { emitQuad(subj,prop,#obj) ; }
                (COMMA objectList[subj, prop])?
    | // Allows for empty list ", ."
    ;
  • n3Directive0!:
                    d=AT_PREFIX ns=nsprefix u=uriref
                    {directive($d, $ns, $u);}
                    ;
    
    • You have to use '=' for assignments.
    • Tokens can then be used as '$tokenname.getText()', ...
    • Rule results can then be used in your code as 'rulename.result'
    • If you have rules having declared result names, you have to use these names iso.
      'result'.

SEO google keyword position tools?

Hi guys,

I want to check our google postions for several keywords every day and make a note in a spreadseet. At the moment, we have a student doing it but it's a rubbish job and it doesn't seem fair on them!

Are there any tools available to automate this process? I have tried rankchecker by seobook.com, but although that should be exactly what im looking for when i set scheduled tasks in that, it doesnt work.

Any tips would be appreciated, thanks!

peter

EDIT: Liam has suggested a Python script to do this, which unfortunately isnt something I'm very familiar with! If anyone knows of a good tutorial or something to help us with this, that would be brilliant.

Update:

Found a php script at seoscript.net which looks like a step in the right direction.

But I cant get it to work! I get this error.

Anyone more knowledgabe than me know how to fix that? I have PEAR installed.

thanks again,

Peter

  • have the student come up with an automatic way of doing this. Sounds like a good exercise for them.

    Bill the Lizard : Tomorrow the student will ask the same question, and we can link to this answer, closing his question as "Exact Duplicate". :)
    From Robert
  • I use a Python script to check the number of results for a set of searches each day and log the results. Then I run another script that builds a spreadsheet from the log files. Checking your position in the results page would be only a little more complex.

    Liam : I hope to share it once I have cleaned it up a bit.
    Peterl86 : thanks liam, that sounds like it could really help.
    From Liam
  • I think it is probably ALOT easier to let the student do it the old fashioned way :p

    From DrG
  • I'm not sure how often it updates, but Google Webmaster Tools shows your rank for the top 20 queries in which your site appeared.

    Otherwise, writing a script or a small program in your favorite programming language should do the trick, as was already suggested.

  • Don't forget rankings vary data center to data center, and are trending more towards being tweaked towards your specific search and browsing history.

    Not to sell you anything, but what you should be looking for is more a suite of site quality metrics and less simple ranking metrics, the outputs of which are increasingly questionable.

    If I were you, I would look into getting some professional help from an SEM firm with a strong development team, as they usually have some pretty advanced metrics working under the hood. Otherwise, just remember that content is king: the W3C is pretty clear about which markup has semantic value, and Google capitalizes on this.

  • It's not a PHP script or something but a nice tool to check your rank at google for some keywords (and it's free software): Google Monitor

    Peterl86 : cheers bud, I'll look into this tomorrow and report back!
  • What a coincidence, I created SERF (Search Engine Rank Finder) for this very purpose. Works with Google and MSN/Live; but I lost interest before I implemented Yahoo support. Link comes with source; exe in the bin folder.

    It works by downloading the actual search pages in question and finding any URL with your domain in it. It won't pass Google your cookies, but it will probably connect to the same Google server you do.

    From tsilb

What is the best way to move files from one server to another with PHP?

If I setup a CRON that runs a PHP script that in turn moves a file from one server to another, what would be the best way? Assume I have been given the proper username/password , and the protocol (like SFTP) is only prohibited if the language can't support it. I'm really open to options here -- these are XML files that hold order export and customer export (non-sensitive) information, and the jobs will run daily. There is the potential that one server is Linux and the other is Windows -- both are on different networks.

  • Why not use shell_exec and scp?

    <?php
        $output = shell_exec('scp file1.txt dvader@deathstar.com:somedir');
        echo "<pre>$output</pre>";
    ?>
    
    Bob Fanger : scp is a very handy and powerful tool, but may require some configuration: http://www.google.com/search?q=+password-less+SSH+login
    From SoloBold
  • If both servers would be on Linux you could use rsync for any kind of files (php, xml, html, binary, etc). Even if one of them will be Windows there are rsync ports to Windows.

    SoloBold : rsync's good too.
  • Why not try using PHP's FTP functions?

    Then you could do something like:

    // open some file for reading
    $file = 'somefile.txt';
    $fp = fopen($file, 'r');
    
    // set up basic connection
    $conn_id = ftp_connect($ftp_server);
    
    // login with username and password
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
    
    // try to upload $file
    if (ftp_fput($conn_id, $file, $fp, FTP_ASCII)) {
        echo "Successfully uploaded $file\n";
    } else {
        echo "There was a problem while uploading $file\n";
    }
    
    // close the connection and the file handler
    ftp_close($conn_id);
    fclose($fp);
    
    From Stephen

From Child instance call base class method that was overridden

Consider the following code:

Public Class Animal

Public Overridable Function Speak() As String
    Return "Hello"
End Function

End Class

Public Class Dog
    Inherits Animal

    Public Overrides Function Speak() As String
        Return "Ruff"
    End Function

End Class

Dim dog As New Dog
Dim animal As Animal
animal = CType(dog, Animal)
// Want "Hello", getting "Ruff"
animal.Speak()

How can I convert/ctype the instance of Dog to Animal and have Animal.Speak get called?

  • you don't; the subclass's method overrides the superclass's method, by definition of inheritance

    if you want the overridden method to be available, expose it in the subclass, e.g.

    Public Class Dog 
        Inherits Animal
        Public Overrides Function Speak() As String
            Return "Ruff"
        End Function
        Public Function SpeakAsAnimal() As String
            Return MyBase.Speak()
        End Function
    End Class
    

    (untested)

  • I don't think you can.

    The thing is that the object is still a dog. the behavior you're describing (getting "ruff" from the casted object rather than "hello") is standard because you want to be able to use the animal class to let a bunch of different type of animals speak.

    For example, if you had a third class as thus:

    Public Class Cat
        Inherits Animal
    
        Public Overrides Function Speak() As String
            Return "Meow"
        End Function
    End Class
    

    Then you'd be able to access them like thus:

    protected sub Something
        Dim oCat as New Cat
        Dim oDog as New Dog
    
        MakeSpeak(oCat)
        MakeSpeak(oDog)
    End sub
    
    protected sub MakeSpeak(ani as animal)
        Console.WriteLine(ani.Speak())
    end sub
    

    What you're talking about doing basically breaks the inheritance chain. Now, this can be done, by setting up the Speak function to accept a parameter which tells it to return it's base value or not or a separate SPEAK function for the base value, but out of the box, you're not going to get things that behave this way.

    Mike Deck : "Another alternative, is to declare the object as an ANIMAL, and then cast it to a DOG when you need the dog's extended properties." That last part is not true. The declared type of the variable is meaningless when it comes to how a given instance behaves polymorphically.
    Stephen Wrighton : That's true, I was thinking in terms of interfaces.
  • I would ask why you are trying to get this type of behavior. It seems to me that the fact you need to invoke the parent class' implementation of a method is an indication that you have a design flaw somewhere else in the system.

    Bottom line though, as others have stated there is no way to invoke the parent class' implementation given the way you've structured your classes. Now within the Dog class you could call

    MyBase.Speak()
    

    which would invoke the parent class' implementation, but from outside the Dog class there's no way to do it.

    From Mike Deck
  • I think if you drop "Overridable" and change "Overrides" to "New" you'll get what you want.

    Public Class Animal
    
    Public Function Speak() As String
        Return "Hello"
    End Function
    
    End Class
    
    Public Class Dog
        Inherits Animal
    
        Public New Function Speak() As String
            Return "Ruff"
        End Function
    
    End Class
    
    Dim dog As New Dog
    Dim animal As Animal
    dog.Speak() ' should be "Ruff"
    animal = CType(dog, Animal)
    animal.Speak() ' should be "Hello"
    
    From Matt Burke

Best way to reverse-engineer a web service interface from a WSDL file?

I've inherited a WSDL file for a web service on a system that I don't have access to for development and testing.

I need to generate a web service that adheres to that WSDL. The wrapper is .NET, but if there's an easy way to do this with another platform, we might be able to look at that. The production web service is Java-based.

What's the best way to go about doing this?

Note: The inherited wsdl doesn't appear to be compatible with wsdl.exe because it doesn't conform to WS-I Basic Profile v1.1. In particular, the group that passed it on mentioned it uses another standard that the Microsoft tool doesn't support, but they didn't clarify. The error is related to a required 'name' field:

Error: Element Reference '{namespace}/:viewDocumentResponse' declared in
schema type '' from namespace ''
       - the required attribute 'name' is missing

For clarity's sake, I understand that I can easily create a .NET wrapper class from the WSDL file, but that's not what I need. It's like this:

Update: The original web service was created using Axis.

Diagram of system showing unavailable web service and mock web service

  • You may find useful the command line utility wsdl.exe of .NET by using the /serverInterface option. According to the documentation:

    Generates interfaces for server-side implementation of an ASP.NET Web Service. An interface is generated for each binding in the WSDL document(s). The WSDL alone implements the WSDL contract (classes that implement the interface should not include either of the following on the class methods: Web Service attributes or Serialization attributes that change the WSDL contract). Short form is '/si'.

    paulwhit : this helps. although the inherited wsdl doesn't appear to be compatible with it because it doesn't conform to WS-I Basic Profile v1.1.
    Panos : If you are getting just warnings and the code is generated, probably you can use it without problem. Wsdl.exe always tries to generate Basic Profile compliant code unless there is something in WSDL that is not compatible.
    Panos : Moreover, if you build the ws client proxy from visual studio you probably received similar warnings. You can create a client proxy with wsdl.exe and compare it with the one that you have in your project.
    paulwhit : it's a stop error; no code's generated :( I'll add more info to the question.
    From Panos
  • Try mock the wrapper interface using RhinoMocks and StructureMap .

    paulwhit : Does this handle the generation of web services? I can't seem to find that information readily available, and it doesn't look applicable on the surface. I meant "mock" in the generic sense, but maybe it's still applicable?
    From IceHeat
  • Not sure if this will help,

    what i've done recently is:

    • Generate .cs file using the wsdl tool or visual studio
    • I've changed it to be a partial class
    • I've created another partial class, in which all it does is add a line to say that the class implements IWhatEver
    • I've created an interface that is the same as the generated proxy class (Therefore the the proxy fully implements the interface)

    Then i've used a Mocking framework (Moq) in my case, to mock the WebService, I've then used poor mans dependancy injection (pass the mock into a constructor of the class under test) .. which can handle an instance of IWhatever

    Test away..

    Hope that helps

    paulwhit : I tried wsdl.exe and it's not compatible with the inherited wsdl because it doesn't follow the standard. :( After that, I'm not sure I need a mocking framework; couldn't I just change the proxy class URL setting?
    From danswain
  • We are using WSCF - Web Services Contract First tool from Thinktecture to do web service development creating XSD schema first and then generating service interfaces using this tool. It may be useful to generate service interfaces from WSDL but I have not tried this yet myself.

    paulwhit : That's pretty slick. Didn't work, but I can use this for other things! :)
    paulwhit : (Should clarify that it *does* work for my purpose, but I'm still dealing with a borked up WSDL that I think can only work on the original app that generated it (Axis). Trying that next)
    paulwhit : Accepting because I think this would be the best way except in my edge case with a messed up WSDL.
    Vlad N : I'm glad that it helped you somewhat. ;-)
    From Vlad N
  • Yes - you can use WSCF (as per above) to generate server side code. The actual URL can then be overwritten to point to the test URL that you want to use.

    However, this just generates a stub. You still have to code the actual e.g. GetCustomers() method which is somewhat suspect because you have no idea how the actual implementation works.

    Then you can either mock this or create a simple ASP web server to run it.

    From nzpcmad