Wednesday
03Mar2010

Switching layouts when screen orientation changes in Android

 

When a displays orientation is changed you may find that your original layout doesn’t scale well. Every time the device orientation changes you current activity is destroyed and recreated. You can change your layout based on the current screen orientation in onCreate()

private void setContentBasedOnLayout()
{
    WindowManager winMan = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
    
    if (winMan != null)
    {
        int orientation = winMan.getDefaultDisplay().getOrientation();
        
        if (orientation == 0) {
            // Portrait
            setContentView(R.layout.alertdialogportrait);
        }
        else if (orientation == 1) {
            // Landscape
            setContentView(R.layout.alertdialoglandscape);
        }            
    }
}

For more information see Wei-Meng Lee’s article on Dev-X: http://www.devx.com/wireless/Article/40792/0/page/1

Monday
08Feb2010

Moving a SharePoint site collection to another managed path

To move a SharePoint site collection to another location you can run the following commands

 

1. stsadm –o backup –url <site collection url> –filename <filename to store backup>

2. stsadm –o deletesite –url <site collection url>

3. stsadm –o restore –url <site collection url> –filename <filename to restore from>

You must delete the original site before restoring to avoid errors.

Saturday
06Feb2010

Battery Conscious: Using your GPS with Android

With that Android OS it is straight forward to use your GPS to get your location. Starting out you may get your location manager and register for updates so your program get’s notified of changes in position. It may look something like this:

LocationManager locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locListener = new LocationListener()
{
    public void onLocationChanged(Location location)
    {
        if (location != null)
        {
            Toast.makeText(getBaseContext(),
            "Position: latitude [" +
            location.getLatitude() +
            "] longitude [" + location.getLongitude()+"]",
            Toast.LENGTH_SHORT).show();
        }
    }
 
    public void onProviderDisabled(String provider)
    {
    }
 
    public void onProviderEnabled(String provider)
    {
    }
 
    public void onStatusChanged(String provider,
    int status, Bundle extras)
    {
    }
 
};
 
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locListener);


This is a typical example you might see floating around on the internet or in an Android Pro book. The line that requests location updates takes the following parameters

 

1. GPS Provider

2. Minimum time between updates in milliseconds

3. Minimum distance between updates in meters

4. Location Listener

 

The above implementation will actually keep you GPS active all the time and drain your battery in less than 5 hours. It also doesn’t take into account your actual needs when specifying the location provider, in this case the GPS. Let’s take a look at how to improve this code to save battery life.

The first thing you can do is set up criteria based on your needs to get the best GPS provider available. For instance, if you only need to get your location (lat, lon) without any information on bearing or speed, and require that the battery have at least a medium charge to use the GPS then you can do so. The following example uses Criteria to get the best GPS provider and limits the time and distance between updates to save battery life.

private void SetupGPSListener()
{
    Criteria criteria = new Criteria();
    
    criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    
    criteria.setAltitudeRequired(false);
    criteria.setSpeedRequired(false);
    criteria.setBearingRequired(false);
    
    // Indicates whether the provider is allowed to incur monetary cost.
    criteria.setCostAllowed(true);
    
    // Most location sensitive apps will need to be reactive to user movement.
    // Simply polling the Location Manager will not force it to get new updates from the Location Providers.
    // Use the requestLocationUpdates method to get updates whenever the current location changes
    
    // the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, 
    // and actual time between location updates may be greater or lesser than this value.
    int minTimeBetweenUpdatesms = 1000 * 60;
    
    // the minimum distance interval for notifications, in meters
    int minDistanceBetweenUpdatesMeters = 20; // 100 ft
    
    // Enable location providers
    // This method enables each provider and returns the last known location.
    // Also requests periodic updates for each provider to force android to start updating the locations for the other applications.
    String provider = locationManager.getBestProvider(criteria, true);
            
    locationManager.requestLocationUpdates(provider, minTimeBetweenUpdatesms, minDistanceBetweenUpdatesMeters, new LocationListener() {
        
        public void onLocationChanged(Location location) {
            currentLatitude = location.getLatitude();
            currentLongitude = location.getLongitude();                    
        }
 
        public void onProviderDisabled(String provider) {
            // Update application if provider disabled.
            Log.i(LOG_TAG, "GPS Provider is disabled");
        }
 
        public void onProviderEnabled(String provider) {
            // Update application if provider enabled.
            Log.i(LOG_TAG, "GPS Provider is enabled");
        }
 
        public void onStatusChanged(String provider, int status, Bundle extras) {
            
        }                
    });    
}
Thursday
04Feb2010

