How to invoke unit test a Print Event handler in c# - event-handling

I have below method which will get invoked when I call Print() method. I need to unit test the same. Is there any suggestions on how to do this?
internal PrintRemovalController(IApplicationContextHelper applicationContextHelper)
{
_applicationContextHelper = applicationContextHelper;
using (PrintDocument)
_printDocument.PrintPage += PrintDocument_PrintPage;
}
public void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
{
Font printFont = null;
try
{
PrintDetails pd;
do
{
pd = _printLines[_printPosition];
printFont = new Font("Courier New", 11, pd.Style);
if (pd.Text != "PAGE~~END")
e.Graphics.DrawString(pd.Text, printFont, Brushes.Black, pd.XPos, d.YPos);
_printPosition++;
}
while (pd.Text != "PAGE~~END");
e.HasMorePages = _printPosition < _printLines.Count;
}
finally
{
if (printFont != null)
printFont.Dispose();
}
}

Related

AutoCompleteTextField list does not always scroll to top?

The AutoCompleteTextField seems to work exactly as intended until I start backspacing in the TextField. I am not sure what the difference is, but if I type in something like "123 M" then I get values that start with "123 M". If I backspace and delete the M leaving "123 " in the field, the list changes, but it does not scroll to the top of the list.
I should note that everything works fine on the simulator and that I am experiencing this behavior when running a debug build on my iPhone.
EDIT: So this does not only seem to happen when backspacing. This image shows the results I have when typing in an address key by key. In any of the pictures where the list isn't viewable or is clipped, I am able to drag down on the list to get it to then display properly. I have not tried this on an Android device.
EDIT2:
public class CodenameOneTest {
private Form current;
private Resources theme;
private WaitingClass w;
private String[] properties = {"1 MAIN STREET", "123 E MAIN STREET", "12 EASTER ROAD", "24 MAIN STREET"};
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
}
public void start() {
if(current != null) {
current.show();
return;
}
Form form = new Form("AutoCompleteTextField");
form.setLayout(new BorderLayout());
final DefaultListModel<String> options = new DefaultListModel<>();
AutoCompleteTextField ac = new AutoCompleteTextField(options) {
protected boolean filter(String text) {
if(text.length() == 0) {
options.removeAll();
return false;
}
String[] l = searchLocations(text);
if(l == null || l.length == 0) {
return false;
}
options.removeAll();
for(String s : l) {
options.addItem(s);
}
return true;
};
};
Container container = new Container(BoxLayout.y());
container.setScrollableY(true); // If you comment this out then the field works fine
container.add(ac);
form.addComponent(BorderLayout.CENTER, container);
form.show();
}
String[] searchLocations(String text) {
try {
if(text.length() > 0) {
if(w != null) {
w.actionPerformed(null);
}
w = new WaitingClass();
String[] properties = getProperties(text);
if(Display.getInstance().isEdt()) {
Display.getInstance().invokeAndBlock(w);
}
else {
w.run();
}
return properties;
}
}
catch(Exception e) {
Log.e(e);
}
return null;
}
private String[] getProperties(String text) {
List<String> returnList = new ArrayList<>();
List<String> propertyList = Arrays.asList(properties);
for(String property : propertyList) {
if(property.startsWith(text)) {
returnList.add(property);
}
}
w.actionPerformed(null);
return returnList.toArray(new String[returnList.size()]);
}
class WaitingClass implements Runnable, ActionListener<ActionEvent> {
private boolean finishedWaiting;
public void run() {
while(!finishedWaiting) {
try {
Thread.sleep(30);
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
public void actionPerformed(ActionEvent e) {
finishedWaiting = true;
return;
}
}
public void stop() {
current = Display.getInstance().getCurrent();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = Display.getInstance().getCurrent();
}
}
public void destroy() {
}
}
I used this code on an iPhone 4s:
public void start() {
if(current != null){
current.show();
return;
}
Form hi = new Form("AutoComplete", new BorderLayout());
if(apiKey == null) {
hi.add(new SpanLabel("This demo requires a valid google API key to be set in the constant apiKey, "
+ "you can get this key for the webservice (not the native key) by following the instructions here: "
+ "https://developers.google.com/places/web-service/get-api-key"));
hi.getToolbar().addCommandToRightBar("Get Key", null, e -> Display.getInstance().execute("https://developers.google.com/places/web-service/get-api-key"));
hi.show();
return;
}
Container box = new Container(new BoxLayout(BoxLayout.Y_AXIS));
box.setScrollableY(true);
for(int iter = 0 ; iter < 30 ; iter++) {
box.add(createAutoComplete());
}
hi.add(BorderLayout.CENTER, box);
hi.show();
}
private AutoCompleteTextField createAutoComplete() {
final DefaultListModel<String> options = new DefaultListModel<>();
AutoCompleteTextField ac = new AutoCompleteTextField(options) {
#Override
protected boolean filter(String text) {
if(text.length() == 0) {
return false;
}
String[] l = searchLocations(text);
if(l == null || l.length == 0) {
return false;
}
options.removeAll();
for(String s : l) {
options.addItem(s);
}
return true;
}
};
ac.setMinimumElementsShownInPopup(5);
return ac;
}
String[] searchLocations(String text) {
try {
if(text.length() > 0) {
ConnectionRequest r = new ConnectionRequest();
r.setPost(false);
r.setUrl("https://maps.googleapis.com/maps/api/place/autocomplete/json");
r.addArgument("key", apiKey);
r.addArgument("input", text);
NetworkManager.getInstance().addToQueueAndWait(r);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
String[] res = Result.fromContent(result).getAsStringArray("//description");
return res;
}
} catch(Exception err) {
Log.e(err);
}
return null;
}
I was able to create this issue but not the issue you describe.

SharePoint Backup Tool for Custom Lists

I have a SharePoint 2013 document library with three custom lists.
Once a day I would like to backup the custom lists as excel documents.
Is there an inbuilt functionality in SharePoint 2013 which can be configured as a recurring task?
Or should one use PowerShell or CSOM to write script or an application which is then run by a Windows Task?
you dont have any OOB features to do this, i had the same req and i wrote an Utility - PFB the code - this will give you an o/p in .csv file
class Program
{
private static DataTable dataTable;
private static SPList list;
static void Main(string[] args)
{
try
{
Console.WriteLine("Site Url: ");
string _siteUrl = Console.ReadLine();
if (!string.IsNullOrEmpty(_siteUrl))
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(_siteUrl))
{
if (site != null)
{
SPWeb web = site.RootWeb;
if (web != null)
{
// Export List code segment
Console.WriteLine("List Name:");
string _listName = Console.ReadLine();
if (!string.IsNullOrEmpty(_listName))
{
list = web.Lists[_listName];
if (list != null)
{
dataTable = new DataTable();
//Adds Columns to SpreadSheet
InitializeExcel(list, dataTable);
string _schemaXML = list.DefaultView.ViewFields.SchemaXml;
if (list.Items != null && list.ItemCount > 0)
{
foreach (SPListItem _item in list.Items)
{
DataRow dr = dataTable.NewRow();
foreach (DataColumn _column in dataTable.Columns)
{
if (dataTable.Columns[_column.ColumnName] != null && _item[_column.ColumnName] != null)
{
dr[_column.ColumnName] = _item[_column.ColumnName].ToString();
}
}
dataTable.Rows.Add(dr);
}
}
}
}
System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
grid.HeaderStyle.Font.Bold = true;
grid.DataSource = dataTable;
grid.DataBind();
using (StreamWriter streamWriter = new StreamWriter("C:\\" + list.Title + ".xls", false, Encoding.UTF8))
{
using (HtmlTextWriter htmlTextWriter = new HtmlTextWriter(streamWriter))
{
grid.RenderControl(htmlTextWriter);
}
}
Console.WriteLine("File Created");
#endregion
}
}
}
});
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
Console.ReadLine();
}
// Create excel funution
public static void InitializeExcel(SPList list, DataTable _datatable)
{
if (list != null)
{
string _schemaXML = list.DefaultView.ViewFields.SchemaXml;
if (list.Items != null && list.ItemCount > 0)
{
foreach (SPListItem _item in list.Items)
{
foreach (SPField _itemField in _item.Fields)
{
if (_schemaXML.Contains(_itemField.InternalName))
{
if (_item[_itemField.InternalName] != null)
{
if (!_datatable.Columns.Contains(_itemField.InternalName))
{
_datatable.Columns.Add(new DataColumn(_itemField.StaticName, Type.GetType("System.String")));
}
}
}
}
}
}
}
}
}

