Prash's Blog

java.lang.VerifyError: Expecting a stackmap frame at branch target January 19, 2012

Filed under: Google App Engine,Java — prazjain @ 6:30 pm
Tags: ,

If you get this same error :


WARNING: Error for /doit
java.lang.VerifyError: Expecting a stackmap frame at branch target 27 in method com.yourpackage.YourServlet.doGet(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V at offset 11
 at java.lang.Class.getDeclaredConstructors0(Native Method)
 at java.lang.Class.privateGetDeclaredConstructors(Class.java:2404)
 at java.lang.Class.getConstructor0(Class.java:2714)
 at java.lang.Class.newInstance0(Class.java:343)
 at java.lang.Class.newInstance(Class.java:325)
 at org.mortbay.jetty.servlet.Holder.newInstance(Holder.java:153)
 at org.mortbay.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:428)
 at org.mortbay.jetty.servlet.ServletHolder.getServlet(ServletHolder.java:339)
 at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
 at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:35)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
 at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:60)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
 at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
 at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:122)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
 at com.google.appengine.tools.development.BackendServersFilter.doFilter(BackendServersFilter.java:97)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
 at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
 at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
 at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
 at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
 at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
 at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:78)
 at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
 at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:362)
 at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
 at org.mortbay.jetty.Server.handle(Server.java:326)
 at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
 at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
 at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:547)
 at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
 at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
 at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
 at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)

 

then you need to add an attribute -XX:UseSplitVerifier to your Default VM arguments.

On Eclipse : Windows -> Preferences -> Java -> Installed JRE’s

And selected and edit, the one that you are using, to include -XX:-UseSplitVerifier

Hope that helps

 

oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match January 6, 2012

Filed under: Android — prazjain @ 1:00 pm
Tags: , , ,

I got this error when trying to post a simple tweet from my android app into twitter.

I had a sample test app created in twitter that I was using for a couple of days and it worked fine with all its consumer keys / secrets. But just before I was about to release the android app and created a new twitter app for use in release BOOM! I get this error! All I did was replace the CONSUMER KEY  and CONSUMER SECRET.

I searched the net all over the place but nothing could solve my issue.

Here is the resolution that worked.

In Twitter you can create apps that are either Browser based or Client based. Earlier twitter had a mechanism where it will ask the user to choose their app type. As seen in the below screenshot.

Here user can easily specify whatever type of application he intends to make. Also the callback url is optional because your android app application will overwrite it anyways to receive a callback.

Previous version of Twitter's Application creation page

Previous version of Twitter's Application creation page

Previous version of Twitter’s Application creation page

The new Twitter application creation page looks like this :

New Version of Twitter's application creation page

New Version of Twitter's application creation page

Here still the callback url is optional but what is not mentioned here in description is, this field is also used to determine if your application is a Client or Browser based application.

So only if you fill callback url for your application, it will be considered as browser based application else it will be considered as a client application.

In my case in the first test app I had set callback url but when I created a second app on twitter I left it out (because it is an optional field) and hence the Authorization failed.

So remember to give your application Read and Write Access and assign it a callback url so twitter will know that it is a browser based application.

I hope that helps.

 

Cannot convert lambda expression to type ‘string’ because it is not a delegate type November 7, 2011

Filed under: ADO — prazjain @ 12:34 pm
Tags: , , , , ,

This error happens over and over but only after considerable time when you have forgotten how you fixed it last time.

            foreach (string colName in breakup)
            {
                IEnumerable res = from row in QueryCSVModel.FilteredData.Table
                                  select row[colName];    //error on select : Cannot convert lambda expression to type 'string' because it is not a delegate type
                //do something here
            }

This is the solution specified here  (rewriting here in case it helps you)

  • Add reference to System.Data.DataSetExtensions
  • Add using for System.Data and System.Linq

But this still did not work for me.

