Google Search

Showing newest posts with label programming. Show older posts
Showing newest posts with label programming. Show older posts

Thursday, April 8, 2010

Finger kinetic scrolling list view in windows mobile .netcf C# ?

i was recently searching a way to achieve a flick or finger scroll able listview in our upcoming project in Windows Mobile but unfortunately though the native .net compact framework list view is finger scrollable in touch supported phones but it was pathetic and unusable for real live projects as it is single line and cannot be customized and after a lot of R&D i came to know that we must either buy a third party control or write our own control first i tried with the owner drawn list view with sample in MSDN and built my own control but later we faced lot of short comings as it is not finger scrollable but can only be used to select by touching the screen and only way to scroll is DPAD navigation or using scroll bar, but the Owner drawn listview given in MSDN by Microsoft did not serve the purpose in the new touch screen era so i discarded the control and kept it aside for use in non touch mobiles.

Then after a lot of search i accidentally came across a custom control in one of the forums which was originally developed by the forum member called DOSFAN(forum identity) and which underwent a lot of changes and optimization by ginger cat(forum identity) which turned into a truely good finger scrollable kinetic list control and after a huge cosmetic modification i was able to use it in our project below is the video of the bare custom control downloaded from the forum here

video

though the control is good finger responsive and has good scrolling logic there are few shortcomings in the control first is it does not support DPAD navigation and does not support scroll bar apart from that it is one of the best free alternative for the native list control, so if you guys are in the need of kinetic listview you can try this if by any chance you were able to modify the code for DPAD Navigation and Scroll bar do share the modified control with us.

Thursday, March 11, 2010

breakpoints not working in visual studio ? solution and quick fix

Are you getting the warning "The break point will not currently be hit. No symbols have been loaded for this document." recently all of a sudden breakpoints stopped working in my project on vs IDE the breakpoints became hollow circle with a warning message inside though i had this problem previously on both VS 2008 and Vs 2005 i always forgot the solution on how i fixed it so this time i thought of logging it in my blog for future reference ;) below are few points that comes handy when you break points stop working on vs


--> First of all check whether you are running on debug or release mode if you are running on release mode change it to debug, if it is in debug try next step.

--> Go to Debug-->Windows-->Modules check whether all the project dll's have symbol status if it says cannot find or open pdb file right click on module select load symbols and browse to the path of your application PDB,if it says says symbol Loaded then try next point.

--> Exit your IDE and delete bin and obj folder go to visual studio command line and run "devenv /resetsettings" NOTE: running this command will reset all your visual studio settings to default so think before running it and use at your own risk.

--> If you are using web development then Clear temproary output folders the path looks something like below

C:\WINDOWS\Microsoft.NET\Framework\{framework version}\Temporary ASP.NET Files\{some name}\{some numbers}\{some numbers}

--> if your are Windows developer like me and all the above tips fails try deleting the emulator images actually this worked for me go to below path and delete the emulator images as shown in below pic

C:\Documents and Settings\yourname\Application Data\Microsoft\Device Emulator


though just deleting the image emulator worked for me there are wide array of reasons why the break points never hits and depends on type or projects and applications being developed if your problem was different and you fixed it and if it is not in the above points do share with us by leaving a comment here.

Thursday, February 11, 2010

Draw LinearGradientBrush Background in C# windows mobile .netcf

wanted to draw gradient background on windows form in .net compact framework but not able to find it in the system.Drawing2d this is the most common problem developers face when they first code on .netframework this is because .netcompact framework does not support LinearGradientBrush class recently i too faced the same problem as i wanted to paint double shade linear gradient color as the background to the form but after a small R&D i came to know that there is GradientFill API in windows CE that can be used to get accomplish the task.

i found the sample code in msdn library which liked like a charm now you can display nice gradient fill graphics by using below code as the background. with this sample code you will be able to fill the gradient in two different styles leftoright and toptobottom as shown in below Pic left picture shows leftright pattern and right picture shows topBottom pattern. below is the sample source code which to get the above gradient effect







public void Fill(Graphics gr, Rectangle rc, Color startColor, Color endColor, FillDirection fillDir)
{

// Initialize the data to be used in the call to GradientFill.
Win32Helper.TRIVERTEX[] tva = new Win32Helper.TRIVERTEX[2];
tva[0] = new Win32Helper.TRIVERTEX(rc.X, rc.Y, startColor);
tva[1] = new Win32Helper.TRIVERTEX(rc.Right, rc.Bottom, endColor);
Win32Helper.GRADIENT_RECT[] gra = new Win32Helper.GRADIENT_RECT[] {
new Win32Helper.GRADIENT_RECT(0, 1)};

// Get the hDC from the Graphics object.
IntPtr hdc = gr.GetHdc();

// PInvoke to GradientFill.
bool b;

b = Win32Helper.GradientFill(
hdc,
tva,
(uint)tva.Length,
gra,
(uint)gra.Length,
(uint)fillDir);
System.Diagnostics.Debug.Assert(b, string.Format(
"GradientFill failed: {0}",
System.Runtime.InteropServices.Marshal.GetLastWin32Error()));

// Release the hDC from the Graphics object.
gr.ReleaseHdc(hdc);


}