Creating a static WSDL through reflection

If you are deploying custom services to a SharePoint site you are accustom to the following steps:

1. Deploy the signed library to the GAC.

2. Deploy the asmx file to \12\TEMPLATE\LAYOUTS\

3. Run disco.exe to generate a disco wsdl file.

4. Copy the asmx file to 12\ISAPI.

5. Modify the disco and wsdl file, rename them, and copy them to the 12\ISAPI

For more info on that read Creating a Custom SharePoint Web Service

To speed up your deployment the following code will open up the service dll, reflect it, and modify the attributes for use in SharePoint. This can be run as a post-build event so the output from your builds are the actual deployable files.

 

string assemblyFile = "C:\\temp\\WebServiceLibrary.dll";
string serviceClassName = "WebServiceLibrary.ClientPortalSvc";
string outFile = "c:\\temp\\test1.txt";
 
// Load the assembly from file
// Note: Assembly will be locked
Assembly assembly = null;
 
try
{
    assembly = Assembly.LoadFile(assemblyFile);
}
catch (Exception ex)
{
    Console.WriteLine("Error loading file " + ex.Message);
    return;
}
 
Type[] types = assembly.GetTypes();
Type referencedType = null;
 
foreach (Type typ in types)
{
    if (typ.FullName.Equals(serviceClassName))
    {
        // Found the requested type
        referencedType = typ;
    }
}
 
if (referencedType != null)
{
    var reflector = new ServiceDescriptionReflector();
    reflector.Reflect(referencedType, "http://localhost/temp.asmx");
 
    using (var ms = new MemoryStream())
    {
        var wtr = new XmlTextWriter(ms, Encoding.ASCII);
        wtr.Formatting = Formatting.Indented;
 
        // Add the SP imports and start element
        wtr.WriteStartElement("%@ Assembly Name=\"Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c\" %>\r\n" +
                              "<%@ Import Namespace=\"Microsoft.SharePoint.Utilities\" %>\r\n" +
                              "<%@ Import Namespace=\"Microsoft.SharePoint\" %>\r\n" +
                              "<% Response.ContentType = \"text/xml\"; %");
 
        reflector.ServiceDescriptions[0].Write(wtr);
 
        // Read the XML into a string
        ms.Position = 0;
        var reader = new StreamReader(ms);
        var xmlString = reader.ReadToEnd();
        ms.Position = 0;
        wtr.Close();
 
        // Rewrite the soap address for SP. This will allow the soap:address to be
        // correct regardless of service name or request location
        string spLocation =
            " location=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request))" +
            ",Response.Output); %> />";
 
        xmlString = Regex.Replace(xmlString, "\\<soap\\:address.*", "<soap:address" + spLocation);
        xmlString = Regex.Replace(xmlString, "\\<soap12\\:address.*", "<soap12:address" + spLocation);
 
        // Out to a file
        using (StreamWriter fileStream = new StreamWriter(outFile))
        {
            fileStream.Write(xmlString);                        
        }
        
    }
}
else
{
    throw new Exception("The " + serviceClassName + " was not found in " + assemblyFile);
}
}

 

Download:

Thursday
04Feb2010

Debugging JavaScript in IE8 with Developer Tools

IE8 comes with developer tools that allow you to debug JavaScript. How many times have you seen this:

image

When you need to debug JavaScript press F12 or select options –> Developer Tools. This will bring up the developer tools. Click the Script tab at the top and set breakpoints as needed.

 

 

image

 

The right hand pane has a locals view that will show you the values of your variables as you step through the JavaScript. Hit the start debugging button and reload the page in your browser. You can continue (F5) after hitting your breakpoint and checking out the values.

image