What I missed is using AsEnumerable() after DataTable, this code below works

            foreach (string colName in breakup)
            {
                IEnumerable res = from row in QueryCSVModel.FilteredData.Table.AsEnumerable()
                                  select row[colName];
                //do something here
            }

 

How to Select or Project some columns from a Datatable programmatically without SQL November 7, 2011

Filed under: ADO — prazjain @ 11:26 am
Tags: , , , , , , , ,

If you want to filter a few rows you a give a conditional expression that will be applied and you get only the resulting rows that satify the conditional expression.

But what if you have around 50 columns and you do not want to see all of them in the result after a select query.

So how do you remove the extra columns? This is how I worked around removing the columns I did not need.

Steps:

  1. Get the rows that satify the filter search criteria
  2. Import them and create a new table
  3. Now all I am doing is, if the the column name is not part of SelectedColumn (string property) then I just remove it from the data table’s column collection. (Of course you cannot remove it in the ‘for’ loop because you cannot edit the collection underlying the enumerator while you are running through the enumerator. So just store it in a temporary collection and remove them later).
  4. Thats it, you have your results!
        private void btnExecute_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder queryBuilder = new StringBuilder();
            //Filter the rows that satisfy the conditional expression
            DataRow[] rows = QueryCSVModel.Data.Table.Select(QueryCSVModel.FilterCriteria);
            //Clone the table to create a new one, and import the eligible rows
            DataTable dt = QueryCSVModel.Data.Table.Clone();
            foreach (DataRow item in rows)
            {
                dt.ImportRow(item);
            }
            List<DataColumn> toRemove = new List<DataColumn>();
            foreach (DataColumn col in dt.Columns)
            {
                //Any column name that is not desired (not in selected columns) is to be removed.
                if (!string.IsNullOrWhiteSpace(QueryCSVModel.SelectedColumns) && !QueryCSVModel.SelectedColumns.Contains(col.ColumnName))
                {
                    toRemove.Add(col);
                }
            }
            // iterate over data column collection and remove the unwanted columns.
            foreach (DataColumn col in toRemove)
	        {
                dt.Columns.Remove(col);
	        }
            //thats it, you have your data with fewer columns
            QueryCSVModel.FilteredData = dt.DefaultView;
        }
     

 

OleDbException is not a valid path Make sure the path name is spelled correctly November 3, 2011

Filed under: ADO — prazjain @ 5:39 pm
Tags: , , , , ,

It has been ages since I did ADO programming. And naturally I hit this common error when loading up my CSV file in memory.

Problem:

      System.Data.OleDb.OleDbException was unhandled

      Message=’C:\CSVTasks\TXT2_RMMTRADE_20101124EOD_20101125_RERUN.CSV’ is not a valid path.

      Make sure that the path name is spelled correctly  and that you are connected to the server on which the file resides.

      Source=Microsoft JET Database Engine ErrorCode=-2147467259

Reason:

The reason this happens is if you give the full file path in the connection string or if you give just the relative file path when creating Data Adapter using select command text.

example:

            // if you have given full file path below, then it will cause this issue
            string connStr = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + filePathFull + ";Extended Properties=\"Text;HDR=YES;FMT=Delimited\"";
            OleDbConnection conn = new OleDbConnection(connStr);
            conn.Open();

Or if you give just the file name (relative url) when loading file in adapter you will get this exception:

            // if you have given just the file name (not full path) below then it will cause this issue
            OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + fileName, conn);
            DataSet ds = new DataSet("QueryCSV");
            adapter.Fill(ds);

Solution:

To avoid this issue

  1. You need to give the full path to the directory when your CSV or Text file resides, in the connection string.
  2. You need to give the full file path in the select command text when creating data adapter.