public enum FillDirection
{
//
// The fill goes horizontally
//
LeftToRight = Win32Helper.GRADIENT_FILL_RECT_H,
//
// The fill goes vertically
//
TopToBottom = Win32Helper.GRADIENT_FILL_RECT_V
}



public sealed class Win32Helper
{
public struct TRIVERTEX
{
public int x;
public int y;
public ushort Red;
public ushort Green;
public ushort Blue;
public ushort Alpha;
public TRIVERTEX(int x, int y, Color color)
: this(x, y, color.R, color.G, color.B, color.A)
{
}
public TRIVERTEX(
int x, int y,
ushort red, ushort green, ushort blue,
ushort alpha)
{
this.x = x;
this.y = y;
this.Red = (ushort)(red << 8);
this.Green = (ushort)(green << 8);
this.Blue = (ushort)(blue << 8);
this.Alpha = (ushort)(alpha << 8);
}
}
public struct GRADIENT_RECT
{
public uint UpperLeft;
public uint LowerRight;
public GRADIENT_RECT(uint ul, uint lr)
{
this.UpperLeft = ul;
this.LowerRight = lr;
}
}


[DllImport("coredll.dll", SetLastError = true, EntryPoint = "GradientFill")]
public extern static bool GradientFill(
IntPtr hdc,
TRIVERTEX[] pVertex,
uint dwNumVertex,
GRADIENT_RECT[] pMesh,
uint dwNumMesh,
uint dwMode);

public const int GRADIENT_FILL_RECT_H = 0x00000000;
public const int GRADIENT_FILL_RECT_V = 0x00000001;

}


Now just copy the above code and paste it in appropriate class file and location it should definitely work

Friday, January 22, 2010

how to speed up visual studio build and compile time ?

Want to reduce build, compile and deployment time in visual studio 2008 or vs2005 windows mobile development? one thing that frustrates .netcf developers is building/ compiling application takes hell lot of a time this is due to platform verification but fortunately there is a hack which can speedup build and compile time several times faster just follow below steps if you are also facing the same issue

--> first of all close your visual studio

--> go to this path C:\WINDOWS\Microsoft.NET\Framework\v3.5\

--> Find Microsoft.CompactFramework.Common.targets file and make sure to back up it

-->Now open Microsoft.CompactFramework.Common.targets file in text editor and look for below statements


<Target
Name="PlatformVerificationTask">
<PlatformVerificationTask
PlatformFamilyName="$(PlatformFamilyName)"
PlatformID="$(PlatformID)"
SourceAssembly="@(IntermediateAssembly)"
ReferencePath="@(ReferencePath)"
TreatWarningsAsErrors="$(TreatWarningsAsErrors)"
PlatformVersion="$(TargetFrameworkVersion)"/>
</Target>

Now modify the Name="PlatformVerificationtask" line by adding this code"Condition="'$(SkipPlatformVerification)' == 'true'"" as below


<Target
Name="PlatformVerificationTask" Condition="'$(SkipPlatformVerification)' == 'true'">
<PlatformVerificationTask
PlatformFamilyName="$(PlatformFamilyName)"
PlatformID="$(PlatformID)"
SourceAssembly="@(IntermediateAssembly)"
ReferencePath="@(ReferencePath)"
TreatWarningsAsErrors="$(TreatWarningsAsErrors)"
PlatformVersion="$(TargetFrameworkVersion)"/>
</Target>


Now open your project and compile it i am damn sure it works 5x faster

Thursday, January 14, 2010

how to create test environment for windows mobile .netcf (unit testing)

After completing the windows mobile application we wanted to create a test environment for testers to test the application but when i searched on the net for the information i was not able to find any help some of them said we have to install the sdks and some said to install the whole visual studio then after brief R&D i was a able to setup and create a basic test environment for testers to test the application.

below are the basic software's, and tools and configuration to test the windows mobile application some of the required software's and link to download

1. Microsoft Active Sync
2. Windows Mobile 6.1 Professional Emulator Images
3. Microsoft Device Emulator 3.0 Standalone

Creating the Environment:
1. First of all Install Active Sync , Windows Mobile Emulator Images and Microsoft Device Emulator as above series

2. Now to start emulator click on start--> all programs--> windows mobile 6.1 sdk--> emulator images--> windows mobile 6.1 professional emulator

3. Once emulator is opened Double click on the Active Sync Icon in the task bar as shown in below picture

4.Now Click On files --> “connection settings” and configure the settings as shown below picture After configuring the connecting settings press “ok”


5.Now to connect emulator to active sync we have to use device emulator start--> all programs--> windows mobile 6.1 sdk--> tools--> device emulator manager


6.The Green Right Arrow indicates active Emulator now right click on the link and select cradle as shown in above link now you can see the emulator starts connecting to active sync as show in below picture

Creating SD Card on Emulator:

1.By default Emulator does not contains card memory to create a virtual card memory go to D: or E: drive on your computer create a folder called “sd card”

2.Now Open your emulator click on files--> configure as shown in below pic

3.Now in the emulator properties go to general tab and browse and set the path to “sd card” folder created before now this folder acts as your storage card for your emulator

4.Now click ok and open your emulator now from your emulator file explorer you can see the virtual storage card as show in below picture


Installing the Cab

To install a cab file put the cab file in storage card folder via active sync or directly in your computer and click to install through the phone

