Friday, November 11, 2011

Castle Monorails with IIS 7

IIS7 ignores the old httpHandler and httpModule tags in the web.config.... we need to add the following under the root


    
     
      
      
      
      



Friday, November 4, 2011

git diff on files

you can compare diff commits on files and branches the same way in git

git diff hash -- path/to/file

Friday, October 14, 2011

Creating a WCF Stand Alone Console App

So I had a problem the other day that really annoyed me. I realized that I couldn't spawn processes directly from IIS. The solution was simple, build a wcf stand alone service that IIS app would call to spawn another process...the result was actually really easy. wcf is almost like remoting, in fact it reminds me a lot of java RMI. It's super ez to setup though...

First you have to provide an interface just like java RMI to serve as a contract between the two processes:

using System.ServiceModel;

[ServiceContract]
    public interface IJSXAdapter
    {
        [OperationContract]
        byte[] GetProcessedImageBytes(string jsxTemplatePath, string[] args);
    }

notice the ServiceContract and the OperationContract attributes

you then of course specify the concrete class (you don't need the attributes in the concrete implementation)


here is the server code:

class Program
        {
            static void Main(string[] args)
            {
                using (ServiceHost host = new ServiceHost(typeof(JSXAdapter), new Uri[]{
                        new Uri("http://localhost:8000"),
                        new Uri("net.pipe://localhost")
                    }))
                {
                    host.AddServiceEndpoint(typeof(IJSXAdapter),
                      new BasicHttpBinding(),
                      "Reverse");

                    host.AddServiceEndpoint(typeof(IJSXAdapter),
                      new NetNamedPipeBinding(),
                      "PipeReverse");

                    host.Open();

                    Console.WriteLine("Service is available. " +
                      "Press  to exit.");
                    Console.ReadLine();

                    host.Close();
                }
            }
        }



That's it for the server. In this example I make not one but two ServiceEndpoints or listeners. One http and another net.pipe. In your client you can connect with either..

Now for the client. You specify the same interface (you could potentially share a dll:


[ServiceContract]
    public interface IJSXAdapter
    {
        [OperationContract]
        byte[] GetProcessedImageBytes(string jsxTemplatePath, string[] args);
    }



and the client code (copied from a method)
 XmlDictionaryReaderQuotas readerQuotas = new XmlDictionaryReaderQuotas();
            readerQuotas.MaxArrayLength = 2147483647;



            BasicHttpBinding httpBinding = new BasicHttpBinding();
            httpBinding.MaxReceivedMessageSize = 2147483647;
            httpBinding.MaxBufferSize = 2147483647;
            httpBinding.ReaderQuotas = readerQuotas;
            ChannelFactory httpFactory = new ChannelFactory(httpBinding,
                                                                                      new EndpointAddress("http://localhost:8000/Reverse"));
            NetNamedPipeBinding pipeBinding = new NetNamedPipeBinding();




            pipeBinding.MaxReceivedMessageSize = 2147483647;
            pipeBinding.MaxBufferSize = 2147483647;            
            pipeBinding.ReaderQuotas = readerQuotas;
            ChannelFactory pipeFactory = new ChannelFactory(pipeBinding,
                                                                                      new EndpointAddress("net.pipe://localhost/PipeReverse"));




            IJSXAdapter httpProxy = httpFactory.CreateChannel();
            IJSXAdapter pipeProxy = pipeFactory.CreateChannel();

            
            
            string[] args = new string[1];
            args[0] = "some string";



            byte[] processedImageBytesFromHttp = httpProxy.GetProcessedImageBytes("some string", args);

            byte[] processedImageBytesFromPipe = pipeProxy.GetProcessedImageBytes("some string", args);
            





Though that looks like a lot most of it is extending the size of how much data can come back. Also keep in mind that this is an example of both end points. in practice you would only connect to one...

Tuesday, August 16, 2011

How to remove jar from grails

How do you prevent a jar from being packaged in a war under grails prod war?

like so...


grails.war.resources = { stagingDir, args ->
delete file: "${stagingDir}/WEB-INF/lib/YOUR-FILE-HERE.jar"
}

Sunday, August 14, 2011

passing JVM arguments to Grails commands (eg run-app)

I ran into a funny situation where I needed to pass some jvm arguments to a grails app. JMX arguments was what I was trying to pass it. I tried a bunch of things but it ended up that I just needed to put them in the GRAILS_OPTS

export GRAILS_OPTS="-Dcom.sun.management.jmxremote"
grails run-app

Saturday, July 30, 2011

mvservice

UPDATE this project has been replaced by https://github.com/asharif/mv-session-mgr

This is finally the cumulation of a couple different projects for mvbase/PICK. It is a stand alone web application (with embedded jetty) that acts as a proxy between the desired mvbase server and the real world ....lol

Currently it provides 2 means of communication RESTful service and RMI

you start the server with java -jar (read the project readme file for command line args https://github.com/asharif/mv-wservice)

for RESTful you look at /mv/sub/{mvsubname}/{barseperatedmvparams} (eg. /mv/sub/hello/A|B)

It also provides JMX for managing the mvconnection beans (configuration is in the readme file)

Embedded Jetty

A lightweight embedded jetty project. Supports JSP 2.0 as well as log4j through slf4j. That's it!

https://github.com/asharif/embdjetty


To use in your project you download repo, compile with

mvn package

this creates a jar file with the good ol' '-with-dependencies'. that file is the server. You need to specify port on java -jar:

-Dport=8080

Now you can drop it in your favorite spring app, compile with the maven assembly plugin and you got a portable web app (well no embedded db but that's another story)

log4j across many dependencies through slf4j

I ran into a stupid problem that made me feel silly. I had a project that depended on a few jars that I myself had made using log4j. Well classloader issues arise if you just add them to classpath and try to run. different loaders load log4j. Hence why it is important to use slf4j and it's binding for log4j. I just added these in the pom and it was all good (scope depends on your project). Also, log4j files go under /src/main/resources in maven....that way they get copied to WEB-INF/classes/



org.slf4j
slf4j-api
1.6.1
runtime


org.slf4j
slf4j-log4j12
1.6.1
runtime


log4j
log4j
1.2.16
runtime

Tuesday, June 28, 2011

New github repo for mv.jdbc

UPDATE: This repo is obsolete it's replaced by https://github.com/asharif/mv-session-mgr

Created a new project to attempt to be connecting to mvBase in a uniform JDBC compliant way. It also handles multiple threads as the original MVSP connectors don't somehow...(yikes!)

Check it out:

https://github.com/asharif/mv.jdbc

Tuesday, June 14, 2011

Connecting to mvBase 3.0 with Java

A couple posts back I went through the basics of PICK (mvBase). I finally got a chance to connect to it using the mvBase 3.0 MVSP with Java. First off we need the mvapi.jar which acts as our jdbc like interface (UPDATE: MVSP alone is actually hard to use in a web app as it does not handle any connection pooling and basically only allows one active connection at a time. It also doesn't work in a standard JDBC compliant manner which is why I started a project https://github.com/asharif/mv-session-mgr). I downloaded it off the tigerlogic ftp site ftp://ftp.tigerlogic.com/pub/MVSP/Java/

There are some samples in that zip file as well. Then it was just a matter of writing a bit of code:

package comuniversalmetalsmvbase;

import com.tigr.mvapi.MVConnection;
import com.tigr.mvapi.MVConstants;
import com.tigr.mvapi.MVStatement;
import com.tigr.mvapi.ResultSet.MVResultSet;
import com.tigr.mvapi.exceptions.MVException;
import java.util.Properties;

/**
 *
 * @author arash
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {



        Properties props = new Properties();
        props.setProperty("username", "MVSP");
        props.setProperty("password", "");
        String url = "jdbc:mv:mvbase:192.168.1.5:9010";
        String account = "SYSPROG";
        String AM = MVConstants.AM;
        String query;
        MVConnection connection = null;
        try
        {
            connection = new MVConnection(url, props);

            /**
             * Execute a query and display the results:
             */
            MVStatement mvStatement = connection.createStatement();
            connection.logTo(account, "");
           // query = "LIST CUSTOMERS (I";
            //boolean result = mvStatement.execute(query);
            //MVResultSet results = mvStatement.getResultSet();
            MVResultSet results = mvStatement.executeQuery("PEOPLE", "", "", "FIRST-NAME");
            while (results.next())
            {
                String row = results.getCurrentRow();
                System.out.println(row);
            }


        }
        catch (MVException e)
        {
            System.out.println(e.toString());

            
        }
        finally
        {
            if (connection != null)
            {
                try
                {
                    connection.close();
                }
                catch (MVException e)
                {
                    e.printStackTrace();
                }
            }
        }

    }

}



Tuesday, June 7, 2011

Grails Spring Security & Ldap Plugins

So I had to implement a user authentication + role based system at work. Sounded like a perfect fit for Spring Security and the LDAP Grails plugins. Unfortunately they weren't that straight forward at the time. Since then I updated the official docs. See the link:

http://burtbeckwith.github.com/grails-spring-security-ldap/docs/manual/index.html

Tuesday, March 15, 2011

GIT Merges

Learning GIT is fun!

When you want to merge and cannot do a fast forward from a remote getting CONFLICTS are inevitable. First off, if you ever mess anything up you can always

git reset --merge ORIG_HEAD

This will set you back to before the merge attempt.

When you do get a conflict, fix the file and then commit with -i like so:

git commit -i myfile.java


This will stage the file first.

Thursday, March 10, 2011

Learning PICK....

So for a new project I am starting to learn a little about PICK systems, specifically MVBase. Different way of thinking from SQL that's for sure. Anyway just some notes for myself as well as those who are looking to start...

everything is a file. you create a db with:

CREATE-FILE [DB_NAME] 3 43
In the above the 3 and 43 are modulos??? and somehow represent the size of the file as well as the file dictionaly. The command above basically creates a file as well as a file dictionary or a specification on the schema if you will. Now to create the schmea:
[ED|DE] DICT PEOPLE P-ID

in above it's either ED or DE. Then enter the command

I

This will put you in an inline insert mode. Have to refer to the MVBase docs for specifics but the following:

>001 A                                       
002 1    
003 Customer ID                                                   
004                                                                 
005                                                                        
006                                                                       
007 ML(#-####-####)          
008                                                             
009 L                                                                   
010 12

The main thing here is 002 which is the order in which this fields shows up and 003 which is the header. 007 is the formatting of the text, 009 is justification and 010 is the width allocated in the command prompt for the column.

After this is done we need to create a data file for the dictionary like so:

>ED DATA PEOPLE [id]
[id] can be anything it's just the name that you give the file. The important thing about this datafile is that it has to match the dictionary file. If in the DICT file you state on 002 that this field is item 1 then this the value in the data file NEEDS to be on the first line like so

>001 Arash

Lasty you query the file like so

>LIST PEOPLE FIRST-NAME
which should result in

>PEOPLE......First Name...
ASHARI      Arash

Next up....connecting and retriving this from Java! =)

Monday, January 10, 2011

Forcing .NET to proxy requests

Two posts back to back after being away for a couple months....I'm pumped!

So I ran into a situation where I needed to know exactly what my .NET app was doing. In particular I had to log the soap calls it was making to understand them. There are probably many ways of doing this but the way I though of was to make the server proxy it's requests through fiddler. This seems like an easy thing to do but it took me forever googling it to figure it out.

Sure enough the answer is a mere 10 lines of xml in the web.config....enjoy!

<system.net>
    <defaultProxy>
      <proxy
        usesystemdefault="False"
        bypassonlocal="True"
        proxyaddress="http://127.0.0.1:8888"/>
    </defaultProxy>
</system.net>


Put the above anywhere in the configuration section and you'll be going through port 8888.

Castle ActiveRecord and Castle Windsor Configuration for .NET

Well it's been a long time since my last post....over 2 months wow! Started a new job and it's been keeping me busy. Been working a lot with the Castle stack for .NET. It's actually a VERY nice framework based on what are now common enterprise architecture patters, or as Fowler would call them PEAA.

It actually has really good documentation that is not a freaking dissertation (hello SpringSource, I'm talking to you!).

Here is an example of how to configure the ActiveRecord Framework along with the IoC Windsor using the facilitator:

In the web.config in the config section we need to add the castle facilitator:
<configsection>
<section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler,   Castle.Windsor">
</section>
</configsection>



Then we need to setup the castle section that we just defined like so:

<castle>
  <facilities>
   <facility id="arfacility" type="Castle.Facilities.ActiveRecordIntegration.ActiveRecordFacility, Castle.Facilities.ActiveRecordIntegration" isWeb="true" isDebug="false">
    <assemblies>
     <item>[assembly_name_to_init_AR]</item>
    </assemblies>
    <config>
     <add key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
     <add key="dialect" value="NHibernate.Dialect.MsSql2005Dialect"/>
     <add key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
     <add key="connection.connection_string_name" value="[connection_string_name]"/>
     <add key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory,NHibernate.ByteCode.Castle"/>
     <add key="query.factory_class" value="NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory, NHibernate"/>
    </config>
   </facility>
  </facilities>
 </castle>

if you want to use just active record without the IoC and facilitator you just need:

<section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" />
instead to the configuration section and the following:

<activerecord 
        isWeb="true|false" 
        isDebug="true|false" 
        pluralizeTableNames="true|false"
        threadinfotype="custom thread info implementation"
        sessionfactoryholdertype="custom session holder implementation"
        namingstrategytype="custom namingstrategy implementation">

        <config
            database="MsSqlServer2000|MsSqlServer2005|MsSqlServer2008|SQLite|MySql|MySql5|Firebird|PostgreSQL|PostgreSQL81|PostgreSQL82|MsSqlCe|Oracle8i|Oracle9i|Oracle10g"
            connectionStringName="name of connection string in config">
            <!-- Any legal NHibernate parameter you want to specify or override its default value -->
        </config>

        <config type="Full Type name to Abstract Class that defines boundaries for different database">
            <add key="connection.driver_class"           value="NHibernate Driver" />
            <add key="dialect"                           value="NHibernate Dialect" />
            <add key="connection.provider"               value="NHibernate Connection Provider" />
      <!-- Use only one of the two attributes below -->
            <add key="connection.connection_string"      value="connection string" />
            <add key="connection.connection_string_name" value="name of connection string in config" />
        </config>
        
    </activerecord>


this is described in nice detail on the castle website

The last step would be to use the global.asax.cs file and on Application_Start do:

//init windsor IoC container
            Castle.Windsor.WindsorContainer container = new Castle.Windsor.WindsorContainer(new Castle.Windsor.Configuration.Interpreters.XmlInterpreter());
            

Now adding classes for automated DI is just as simple. In the same init method you would do the following:

container.Register(Castle.MicroKernel.Registration.Component.For<[class_name_here]>());

To recall a class you just make a setter in another class that has been injected. If you want access from a class that was not injected by Windsor you would do the following:

container.Resolve<[class_name_here]>();


Not so bad huh?