Code sample

    public class CSVReader
    {
        public static DataView GetData(string fileFullPath,string directoryFullPath)
        {
            // give full path to DIR here
            string connStr = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + directoryFullPath + ";Extended Properties=\"Text;HDR=YES;FMT=Delimited\"";
            OleDbConnection conn = new OleDbConnection(connStr);
            conn.Open();
            // give full path to the file here
            OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + fileFullPath, conn);
            DataSet ds = new DataSet("QueryCSV");
            adapter.Fill(ds);
            DataTable dt = ds.Tables[0];
            conn.Dispose();
            return dt.AsDataView();
        }
    }

 

Odbc drivers not found on Windows 7 Home 64 bit OS December 5, 2010

Filed under: Uncategorized — prazjain @ 2:22 am
Tags: , , ,

I was writing an application that used ODBC drivers but then realized that none of the odbc drivers were present when I check in Control Panel –> ODBC sources. I see only two options SQL Server and SQL Server native client.

To see the other options that you used to see earlier, run the executable mentioned below :

 C:\Windows\SysWOW64\odbcad32.exe 

 

Create Custom Routing Events in WPF May 19, 2010

Filed under: WPF — prazjain @ 10:46 pm
Tags: ,

WPF provides a ton of events in its library, but its not too tough if you have to create a custom event to support a specific scenario.
In a small example below we will create a custom event that would sort the text we enter in the textbox.
Screen before and after the command execution :

  • Create a new WPF project, name it CustomEvents.
  • Copy paste the XAML below in Window1.xaml file


<StackPanel>
 <TextBox Name="textBox" Margin="10,10" />
 <Button Name="btnSort" HorizontalAlignment="Center" Padding="10,3" FontWeight="Bold" Margin="10,3">Sort</Button>
 </StackPanel>

  • Create a custom command for our use:


/// <summary>
 /// Class that holds the custom command(s)
 /// </summary>
 public class SortCommand
 {
 /// <summary>
 /// Actual command object
 /// </summary>
 private static RoutedUICommand sortCommand;

 /// <summary>
 /// Property exposing the command object
 /// </summary>
 public static RoutedCommand Sort
 {
 get { return sortCommand; }
 }

 /// <summary>
 /// Static constructor initializing the input gestures that should invoke the custom command
 /// </summary>
 static SortCommand()
 {
 InputGestureCollection gestures = new InputGestureCollection();
 gestures.Add(new KeyGesture(Key.S, ModifierKeys.Control, "Control-S"));
 sortCommand = new RoutedUICommand("Sort Command", "Sort", typeof(SortCommand), gestures);
 }
 }

  • Now we have created a custom command and we have a UI in place. Now linkup the command object and the UI. Assuming you have not renamed Window1.xaml, paste the code below into your Window1.xaml.cs.


/// <summary>
 /// Interaction logic for Window1.xaml
 /// </summary>
 public partial class Window1 : Window
 {
 public Window1()
 {
 InitializeComponent();
// attach the command to the button so the command can be invoked on button click
 btnSort.Command = SortCommand.Sort;
// create a command binding and attach actual handlers to the command.
 CommandBinding binding = new CommandBinding();
 binding.Command = SortCommand.Sort;
 binding.CanExecute += new CanExecuteRoutedEventHandler(binding_CanExecute);
 binding.Executed += new ExecutedRoutedEventHandler(binding_Executed);
//add the command binding to window, so it would handle the execute event
 this.CommandBindings.Add(binding);
 }

 void binding_Executed(object sender, ExecutedRoutedEventArgs e)
 {
 char[] contents = textBox.Text.ToCharArray();
 Array.Sort(contents);
 textBox.Text = new string(contents);
 }

 void binding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
 {
// we sort only if there is some text
 e.CanExecute = textBox.Text.Length > 0;
 }
 }

When the button is clicked as there is no command binding associated with the Sort command there, the event is routed up the element tree
where the window handles the executed event.

 

Entity Framework 4.0 supports POCO May 13, 2010

Filed under: .Net 4.0,Entity Framework — prazjain @ 8:49 pm
Tags: , ,