To Uninstall a cab file Go to ActiveSync from file menu click tools-->Add/remove Programs make sure to uninstall only our application not framework or any other applications

To Emulate Calls and SMS on Emulator:

1. To Emulate calls on emulator is simple go to start--> all programs--> windows mobile 6.1 sdk--> tools--> “Cellular Emulator” in the cellular emulator window click on “Call Manager” Tab enter the phone number and press “dial” to cut the call press “Drop call” as show in below pic

2.To Receive SMS on Device emulator from Cellular Emulator first of all you have to configure your Device emulator to receive SMS to configure go to files-->Configure in Emulator Properties window in peripherals tab change settings as show in below PIC note: you have to manually type COM3

3.Now once changing the emulator properties ‘Soft Reset’ your phone by going to files--> reset-->soft and wait for the device to restart automatically

4.To send SMS open the Cellular emulator Go to SMS tab type the SMS string and give the phone number and press send see below PIC now you should receive SMS on your emulator

though this is the way i created the environment for testers if there is any better way or if this is not the right way to let us know

Thursday, January 7, 2010

Windows Mobile .NETCF Vibrate alert implementation

i was recently searching for way to vibrate mobile device through c# code in windows mobile professional and i found a clean and interesting code using win32 dlls in msdn by heliosdev so though of re-posting it here as the collection of sample codes in my blog and as the reference for future


using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace Util
{
public class LED
{
class NLED_SETTINGS_INFO
{
public uint LedNum;
public uint OffOnBlink;
public int TotalCycleTime;
public int OnTime;
public int OffTime;
public int MetaCycleOn;
public int MetaCycleOff;
}

class NLED_COUNT_INFO
{
public int cLeds;
}

const int NLED_COUNT_INFO_ID = 0;
const int NLED_SETTINGS_INFO_ID = 2;

public enum Status
{
OFF = 0,
ON,
BLINK
}

[DllImport("coredll.dll")]
private static extern bool NLedGetDeviceInfo(uint nID, NLED_COUNT_INFO pOutput);

[DllImport("coredll.dll")]
private static extern bool NLedSetDevice(uint nID, NLED_SETTINGS_INFO pOutput);

private int _ledCount;

public LED()
{
_ledCount = GetLedCount();
}

public void SetLedStatus(Status status)
{
NLED_SETTINGS_INFO nsi = new NLED_SETTINGS_INFO();
nsi.OffOnBlink = (uint)status;
for (int i = 0; i < _ledCount; i++)
{
nsi.LedNum = (uint)i;
NLedSetDevice(NLED_SETTINGS_INFO_ID, nsi);
}
}

public void Vibrate(int millisecondsTimeout)
{
SetLedStatus(Status.ON);
Thread.Sleep(millisecondsTimeout);
SetLedStatus(Status.OFF);
}

private int GetLedCount()
{
int count = 0;
NLED_COUNT_INFO nci = new NLED_COUNT_INFO();
if (NLedGetDeviceInfo(NLED_COUNT_INFO_ID, nci))
{
count = nci.cLeds;
}
return count;
}
}
}

Just call vibrate(1000) from any function i made it to vibrate for a second though i did not found any managed code to do it, above code is working like a charm without any issues if there is any managed API for vibrate do let us know.

Tuesday, January 5, 2010

mscorlib.dll and windows mobile cab size

how to reduce build size in windows mobile? most of the .NETCF programmers who are making installation package for the first time will face the common problem that is large install cab of their application most of the time visual studio automatically include some of the dlls such as mscorlib.dll, mscorlib.tlb, system.configuration.dll etc as the dependencies but which are not actually required mscorlib.dll itself occupies around 4MB size in the installer which is very huge some times which is more than 10 times the size of actual application.

the solution is to remove the mscorlib.dll and mscorlib.tlb as it is the part of the .netframeframework and other unwanted dependecies make sure to "exclude" the unwanted dependencies as show in above pic recently one of my friend from other company who moved from J2ME to WM asked me so thought of writing it here as i too faced the similar problem during my early cab generation days ;)

I still was not able to figure it out what happens to make Visual Studio to consider framework dlls as the dependency to the cab file if any of you guys know the answer do share with us

Saturday, December 19, 2009

Fix Microsoft Visual Studio Not Responding and Busy Problem

We are using VS 2008 for development of mobile application until recently the compile and deploy time jumped from mere 5 seconds to almost 30 to 40 seconds its a real pain in the a## if your project deadlines are near this drag in compile occurs for various reason because its a Microsoft product :) but its a best IDE compared to any available IDE out there in the market...

Though its very hard to trace why this happens there are few things that you can look at so that it might solve your problem

1. Check whether your program is going into infinite loop.
2. Most of the time this happens if there is memory leaks in IDE
3. Some times plugins to the visual studio might cause the problem so check whether you have installed any incompatible plugin before you started getting this problem.
4. Check whether you have installed latest service pack released for your version visual studio most of the time this problem might get solved by installing right service packs.

5. you can modify devenv.exe.config so that it can log all the things errors,crashes in a logfile i came across below script in stackoverflow.com just copy and paste below xml code in your denev.exe.config file make sure to take a back of this file before altering it

<system.diagnostics>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="myListener"
type="System.Diagnostics.TextWriterTraceListener, System version=1.0.3300.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="c:\myListener.log" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>