Eclipse Plugin Creating a IJavaLineBreakpoint programmatically does not show method info in Breakpoints view

I'm creating a Eclipse plugin and I'm trying to create JavaLineBreakpoint using JDIDebugModel.
However, when a line breakpoint is created from the Java editor, it displays the Class name, the line number and the method name as the following image:
When the line breakpoint is created in the plugin the method name is replaced by the class name as follows:
The following is the code used to create the breakpoint.
Thank you.
IBreakpoint[] breakpoints = DebugPlugin.getDefault().getBreakpointManager().getBreakpoints();
if (breakpoints.length == 0) {
return null;
}
IJavaLineBreakpoint oldBreakpoint = null;
for (int i = 0; i < breakpoints.length; i++) {
IBreakpoint breakpoint = breakpoints[i];
if (breakpoint instanceof IJavaLineBreakpoint) {
oldBreakpoint = (IJavaLineBreakpoint)breakpoint;
break;
}
}
if (oldBreakpoint != null) {
Map newAttrMap = null;
IResource resource = null;
try {
IMarker marker = oldBreakpoint.getMarker();
if (marker != null && marker.exists()) {
newAttrMap = marker.getAttributes();
resource = marker.getResource();
}
} catch (CoreException ce) {
Activator.logError("SinfoniaCloudBreakpointItem - Contructor - Marker attributes not found", ce);
}
int lineNumber = -1;
try {
lineNumber = (Integer)newAttrMap.get(IMarker.LINE_NUMBER);
} catch (ClassCastException cce) {
} catch (NullPointerException ne) {
}
try {
JDIDebugModel.createLineBreakpoint(
resource,
oldBreakpoint.getTypeName(),
lineNumber, -1, -1, 0, true, newAttrMap);
oldBreakpoint.delete();
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

WP - How to constantly update my location

Currently my location not updating when I change it to different location via emulator. But it will change after I restart my application. This is what I write when the app launch
private void Application_Launching(object sender, LaunchingEventArgs e)
{
IsolatedStorageSettings Settings = IsolatedStorageSettings.ApplicationSettings;
GeoCoordinate DefaultLocation = new GeoCoordinate(-6.595139, 106.793801);
Library.GPSServices MyGPS;
if (!Settings.Contains("FirstLaunch") || (bool)Settings["FirstLaunch"] == true)
{
Settings["FirstLaunch"] = false;
Settings["LastLocation"] = DefaultLocation;
Settings["SearchRadius"] = 1;
}
//If key not exist OR key value was set to false, ask for permission to use location
if (!Settings.Contains("LocationService") || (bool)Settings["LocationService"] == false)
{
var result = MessageBox.Show(
"Jendela Bogor need to know your location to work correctly, do you want to allow it?",
"Allow access to your location?",
MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
Settings["LocationService"] = true;
MyGPS = new Library.GPSServices();
}
else
{
Settings["LocationService"] = false;
}
Settings.Save();
}
else if ((bool)Settings["LocationService"] == true)
{
MyGPS = new Library.GPSServices();
}
}
I store my location in my application setting IsolatedStorage with name Settings["LastLocation"]
How should I do to constantly update my location in the Background using MVVM Pattern (MVVM-Light) so my PushPin on map in the ThirdPageView always updated?
EDIT
public GPSServices()
{
if ((bool)Settings["LocationService"] == true)
{
if (_watcher == null)
{
_watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
_watcher.MovementThreshold = 20;
}
StartWatcher();
_watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
_watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
}
else if ((bool)Settings["LocationService"] == false)
{
StopWatcher();
}
}
private void StartWatcher()
{
_watcher.Start();
}
private void StopWatcher()
{
if (_watcher != null)
_watcher.Stop();
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
if (e.Position.Location.IsUnknown)
{
MessageBox.Show("Please wait while your position is determined....");
return;
}
Settings["LastLocation"] = e.Position.Location;
Settings.Save();
}
System.Device.Location.GeoCoordinateWatcher provides what you need.
var geoWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
// This event fires every time the device location changes
geoWatcher.PositionChanged += (s, e) => {
//e.Position.Location will contain the current GeoCoordinate
};
geoWatcher.TryStart(false, TimeSpan.FromMilliseconds(2000));
is this helpful for you ? using GeocoordinateWatcher.PositionChanged event?
public Location()
{
GeoCoordinateWatcher location == new GeoCoordinateWatcher();
location.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(location_PositionChanged);
location.Start();
}
//event to track the location change
public void location_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
}

my commands using lwuit not working properly ..

I am trying to move between 3 forms. 1 is main form and 2 other simple forms.
I have commands in the soft keys but they are not working...
below is my code...
public class checkOutComponents extends MIDlet implements ActionListener
{
private Form appForm;
private Form f1;
private Form f2;
Command GoTof1 = new Command("GoTof1");
Command GoTof2 = new Command("GoTof2");
Command GoToMainForm = new Command("GoToMainForm");
public void startApp()
{
Display.init(this);
appForm = new Form("Check These Components!! ");
appForm.setLayout(new BorderLayout());
appForm.addCommand(GoTof1);
appForm.addCommand(GoTof2);
appForm.addComponent(BorderLayout.CENTER, formContainer);
appForm.show();
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void actionPerformed(ActionEvent event)
{
Command eventCmd = event.getCommand();
Form f = Display.getInstance().getCurrent();
boolean sentido = false;
if (eventCmd == GoTof1)
{
sentido = true;
Image i1 = null;
try
{
i1 = Image.createImage("/hello/1.jpeg");
}
catch (IOException ex)
{
ex.printStackTrace();
}
Label lab1 = new Label(i1);
f1.addComponent(lab1);
f1.addCommand(GoTof2);
f1.addCommand(GoToMainForm);
f.setTransitionOutAnimator(Transition3D.createCube(300, sentido));
f1.show();
}
else if (eventCmd == GoTof2)
{
sentido = false;
Image i2 = null;
try
{
i2 = Image.createImage("/hello/2.jpeg");
}
catch (IOException ex)
{
ex.printStackTrace();
}
Label lab2 = new Label(i2);
f1.addComponent(lab2);
f1.addCommand(GoTof1);
f1.addCommand(GoToMainForm);
f.setTransitionOutAnimator(Transition3D.createCube(300, sentido));
f2.show();
}
else if(eventCmd == GoToMainForm)
{
appForm.showBack();
}
}
}
Kindly help regarding this.
Thanks in advance and regards,
Swati
Add command listener to the form appForm.
appForm.addCommandListener(this);