POCO – Plain Old CLR Object

In Entity Framework 3.5 an Entity Class had to extend EntityObject class which in turn implemented IEntityWithKey, IEntityWithChangeTracker, IEntityWithRelationships. All of this meant more persistence logic into a domain object, a place where it does not belong. It also made testing of these domain object a bit more complicated.

Entity Framework 4.0 now supports POCO, so simple implementation like below could be used with EF 4.0 (database used with this example is the Microsoft AutoLot database).


public class Customers {

public int CustID {   get;   set;   }

public string FirstName {   get;   set;   }

public string LastName {   get;   set;   }

}

This also makes the code easier to test, and it extracts the persistence logic out of domain objects.

 

New C# Language Features in .Net 4.0 May 7, 2010

Filed under: .Net 4.0 — prazjain @ 11:31 pm
Tags: , , , ,

.Net 4.0 has added couple of new language features in C#

Dynamic Lookup

C# has added a new static type named ‘dynamic’. It supports late binding, so any calls to methods, properties, fields are not resolved at compile time. Thus an error arising due to its use is also detected at runtime.


dynamic person = GetPerson();

// A runtime error would be generated if the object returned by GetPerson() method does not has Name property

person.Name="Prashant";

‘dynamic’ type provides a lot of help to programmers dealing with COM objects in C#

Optional Parameters

C# now provides the ability to assign default values to method parameters incase the caller does not intend to pass value for a parameter.


void Print(string car="Mini Cooper", int price=15000)

{      Console.Writeln(string.format("Car : {0}, Price : {1}",car, price));  }

void M1()

{   Print("VW Golf");  }

Upon invoking M1(), it would print : “Car : VW Golf, Price : 15000″

This shows the parameter ‘price’ assumed the default value.

Named Parameter

Method parameters can now be assigned names, so its no longer necessary that method arguments are passed in the same order as method parameters.


void Print(string car="Mini Cooper", int price=15000)

{      Console.Writeln(string.format("Car : {0}, Price : {1}",car, price));  }

void M1()

{   Print(price: 16000, car: "VW Golf");  }

Upon invoking M1(), it would print : “Car : VW Golf, Price : 16000″

Covariance

Covariance means that an object can be treated as less derived. This features is used to return values from methods that are more abstract.


class Vehicle { ... }

class Car : Vehicle { ... }

class Test {

static void Main(string[] args)

{

...

IEnumerable<Car> cars = GetCars();

// this is now possible in .Net 4.0

IEnumerable<Vehicle> vehicles = cars;

// prior to .Net 4.0 it would have required going through 'cars' collection and add every object into a new collection vehicles

}

}

To allow Covariance the IEnumerable type is defined with an ‘out’ keyword


IEnumerable<out T> { ... }

‘out’ keyword says that its fine to take values out from the collection, adding values is not allowed.

Contravariance

Contravariance allows a more derived type argument to be passed into a less derived type method parameter.


class Vehicle { ... }

class Car : Vehicle { ... }

class Test

{

// Contravariance is enabled by using 'in' keyword

delegate void MyHandler<in T> (T a);

static void Main(string[] args)

{

MyHandler<Vehicle> handler = (veh) => { Console.Writeln(veh); }

// below line is now allowed in .Net 4.0

MyHandler<Car> carHandler = handler;

}

}

All that it means is contravariance allows a Car (subtype) to be passed into a method that requires Vehicle (base type), which could do not harm to the execution of method. But this is only allowed when the delegate generic definition uses ‘in’ keyword, without ‘in’ it would fail in .Net 4.0 too!

Events

Events in C# look like fields / properties. Operators += and -= are overloaded to map to add and remove accessor methods.

Prior to C# 4.0, these generated accessors were synchronized across threads using ‘lock(this)’ as the auto generated code decorated accessors with MethodImpl(MethodImpl.Synchronized) attribute, that meant instead of synchronizing access on that invoke ‘add’ & ‘remove’ method, it would synchronized access across any thread that capture lock on ‘this’ object.