Now restart your visual studio now you can see the log in c drive.... If you know any other fix for this problem do share the solution with us

Thursday, December 17, 2009

run android emulator from command line

recently i wanted to run android emulator from command prompt instead of eclipse as i don't want to open eclipse just to run the apk and check the project as i am working on visual studio now below are the steps to work on emulator without IDE

Step1: First of all download latest Android SDk if you do not have it you can download android sdk from here if you already have it go to next step

after downloading android sdk extract the folder in any drive say D: or E: which has more space in my case i have more space in G: drive so i am extracting it there

step2: Make sure your system has Java Run time if not download it if you already have java installed on your system skip this step...... Now install the downloaded java run time environment and restart the system

step3: Setup the environment variables of your system so that your system can point to android SDK

right click "on mycomputer"-->select "properties"--> click on "Advanced tab" now below advanced tab window click on "Environment Variables button" now in the environment variables window make sure to add the sdk path till tools directory in my case path is G:\android-sdk-windows-1.5_r3\tools now in same window add the same path in system variables "path" as shown in below pic


step4: Now sdk is downloaded and environment is created its now time to create emulator image Android virtual device (AVD) else it is not possible to invoke a emulator... to create avd type below command in command prompt

G:\android-sdk-windows-1.5_r3\tools>android create avd --target 2 --name newavd
where newavd is the name of the emulator

Now it takes a few seconds to create a image of emulator and return the cursor back to command prompt once the command is successfully created you can invoke or start

step5: Now after setting environment and creating emulator image we can run android emulator from command prompt by typing below command

G:\android-sdk-windows-1.5_r3\tools>emulator.exe -avd newavd

above is the steps i found out myself after doing small R&D on how to setup and start a android emulator from command prompt any still better approach will be appreciated

you might also be interested in setting up environment for android programming and to run hello world program through eclipse http://www.ceveni.com/2009/06/writing-android-hello-world-program.html you can find it in above link

Tuesday, November 17, 2009

How to Download file in .NET compact frame work windows mobile ?

if you are desktop developer you know there is api "WebClient" to download a file from the web unfortunately in .netcf that api is absent but there is a alternative way of doing it by using IO streams and download a file see the below code snippet


public static bool fileDownloadDotNetCF(string url)
{
bool success = false;
string destination = getPath();
System.Net.HttpWebRequest request = null;
System.Net.WebResponse response = null;
Stream responseStream = null;
FileStream fileStream = null;

try
{
request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
request.Method = "GET";
request.Timeout = 100000; // 100 seconds
response = request.GetResponse();

responseStream = response.GetResponseStream();

fileStream = File.Open(destination + "\\temp.CAB", FileMode.Create, FileAccess.Write, FileShare.None);

// read up to ten kilobytes at a time
int maxRead = 10240;
byte[] buffer = new byte[maxRead];
int bytesRead = 0;
int totalBytesRead = 0;

// loop until no data is returned
while ((bytesRead = responseStream.Read(buffer, 0, maxRead)) > 0)
{
totalBytesRead += bytesRead;
fileStream.Write(buffer, 0, bytesRead);
}

// we got to this point with no exception. Ok.
success = true;
}
catch (Exception exp)
{
// something went terribly wrong.
MessageBox.Show(exp.ToString(), "Error Could not Download the file");
success = false;

}
finally
{

// cleanup all open streams.

if (null != responseStream)
responseStream.Close();
if (null != response)
response.Close();
if (null != fileStream)
fileStream.Close();
}

// if data transfer fails in between file download delet the
// partially downloaded file
if (!success && File.Exists(destination))
File.Delete(destination);

return success;
}

I dont know why wm .netcf team stripped such a important api from compact framework not only this there are tons of such API's which are very required and useful but not incorporated in compact framework.

Friday, November 13, 2009

Owner-Drawn ListViews or custom list view in windows mobile .netcf?

every developer knows the listview provided by .net compact framework most of the time will not serve the purpose consider if we want a list view some thing like native inbox mail list the generic .netcf tool box does not provide any such options in such cases we can take over the paint method and draw our own items.below is the implemention of an owner-drawn ListView i came across some chinese site it worked.


//This is the basic custom list view control
using System;
using System.Windows.Forms;
using System.Collections;
using System.Drawing;
using System.Data;
using System.Reflection;

using System.Drawing.Imaging;

namespace SmartUI {
enum MailIcon {
unopened,
opened
}

/// <summary>
/// simple MailItem class for each ListView item.
/// </summary>
class MailItem {
public MailIcon icon;
public string sender;
public string subject;

public MailItem(MailIcon Icon, string Sender, string Subject)
{
this.icon = Icon;
this.sender = Sender;
this.subject = Subject;
}
}

/// <summary>
/// Provide a line listview
/// </summary>
class MyListView : OwnerDrawnList {
constint Column1Left = 5;
const int Column2Left = 25;

public MyListView() {
// We need a total of 5 rows, so the height is 180/5=36
Graphics g = this.CreateGraphics();
Font font = new Font(this.Font.Name, 10, FontStyle.Bold);
// Calc line height to be height of letter A plus 10%
int fontHeight = (int)(g.MeasureString("A", font).Height*1.1);
this.ItemHeight = fontHeight*2;
g.Dispose();
}


protected override void OnKeyDown(KeyEventArgs e) {
switch(e.KeyCode) {
case Keys.Return:
MessageBox.Show("You selected item " + this.SelectedIndex.ToString(),
"Item selected",
MessageBoxButtons.OK,
MessageBoxIcon.Asterisk,
MessageBoxDefaultButton.Button1);
break;
}

base.OnKeyDown(e);
}



protected override void OnPaint(PaintEventArgs e) {

// Declare vars
Font font;
Color fontColor;
string bmpName;


Graphics gOffScreen = Graphics.FromImage(this.OffScreen);
gOffScreen.FillRectangle(new SolidBrush(this.BackColor), this.ClientRectangle);
int itemTop = 0;

for(int n = this.VScrollBar.Value; n <= this.VScrollBar.Value + DrawCount; n++)
{



if(n == this.SelectedIndex) //check whether if mail item is selected if so highlight the background color
{
//paint the selected rectangle with system background color
gOffScreen.FillRectangle(new SolidBrush(SystemColors.Highlight),
0,
itemTop,
this.ClientSize.Width - (this.VScrollBar.Visible ? this.VScrollBar.Width : 0),
this.ItemHeight);
fontColor = CalcTextColor(SystemColors.Highlight);
}
else
fontColor = this.ForeColor;


gOffScreen.DrawLine(new Pen(Color.DarkGray),
1,
itemTop+this.ItemHeight,
this.ClientSize.Width - (this.VScrollBar.Visible ? this.VScrollBar.Width : 2),
itemTop+this.ItemHeight);


MailItem lvi = (MailItem)this.Items[n];//paint appropriate mail item to background


if (lvi.icon == MailIcon.unopened) {
font = new Font(this.Font.Name, 10, FontStyle.Bold);
bmpName = "SmartUI.unread.bmp";
}
else {
font = new Font(this.Font.Name, 10, FontStyle.Regular);
bmpName = "SmartUI.read.bmp";
}


Bitmap bmp = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream(bmpName)); //make sure to give correct path else it may crash here

// To draw a transparent image, we need to set the transparent
ImageAttributes ia = new ImageAttributes();
ia.SetColorKey(Color.Red, Color.Red);

// Set the image rectangle
Rectangle imgRect = new Rectangle(Column1Left, itemTop+3, bmp.Width, bmp.Height);

// Draw the image
gOffScreen.DrawImage(bmp, imgRect, 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, ia);
// Draw the mail sender
gOffScreen.DrawString(lvi.sender, font, new SolidBrush(fontColor), Column2Left, itemTop);
// Draw the mail subject
gOffScreen.DrawString(lvi.subject, font, new SolidBrush(fontColor), Column2Left, itemTop + (ItemHeight/2));


font.Dispose();
bmp.Dispose();


itemTop += this.ItemHeight;
}


e.Graphics.DrawImage(this.OffScreen, 0, 0);

gOffScreen.Dispose();
}

// Draws the external border around the control.
protected override void OnPaintBackground(PaintEventArgs e) {
// e.Graphics.DrawRectangle(new Pen(Color.Black), 0, 0, this.ClientSize.Width - 1, this.ClientSize.Height - 1);
}
}


class OwnerDrawnList : Control {
int scrollWidth;
int itemHeight = -1;
int selectedIndex = -1;

Bitmap offScreen;
VScrollBar vs;
ArrayList items;
public OwnerDrawnList() {
this.vs = new VScrollBar();
scrollWidth = this.vs.Width;
this.vs.Parent = this;
this.vs.Visible = false;
this.vs.SmallChange = 1;
this.vs.ValueChanged += new EventHandler(this.ScrollValueChanged);

// Items to draw
this.items = new ArrayList();
}
/// <summary>
///
/// </summary>
public ArrayList Items {
get { return this.items;}
}

protected Bitmap OffScreen {
get {return this.offScreen;}
}

protected VScrollBar VScrollBar {
get {return this.vs;}
}

public event EventHandler SelectedIndexChanged;

// Raise the SelectedIndexChanged event
protected virtual void OnSelectedIndexChanged(EventArgs e) {
if(this.SelectedIndexChanged != null)
this.SelectedIndexChanged(this, e);
}


public int SelectedIndex {
get {return this.selectedIndex;}
set {
this.selectedIndex = value;
if (this.SelectedIndexChanged != null)
this.SelectedIndexChanged(this, EventArgs.Empty);
}
}

protected void ScrollValueChanged(object o, EventArgs e) {
this.Refresh();
}

protected virtual int ItemHeight {
get {return this.itemHeight;}
set {this.itemHeight = value;}
}

// If the requested index is before the first visible index then set the
// first item to be the requested index. If it is after the last visible
// index, then set the last visible index to be the requested index.
public void EnsureVisible(int index) {
if(index < this.vs.Value) {
this.vs.Value = index;
this.Refresh();
}
else if(index >= this.vs.Value + this.DrawCount) {
this.vs.Value = index - this.DrawCount + 1;
this.Refresh();
}
}

//on key press event
protected override void OnKeyDown(KeyEventArgs e) {
switch(e.KeyCode) {
case Keys.Down:
if(this.SelectedIndex < this.vs.Maximum) {
EnsureVisible(++this.SelectedIndex);
this.Refresh();
}
break;
case Keys.Up:
if(this.SelectedIndex > this.vs.Minimum) {
EnsureVisible(--this.SelectedIndex);
this.Refresh();
}
break;
}

base.OnKeyDown(e);
}


protected int DrawCount {
get {
if(this.vs.Value + this.vs.LargeChange > this.vs.Maximum)
return this.vs.Maximum - this.vs.Value + 1;
else
return this.vs.LargeChange;
}
}

protected override void OnResize(EventArgs e) {
int viewableItemCount = this.ClientSize.Height / this.ItemHeight;
this.vs.Bounds = new Rectangle(this.ClientSize.Width - scrollWidth,
0,
scrollWidth,
this.ClientSize.Height);


if(this.items.Count > viewableItemCount) {
this.vs.Visible = true;
this.vs.LargeChange = viewableItemCount;

this.offScreen = new Bitmap(this.ClientSize.Width - scrollWidth, this.ClientSize.Height);
}
else {
this.vs.Visible = false;
this.vs.LargeChange = this.items.Count;

this.offScreen = new Bitmap(this.ClientSize.Width, this.ClientSize.Height);
}

this.vs.Maximum = this.items.Count - 1;
}


protected Color CalcTextColor(Color backgroundColor) {
if(backgroundColor.Equals(Color.Empty)) 
return Color.Black;

int sum = backgroundColor.R + backgroundColor.G + backgroundColor.B;

if(sum > 256)
return Color.Black;
else
return Color.White;
}

}
}