To get across this problem, C# 4.0 changes the way the code is generated for these accessors, it generates code to test for race conditions and updates delegate list accordingly.

This should be a non-breaking changes unless your code is dependent on the way synchronization was implemented earlier.

 

How to use Routing Service in Virtual Earth / Bing May 3, 2010

Filed under: Bing — prazjain @ 8:19 pm
Tags: , , , ,

In my previous article on using Geocoding service in Virtual Earth I gave an introduction on how to geo code the address. See here.

In this article I will show how to use that geocoded data and calculate route information using Bing. In this article we would use the Bing Maps keys to authenticate rather than the client token that we used in last article as that if for staging environment. But if you are using the staging environment then I suggest that you use the staging url for the service wsdl and use the VEStagingToken webservice for authenticate (as shown in geocoding service article).

1) Add a service in your VS solution pointing to : http://dev.virtualearth.net/webservices/v1/routeservice/routeservice.svc?wsdl and name it VERouterServiceReference.

2) Create a class RouteFetcher which would hold code to get route information for the locations passed by you.

3) Brief description of what the code does : It uses the Bing Maps key for authentication. It creates a WayPoint object for every location passed by you and send it to the webservice for calculating the route. In the end returning a string representation of instructions for the multi leg journey.

PS : Does anyone know how to paste code without losing indenting ! I have a real bad time pasting my codes here.

/// <summary>
 /// Plans a route through the locations passed in argument in the order specified.
 /// </summary>
 /// <param name="locations">array of string location formatted as (latitude,longitude)</param>
 /// <returns></returns>
 public string Route(string[] locations)
 {
 try
 {
 string results = "";
 RouteRequest routeRequest = new RouteRequest();
 routeRequest.Credentials = new Credentials();
 //routeRequest.Credentials.Token = _clientToken;
 routeRequest.Credentials.ApplicationId = _key;

 Waypoint[] wayPoints = new Waypoint[locations.Length];

 int pointIndex = -1;
 foreach (string point in locations)
 {
 pointIndex++;
 wayPoints[pointIndex] = new Waypoint();
 string[] digits = point.Split(',');
 // ignore the location if the string is not correctly formatted
 if (digits.Length!=2) continue;
 wayPoints[pointIndex].Location = new Location() { Latitude = double.Parse(digits[0].Trim()), Longitude = double.Parse(digits[1].Trim()) };
 if (pointIndex == 0)
 wayPoints[pointIndex].Description = "Start";
 else if (pointIndex == locations.Length)
 wayPoints[pointIndex].Description = "End";
 else
 wayPoints[pointIndex].Description = string.Format("Stop #{0}", pointIndex);

 }

 routeRequest.Waypoints = wayPoints;

 RouteServiceClient routeServiceClient = new RouteServiceClient();
 RouteResponse routeResponse = routeServiceClient.CalculateRoute(routeRequest);

 StringBuilder directions = new StringBuilder("");
 if (routeResponse.Result.Legs.Length > 0)
 {
 int instructionIndex = 0;
 int legIndex = 0;
 foreach (var leg in routeResponse.Result.Legs)
 {
 directions.Append(string.Format("Leg #{0}\n", ++legIndex));
 foreach (var itineraryItem in leg.Itinerary)
 {
 directions.Append(string.Format("{0}. {1}\n", ++instructionIndex, itineraryItem.Text));
 }
 Regex regex = new Regex("<[a-z/:]*>",RegexOptions.IgnoreCase);
 results = regex.Replace(directions.ToString(),string.Empty);
 }
 }
 else
 results = "No routes found";

 return results;

 }
 catch (Exception ex)
 {
 Console.WriteLine(ex.Message);
 return "Exception occurred";
 }

 }

 

 
Follow

Get every new post delivered to your Inbox.