//Call below code from any window form

public CustomListView()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//

olv = new MyListView();
olv.Parent = this;
// Set the bounds of the listview.
olv.Bounds = new Rectangle(0,0, this.ClientSize.Width, this.ClientSize.Height);

// Add data items to listview
for (int i=0; i<10; i++) {
olv.Items.Add(new MailItem(MailIcon.unopened, "Ceveni Com", "re: Custom ListView"));
olv.Items.Add(new MailItem(MailIcon.opened, "James Bond", "Custom ListView"));
}

olv.SelectedIndex = 0;
olv.EnsureVisible(olv.SelectedIndex);

}


if there is any problem in the below code or if there is still shortest method of doing it or any free third party control readily available share with us.

Wednesday, November 11, 2009

GO new Programming Language by Google

Google is really on the "GO" after Browser Chrome, Android Mobile OS, now its Programming language "GO" google officially released this experimental new language boosting to be "fast and lightweight" to the open source community work on this new language was started 2 years ago by eminent team members like Ken Thompson,Rob Pike, Robert Thompson and few others.

The go was designed to combine the speed of dynamic language like python and performance of compiled language such as c, c++ the implementation of go langauge is currently available for Linux and Mac OS x.

The syntax of "GO" is near to C and Python and what interesting is unlike c it supports garbage collection,"GO" supports multi processing and some cool features like true closure, reflection etc some of the features which is lacking as of now in "GO" is type Inheritance, Method Overriding, exception handling, assert.



here is the official website of "GO" community, well i guess google is trying to creep into core it infrastructure may be in matter of days it may even conquer the OS world dominating Microsoft so microsoft watchout.

Thursday, October 22, 2009

delete a file using c# during system reboot or windows restart

How to delete a locked file in C# program in next reboot? some times you may want to delete a file that is locked by other process this scenario may arise in situation such as un installation procedures, clean up operation or deleting a virus infected file in this type of scenarios you can use delete a file by scheduling it to delete in next bootup using MoveFileEx though this is a unmanaged api you can use it by using dllimport and pinvoking in C# below is the sample code snippet on how to do it.


[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
public static extern bool MoveFileEx(string
lpExistingFileName, string lpNewFileName, int dwFlags);

public const int MOVEFILE_DELAY_UNTIL_REBOOT = 0x4;

public static void DeleteOnStartup(string fname)
{
if (!MoveFileEx(fname, null,
MOVEFILE_DELAY_UNTIL_REBOOT))
System.Windows.Forms.MessageBox.Show("unable to process");
}



call the delete function from start or in any event trigger

static void Main(string[] args)
{
DeleteOnStartup(@"C:\lockedfile.txt");

}

though i did not get any direct api to do this in managed code C# if there is any do let us know

Thursday, October 15, 2009

Double Buffering in .NETCF windows Mobile and way to avoid flicker

flickering of UI during painting is One of the common problem windows mobile developer come across though now a days silverlight seems to a good promising alternative for UI design, if you still want to use older methods of coding UI then double buffering is a must for smoother UI and only way to avoid flicker.

unlike desktop environment .netcf is missing inbuilt double buffering support that is The setstyle() in .net, only way to overcome is we have to handle double buffering ourselves, i really curse MS for not porting setstyle() to Compact Framework.

the main reason for flickering is while drawing graphics onto the screen the delay between the calculation time and drawing each data to screen such as Ellipse, Line, Image, Polygon, Rectangle, String etc seems to flicker one way to do is cache it by drawing everything to bitmap and writing it to the screen at one shot see the below example for a brief idea.

Painting without double buffering

protected override void OnPaint(PaintEventArgs e )
{
//Some drawing logic
Graphics gr = e.Graphics;
gr.DrawImage(image, 0, 0);
Graphics gr = e.Graphics;
gr.DrawImage(image, 0, 0);
gr.DrawRectangle(pen, this.ClientRectangle);
}


Painting with double buffering

protected override void OnPaint(PaintEventArgs e )
{
Graphics g; //Offscreen graphics

if (bmpBuff == null) //Bitmap for doublebuffering
{
bmpBuff = new Bitmap(ClientSize.Width, ClientSize.Height);
}

g = Graphics.FromImage(bmpBuff);

g.Clear(this.BackColor);
//Draw some bitmap
g.DrawImage(bmpParent, 0, 0, bmpRect, GraphicsUnit.Pixel);

//Boundary rectangle
Rectangle rc = this.ClientRectangle;
rc.Width--;
rc.Height--;

//Draw boundary
g.DrawRectangle(new Pen(Color.Black), rc);
//Draw from the memory bitmap
e.Graphics.DrawImage(bmpBuff, 0, 0);

base.OnPaint(e);
}

the technic is simple cache/draw everything to bitmap and draw at once on paint method but this comes with the expense of memory so the trade of is very important and is worth for smoother UI and another important thing to remember is never write any logic to calculate in paint method all the basic calculation should be outside the paint method and paint method should just contain simple code to paint the values on to the screen and any more suggestion or trick to avoid flickering is welcome.

Thursday, October 8, 2009

Calculate text width in .NET C# windows

Recently i wanted to calculate the width of the string as i wanted to paint using 2d graphics the text on fly though we can use Graphics.MeasureString it returns approximate size not exact measurement of the string so in this cases we have to use Graphics.MeasureCharacterRanges below is the sample code snippet on how to use it


void paintUI( object sender,PaintEventArgs e )
{

Graphics g = e.Graphics;
string text1 = "One",text2 = "Two",text3 = "Three";

StringFormat format = new StringFormat();
format.SetMeasurableCharacterRanges(new CharacterRange[]{new
CharacterRange(0, text1.Length)});
Region[] r = g.MeasureCharacterRanges(text1, this.Font, new Rectangle(0, 0,
1000, 1000), format);
RectangleF rect = r[0].GetBounds(g);

// using MeasureCharacterRanges
g.DrawString(text1, this.Font, SystemBrushes.ControlText, 0, 0);
g.DrawString(text2, this.Font, SystemBrushes.ControlText, rect.Width, 0);

// the assmbled string
g.DrawString(text3, this.Font, SystemBrushes.ControlText, 0, 20);

// using MeasureString
SizeF sf = g.MeasureString(text1, this.Font);
g.DrawString(text1, this.Font, SystemBrushes.ControlText, 0, 40);
g.DrawString(text2, this.Font, SystemBrushes.ControlText, sf.Width, 40);

}

Though above code is working fine for me if you find still better way of doing it or any issue with the code do let us know

Monday, October 5, 2009

Context Menu in C# windows mobile .netCf (tap and hold)

Recently i wanted to implement contextmenu with animation(progress) though there is no direct api or way to do it after hours of searching on the net i finally found a hack to do it by using win32 dll by P/invoking SHRecognizeGesture in aygshell.dll below pic shows the example of context menu in calendar week view


// Initialize the below code snippet in the beginning of the class
internal struct SHRGINFO
{
public int cbSize;
public IntPtr hwndClient;
public int ptDownX;
public int ptDownY;
public SHRGFLags dwFlags;
}

[Flags]
internal enum SHRGFLags
{
SHRG_RETURNCMD = 0x00000001,
SHRG_NOTIFYPARENT = 0x00000002,
SHRG_LONGDELAY = 0x00000008,
SHRG_NOANIMATION = 0x00000010,
}
[DllImport("aygshell")]
extern private static int SHRecognizeGesture(ref SHRGINFO shr);

[DllImport("coredll.dll", SetLastError = true)]
public static extern IntPtr GetActiveWindow();


//call the showContMenu() method in Mouseup or MouseDown event
public void showContMenu(int x, int y)
{
SHRGINFO shr = new SHRGINFO();
shr.cbSize = Marshal.SizeOf(typeof(SHRGINFO));
shr.dwFlags = SHRGFLags.SHRG_RETURNCMD;
shr.ptDownX = x;
shr.ptDownY = y;
shr.hwndClient = GetActiveWindow();

int ret = SHRecognizeGesture(ref shr);

if (ret == 1000)
contextMenu1.Show(this, new System.Drawing.Point(x, y));

}

I have used above method in more than two views and it works awesome, if you have any problem with above snippet you can reach me through email at the bottom of the page and if there is a better way or if managed code exists share with us.

Tuesday, September 29, 2009

How to take Screen shot of windows Mobile Emulator

We cannot take the snap shot of device emulator just by clicking print screen as windows mobile emulator overrides the print screen, i think most of the windows mobile developers would have come across this, 1) to take a snapshot or screen shot of device emulator you need to use a tool called "Remote Zoom In" which you can find in start-->All program --> Microsoft visual studio 2005-->visual studio remote tools-->"Remote Zoom In" as show in below PIC


2) Make sure to select which device or emulator you want to take the screen shot and in case of device make sure it is connected to PC via USB cable

3) Now you can see the application connecting to the emulator or device as shown in below PIc

4) Once the screen shot is processed you can see the image and save as option give the path usually the default format of the picture is BMP you can change the format by opening it in the paint and again saving it in your desired format

If there is any other hack or way to take the snap shot/ screen shot without using the tool do let us know

Friday, September 18, 2009

popup window in android sample program

Popup window is very tricky at least for beginners in android development, best example you can find the implementation in calendar module and you can get overall view if you can check the source code of calendar module week view in the class called "calendar view" and analyze methods "init" and "updateEventDetails" after searching for hours i finally found the major solution in the android calendar source code which is open source....

below is the shrinked sample snippet which worked for me of the popup window in android, write below code in keydown event or any method or tailor according to your needs and between we have to use viewinflate method for popup window


private PopupWindow Popup;
//how much time your popup window should appear
private static final int POPUP_DISMISS_DELAY = 4000
private DismissPopup mDismissPopup = new DismissPopup();




Popup = new PopupWindow(this.getViewInflate()
.inflate(R.layout.main1,null,null),0,0);
Popup.setOutsideTouchable(false);
Popup.setTouchInterceptor(new OnTouchListener() {

public boolean onTouch(View v, MotionEvent event) {
//your code when touched on the event
return false;
}

});

Popup.showAtLocation(this.findViewById(R.id.main2),Gravity.BOTTOM, 20, 20);
youractivity.postDelayed(mDismissPopup, POPUP_DISMISS_DELAY);


Create a class which helps in dismissing the window automatically after the specified time


class DismissPopup implements Runnable {
public void run() {
// Protect against null-pointer exceptions
if (mPopup != null) {
mPopup.dismiss();
}
}
}


Though the popup window is simple to implement but it needs few tries to make it work according to your needs, if there is any error in above snippet or you can improve the code then suggestions are appreciated

Tuesday, September 1, 2009

simple progress bar dialog in android with thread

below is the sample tutorial program to demonstrate a sample thread to display a progressbar in android.we just run the thread for a while and after that change the label to processing done we are using sleep here to emulate some useful operation just a add textview in the main.xml see the pic and below code increase the sleep value in case progress bar does not appear or closes too early to be viewed


public class ProgressDialogSample extends Activity implements Runnable {
private TextView txt;
private ProgressDialog progDailog;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);

txt = (TextView) this.findViewById(R.id.main);
txt.setText("Press any key to start Process");
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

progDailog = ProgressDialog.show(curContxt,
"Progress dialogue sample ", "ceveni.com please wait....",
true);
new Thread() {
public void run() {
try{
// just doing some long operation
sleep(5000);
} catch (Exception e) { }
handler.sendEmptyMessage(0);
progDailog.dismiss(); }
}.start();
}//

private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
txt.setText("Processing Done");

}
};

}

we are using Handler because we get a across thread exception if we handle UI elements from other thread to overcome this problem we can post to the handler once the job / processing is completed so that UI thread can execute the ui operations once the processing gets on the thread gets completed.

Thursday, August 20, 2009

Android gestures detection sample code

I recently wanted to implement all the gestures and motion detection in my project such as onFling (swipeup, swipe down), onLongPress, singletap, showpress context menu etc in android and after searching for a long while did not find any sample program that has all the methods as example mainly for onFling and so i made a sample program with all these see the below code

package testt.manju.com;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class gridd extends Activity implements OnGestureListener
{ private LinearLayout main; private TextView viewA;

private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;


private GestureDetector gestureScanner;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
gestureScanner = new GestureDetector(this);
main = new LinearLayout(this);
main.setBackgroundColor(Color.GRAY);
main.setLayoutParams(new LinearLayout.LayoutParams(320,480));
viewA = new TextView(this);
viewA.setBackgroundColor(Color.YELLOW);
viewA.setTextColor(Color.BLACK);
viewA.setTextSize(16);
viewA.setLayoutParams(new LinearLayout.LayoutParams(320,80));
main.addView(viewA);
setContentView(main);
}
@Override
public boolean onTouchEvent(MotionEvent me)
{
return gestureScanner.onTouchEvent(me);
}
@Override
public boolean onDown(MotionEvent e)
{
viewA.setText("-" + "DOWN" + "-");
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(getApplicationContext(), "Left Swipe", Toast.LENGTH_SHORT).show();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(getApplicationContext(), "Right Swipe", Toast.LENGTH_SHORT).show();
}
else if(e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(getApplicationContext(), "Swipe up", Toast.LENGTH_SHORT).show();
} else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(getApplicationContext(), "Swipe down", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// nothing
}

return true;
}
@Override
public void onLongPress(MotionEvent e)
{
Toast mToast = Toast.makeText(getApplicationContext(), "Long Press", Toast.LENGTH_SHORT);
mToast.show();
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
{
viewA.setText("-" + "SCROLL" + "-");
return true;
}
@Override
public void onShowPress(MotionEvent e)
{
viewA.setText("-" + "SHOW PRESS" + "-");
} @Override
public boolean onSingleTapUp(MotionEvent e) {
Toast mToast = Toast.makeText(getApplicationContext(), "Single Tap", Toast.LENGTH_SHORT);
mToast.show();
return true;
}
}

you can change the threshold, swipe distance and max swip path for onFling Method as per your requirements if the code working mail me or you can suggest improvements

Other Interesting Articles



Related Article Widget by ceveni

Search Powered by Google