To automate file upload in oracle open script [OATS] - openscript

I am very new to Oracle Application Testing Suite(OATS).In my project I need to automate the file uploading functionality. That is , after clicking browse..button , file explorer will open.
My question is how to aytomate this scenario.
I serached many websites and in youtube but did not get any useful. Please help as it is important in my current project. Any help will be appreciated.

Most of file upload based on windows objects .
Open Script doesn't support windows based object identification for that we have to use external plugin or jar files
best suitable one is RobotClass .
Here is the complete example
http://www.testinghive.com/how-to-perform-file-upload-in-oats-tool/
try
{
Robot robot = new Robot();
robot.delay(200);
upload_parseChars("C:\\testDemo.xlsx", robot);
robot.delay(200);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
}
catch (AWTException e) {
e.printStackTrace();
}
public void upload_parseChars(String letter, Robot robot) throws AbstractScriptException {
for (int i = 0; i < letter.length(); i++) {
//info("inside uf_Vik_parseChars method ");
char chary = letter.charAt(i);
//info("Current character = "+letter.charAt(i));
upld_typeCharacter(Character.toString(chary), robot);
}
}
public void upld_typeCharacter(String letter, Robot robot) throws AbstractScriptException {
// info("Pressed event ");
if (Character.isLetterOrDigit(letter.charAt(0))) {
try {
boolean upperCase = Character.isUpperCase(letter.charAt(0));
String variableName = "VK_" + letter.toUpperCase();
KeyEvent ke = new KeyEvent(new JTextField(), 0, 0, 0, 0, ' ');
#SuppressWarnings("rawtypes")
Class clazz = ke.getClass();
Field field = clazz.getField(variableName);
int keyCode = field.getInt(ke);
robot.delay(80);
if (upperCase)
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(keyCode);
robot.keyRelease(keyCode);
if (upperCase)
robot.keyRelease(KeyEvent.VK_SHIFT);
} catch (Exception e) {
System.out.println(e);
}
} else {
if (letter.equals("!")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("#")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_2);
robot.keyRelease(KeyEvent.VK_2);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("#")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("#")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("$")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_4);
robot.keyRelease(KeyEvent.VK_4);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("%")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_5);
robot.keyRelease(KeyEvent.VK_5);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("^")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_6);
robot.keyRelease(KeyEvent.VK_6);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("&")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_7);
robot.keyRelease(KeyEvent.VK_7);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("*")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_8);
robot.keyRelease(KeyEvent.VK_8);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("=")) {
robot.keyPress(KeyEvent.VK_EQUALS);
robot.keyRelease(KeyEvent.VK_EQUALS);
} else if (letter.equals(" ")) {
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyRelease(KeyEvent.VK_SPACE);
} else if (letter.equals("/")) {
robot.keyPress(KeyEvent.VK_BACK_SLASH);
robot.keyRelease(KeyEvent.VK_BACK_SLASH);
} else if (letter.equals("\\")) {
robot.keyPress(KeyEvent.VK_BACK_SLASH);
robot.keyRelease(KeyEvent.VK_BACK_SLASH);
} else if (letter.equals("_")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals(":")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals(";")) {
robot.keyPress(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SEMICOLON);
} else if (letter.equals(",")) {
robot.keyPress(KeyEvent.VK_COMMA);
robot.keyRelease(KeyEvent.VK_COMMA);
} else if (letter.equals("-")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SUBTRACT);
robot.keyRelease(KeyEvent.VK_SUBTRACT);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("?")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SLASH);
robot.keyRelease(KeyEvent.VK_SLASH);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals(" ")) {
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyRelease(KeyEvent.VK_SPACE);
} else if (letter.equals(".")) {
robot.keyPress(KeyEvent.VK_PERIOD);
robot.keyRelease(KeyEvent.VK_PERIOD);
}
}
}

THE download dialog and upload dialog is supported. try to record one and try related

Related

How to initiate a Video call using lync sdk?

My Aim: I want to initiate a video call from the start.
My Problem: It is getting initiated into audio call and then it's turning into video after end user answers the call.
void ConversationManager_ConversationAdded_Video(object sender, ConversationManagerEventArgs e)
{
Console.WriteLine("Inside conversation added for Video");
if (e.Conversation.Modalities[ModalityTypes.AudioVideo].State != ModalityState.Notified)
{
if (e.Conversation.CanInvoke(ConversationAction.AddParticipant))
{
try
{
e.Conversation.ParticipantAdded += Conversation_ParticipantAdded_Video;
e.Conversation.AddParticipant(client.ContactManager.GetContactByUri(receipient));
}
catch (ItemAlreadyExistException ex)
{
}
}
}
}
void Conversation_ParticipantAdded_Video(object source, ParticipantCollectionChangedEventArgs data)
{
if (data.Participant.IsSelf != true)
{
if (((Conversation)source).Modalities[ModalityTypes.AudioVideo].CanInvoke(ModalityAction.Connect))
{
object[] asyncState = { ((Conversation)source).Modalities[ModalityTypes.AudioVideo], "CONNECT" };
try
{
((Conversation)source).Modalities[ModalityTypes.AudioVideo].ModalityStateChanged += _AVModality_ModalityStateChanged_Video;
Console.WriteLine("entered video Satheesh participant added");
// ((Conversation)source).Modalities[ModalityTypes.AudioVideo].BeginConnect(ModalityCallback, asyncState);
((Conversation)source).Modalities[ModalityTypes.AudioVideo].BeginConnect(ModalityCallback, asyncState);
//((Conversation)source).Modalities[ModalityTypes.AudioVideo].EndConnect(ModalityCallback, asyncState);
Thread.Sleep(6000);
Console.WriteLine(source);
Console.WriteLine("entered video participant added");
}
catch (LyncClientException lce)
{
throw new Exception("Lync Platform Exception on BeginConnect: " + lce.Message);
}
}
}
}
public void ModalityCallback(IAsyncResult ar)
{
Object[] asyncState = (Object[])ar.AsyncState;
try
{
if (ar.IsCompleted == true)
{
if (asyncState[1].ToString() == "RETRIEVE")
{
((AVModality)asyncState[0]).EndRetrieve(ar);
}
if (asyncState[1].ToString() == "HOLD")
{
((AVModality)asyncState[0]).EndHold(ar);
}
if (asyncState[1].ToString() == "CONNECT")
{
Console.WriteLine("inside connect method CONNECT");
((AVModality)asyncState[0]).EndConnect(ar);
}
if (asyncState[1].ToString() == "FORWARD")
{
((AVModality)asyncState[0]).EndForward(ar);
}
if (asyncState[1].ToString() == "ACCEPT")
{
((AVModality)asyncState[0]).Accept();
}
}
}
catch (LyncClientException)
{ }
}
public void _AVModality_ModalityStateChanged_Video(object sender, ModalityStateChangedEventArgs e)
{
Console.WriteLine(sender);
Console.WriteLine("entered video modality changed");
switch (e.NewState)
{
case ModalityState.Connected:
if (_VideoChannel == null)
{
_VideoChannel = ((AVModality)sender).VideoChannel;
_VideoChannel.StateChanged += new EventHandler<ChannelStateChangedEventArgs>(_VideoChannel_StateChanged);
}
if (_VideoChannel.CanInvoke(ChannelAction.Start))
{
Console.WriteLine("entered video modality changed123");
_VideoChannel.BeginStart(MediaChannelCallback, _VideoChannel);
}
break;
case ModalityState.OnHold:
break;
case ModalityState.Connecting:
case ModalityState.Forwarding:
break;
case ModalityState.Transferring:
break;
}
}
private void MediaChannelCallback(IAsyncResult ar)
{
((VideoChannel)ar.AsyncState).EndStart(ar);
}
I Think it is because you call _AVModality_ModalityStateChanged_Video in ParticipantAdded event.
that means that you start your video when the person you call (the new participant) joins the conversation. thats why it is getting initiated into audio call and then it's turning into video after end user answers the call.
The solution is to fire a new event : ConversationStateChangedEvent
this is where I did it and works fine :
/// <summary>
/// Handles event raised when New meetNow window change it's state
/// </summary>
private void _NewMeetNowConversation_StateChanged(object sender, ConversationStateChangedEventArgs e)
{
Conversation conference = (Conversation)sender;
switch(e.NewState)
{
case ConversationState.Active:
conference.Modalities[ModalityTypes.AudioVideo].ModalityStateChanged += AVConferenceModalityStateChanged;
conference.ParticipantAdded += ConfParticipantAdded;
break;
case ConversationState.Terminated: //conversation window completely closed
break;
case ConversationState.Inactive:
break;
case ConversationState.Parked:
break;
case ConversationState.Invalid:
break;
}
}

java.sql.SQLException: I/O Error: Socket closed

I want to sync data from MSSQL to android sqllite.All syncdata method write in ansync class.But sometime application return java.sql.SQLException: I/O Error: Socket closed error and not finish sync data . Sometime application successfully sync all update data.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
{
CheckProductGroupInfoHasNew();
CheckProductInfoHasNew();
CheckProductPriceInfoHasNew();
CheckCustomerInfoHasNew();
}
private void CheckProductInfoHasNew() {
AsyncSyncData _AsyncSyncData = new AsyncSyncData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
_AsyncSyncData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
"PC");
else
_AsyncSyncData.execute("PC");
}
private void CheckProductPriceInfoHasNew() {
AsyncSyncData _AsyncSyncData = new AsyncSyncData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
_AsyncSyncData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
"PPRICE");
else
_AsyncSyncData.execute("PPRICE");
}
private void CheckCustomerInfoHasNew() {
AsyncSyncData _AsyncSyncData = new AsyncSyncData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
_AsyncSyncData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
"CV");
else
_AsyncSyncData.execute("CV");
}
private void CheckProductGroupInfoHasNew() {
AsyncSyncData _AsyncSyncData = new AsyncSyncData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
_AsyncSyncData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
"PG");
else
_AsyncSyncData.execute("PG");
}
class AsyncSyncData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
if (params[0].toString().equals("PG")) {
_ListProductGroupInfo = _MSDBConnection
.SelectProductGroupInfo(_Query);}
} else if (params[0].equals("PC")) {
_ListProductInfo = _MSDBConnection
.SelectProductInfo(_Query);
} else if (params[0].equals("CV")) {
_ListCustomerInfo = _MSDBConnection
.SelectCustomerInfo(_Query);
} else if (params[0].equals("PPRICE")) {
_ListProductPriceInfo = _MSDBConnection
.SelectProductPriceInfo(_Query);
} else if (params[0].equals("VAT")) {
_ListCustomerInfo = _MSDBConnection
.SelectCustomerInfo(_Query);
}
#Override
protected void onPostExecute(String result) {
try {
if (result.equals("PG")) {
int _result = 0;
if ((_result = SyncProductGroupInfo()) > 0) {
Toast.makeText(
_context,
"Save Successfully .Product Group Data rows = "
+ _result, Toast.LENGTH_SHORT).show();
}
} else if (result.equals("PC")) {
int _result = 0;
if ((_result = SyncProductInfo()) > 0) {
Toast.makeText(
_context,
"Save Successfully .Product Data rows = "
+ _result, Toast.LENGTH_SHORT).show();
}
} else if (result.equals("PPRICE")) {
int _result = 0;
if ((_result = SyncProductPriceInfo()) > 0) {
Toast.makeText(
_context,
"Save Successfully .Product Price Data rows = "
+ _result, Toast.LENGTH_SHORT).show();
}
} else if (result.equals("CV")) {
int _result = 0;
if ((_result = SyncCustomerInfo()) > 0) {
Toast.makeText(
_context,
"Save Successfully .Customer Data rows = "
+ _result, Toast.LENGTH_SHORT).show();
}
HomeFragment.BindProductGroup();
SyncActivity.this.finish();
// close the progress dialog
progressDialog.dismiss();
} else if (result.equals("VAT")) {
if (SyncVatInfo()) {
Toast.makeText(_context, "Save Successfully Vat Data",
Toast.LENGTH_SHORT).show();
}
SyncActivity.this.finish();
// close the progress dialog
progressDialog.dismiss();
}
} catch (Exception ex) {
Log.i("onPostExecute Ex",
" Chan I'm onPostExecute" + ex.getMessage());
ex.printStackTrace();
Toast.makeText(_context, ex.getMessage().toString(),
Toast.LENGTH_LONG).show();
SyncActivity.this.finish();
// close the progress dialog
progressDialog.dismiss();
} finally {
}
}

How to persist IsolatedStorageSettings after terminate the application

How to retain the saved isolatedstoragesettings while at application launch
I used exception for termination on backevents :
protected void _BackKeyPress(object sender, CancelEventArgs e)
{
if (MessageBox.Show("Do you want to close the application?", "Q", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
{
e.Cancel = true;
System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Add("key2", "33r4 ");
}
else
{
if (IsolatedStorageSettings.ApplicationSettings.Contains("Key"))
{
IsolatedStorageSettings.ApplicationSettings["Key"] = App.Current.ViewModel;
}
else
{
IsolatedStorageSettings.ApplicationSettings.Add("Key", App.Current.ViewModel);
}
throw new Exception("ExitApplication");
}
}
I try to save the viewmodel which declares in app.xaml.cs, but cant able to get the isolatedstorage settings value in it, at launch. But It compiles and run successfully.
You need to call the IsolatedStorageSettings.Save method:
protected void _BackKeyPress(object sender, CancelEventArgs e)
{
if (MessageBox.Show("Do you want to close the application?", "Q", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
{
e.Cancel = true;
System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Add("key2", "33r4 ");
IsolatedStorageSettings.Save();
}
else
{
if (IsolatedStorageSettings.ApplicationSettings.Contains("Key"))
{
IsolatedStorageSettings.ApplicationSettings["Key"] = App.Current.ViewModel;
}
else
{
IsolatedStorageSettings.ApplicationSettings.Add("Key", App.Current.ViewModel);
}
IsolatedStorageSettings.Save();
throw new Exception("ExitApplication");
}
}

Camera Problems

I have run into a few problems when trying to get the camera to work accordingly... The camera Demo Works on the 8520 device (Has a memory Card) but does not work on the 9780 device (Has No Memory Card) the error given
ERROR Class java.lang.ArrayOutOfBoundsException :index 0>=0
My code Sample:
public class MyScreen extends MainScreen{
Player _p;
VideoControl _videoControl;
FileConnection fileconn;
String PATH;
String GetfileName;
LabelField GetPhotofileName = new LabelField("",LabelField.FOCUSABLE){
protected boolean navigationClick(int status, int time){
Dialog.alert("Clicked");
return true;
}
};
public static boolean SdcardAvailabulity() {
String root = null;
Enumeration e = FileSystemRegistry.listRoots();
while (e.hasMoreElements()) {
root = (String) e.nextElement();
if( root.equalsIgnoreCase("sdcard/") ) {
}else if( root.equalsIgnoreCase("store/") ) {
}
}
class MySDListener implements FileSystemListener {
public void rootChanged(int state, String rootName) {
if( state == ROOT_ADDED ) {
if( rootName.equalsIgnoreCase("sdcard/") ) {
}
} else if( state == ROOT_REMOVED ) {
}
}
}
return true;
}
protected boolean invokeAction(int action){
boolean handled = super.invokeAction(action);
if(SdcardAvailabulity()){
PATH = System.getProperty("fileconn.dir.memorycard.photos")+"Image_"+System.currentTimeMillis()+".jpg";//here "str" having the current Date and Time;
} else {
// PATH = System.getProperty("file:///store/home/user/pictures/")+"Image_"+System.currentTimeMillis()+".jpg";
PATH = System.getProperty("fileconn.dir.photos")+"Image_"+System.currentTimeMillis()+".jpg";
}
if(!handled){
if(action == ACTION_INVOKE){
try{
byte[] rawImage = _videoControl.getSnapshot(null);
System.out.println("----------1");
fileconn=(FileConnection)Connector.open(PATH);
System.out.println("----------2");
if(fileconn.exists()){
fileconn.delete();
System.out.println("----------3");
}
fileconn.create();
System.out.println("----------4");
OutputStream os=fileconn.openOutputStream();
System.out.println("----------5");
os.write(rawImage);
GetfileName =fileconn.getName();
System.out.println("----------6");
System.out.println("GetfileName----------"+GetfileName);
fileconn.close();
System.out.println("----------7");
os.close();
Status.show("Image is Captured",200);
GetPhotofileName.setText(GetfileName);
System.out.println("----------8");
if(_p!=null)
_p.close();
System.out.println("----------9");
}catch(Exception e){
if(_p!=null){
_p.close();
}
if(fileconn!=null){
try{
fileconn.close();
}catch (IOException e1){
//if the action is other than click the trackwheel(means go to the menu options) then we do nothing;
}
}
}
}
}
return handled;
}
public MyScreen(){
setTitle("Camera App");
try{
System.out.println("Debug------------10");
_p = javax.microedition.media.Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
_p.realize();
_videoControl = (VideoControl) _p.getControl("VideoControl");
System.out.println("Debug------------11");
if (_videoControl != null){
Field videoField = (Field) _videoControl.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
_videoControl.setDisplayFullScreen(true);
System.out.println("Debug------------12");
_videoControl.setVisible(true);
_p.start();
System.out.println("Debug------------13");
if(videoField != null){
add(videoField);
System.out.println("Debug------------14");
}
}
}catch(Exception e){
if(_p!=null) {
_p.close();
}
Dialog.alert(e.toString());
}
add(GetPhotofileName);
}
}
on the 8520 (Has a Memory Card) the code works fine on the 9780 (Has no Memory Card) the the code stops at "System.out.println("debug---1")", can anyone please tell me if you can see any problem with my code???
public static boolean SdcardAvailabulity() {
String root = null;
Enumeration e = FileSystemRegistry.listRoots();
while (e.hasMoreElements()) {
root = (String) e.nextElement();
if( root.equalsIgnoreCase("sdcard/") ) {
return true;
}else if( root.equalsIgnoreCase("store/") ) {
return false;
}
}
class MySDListener implements FileSystemListener {
public void rootChanged(int state, String rootName) {
if( state == ROOT_ADDED ) {
if( rootName.equalsIgnoreCase("sdcard/") ) {
}
} else if( state == ROOT_REMOVED ) {
}
}
}
return true;
}
This is the sollution, My "SD card availability" code only returned true which caused the picture not to save when the blackberry had no memory card inserted. # Eugen Martynov Please read through the code and you will see it is there :)

Refactor nested IF statement for clarity [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I want to refactor this mumbo jumbo of a method to make it more readible, it has way to many nested IF's for my liking.
How would you refactor this?
public static void HandleUploadedFile(string filename)
{
try
{
if(IsValidFileFormat(filename)
{
int folderID = GetFolderIDFromFilename(filename);
if(folderID > 0)
{
if(HasNoViruses(filename)
{
if(VerifyFileSize(filename)
{
// file is OK
MoveToSafeFolder(filename);
}
else
{
DeleteFile(filename);
LogError("file size invalid");
}
}
else
{
DeleteFile(filename);
LogError("failed virus test");
}
}
else
{
DeleteFile(filename);
LogError("invalid folder ID");
}
}
else
{
DeleteFile(filename);
LogError("invalid file format");
}
}
catch (Exception ex)
{
LogError("unknown error", ex.Message);
}
finally
{
// do some things
}
}
I would reverse the conditions in the test to if bad then deleteAndLog as the example below. This prevent nesting and puts the action near the test.
try{
if(IsValidFileFormat(filename) == false){
DeleteFile(filename);
LogError("invalid file format");
return;
}
int folderID = GetFolderIDFromFilename(filename);
if(folderID <= 0){
DeleteFile(filename);
LogError("invalid folder ID");
return;
}
...
}...
Guard clauses.
For each condition, negate it, change the else block into the then block, and return.
Thus
if(IsValidFileFormat(filename)
{
// then
}
else
{
// else
}
Becomes:
if(!IsValidFileFormat(filename)
{
// else
return;
}
// then
If you are not against using exceptions, you could handle the checks without nesting.
Warning, air code ahead:
public static void HandleUploadedFile(string filename)
{
try
{
int folderID = GetFolderIDFromFilename(filename);
if (folderID == 0)
throw new InvalidFolderException("invalid folder ID");
if (!IsValidFileFormat(filename))
throw new InvalidFileException("invalid file format!");
if (!HasNoViruses(filename))
throw new VirusFoundException("failed virus test!");
if (!VerifyFileSize(filename))
throw new InvalidFileSizeException("file size invalid");
// file is OK
MoveToSafeFolder(filename);
}
catch (Exception ex)
{
DeleteFile(filename);
LogError(ex.message);
}
finally
{
// do some things
}
}
One possible approach is to have single if statements that check for when the condition isn't true. Have a return for each one of these checks. This turns your method into a sequence of 'if' blocks instead of a nest.
There's not a lot to refactor here, as you keep the 3 tests separately due to the fact that the error messages relate to the test performed. You could opt for having the test methods report back the error to log so you don't have them in the if/else tree, which could make things simpler abit as you then could simply test for an error and log it + delete the file.
In David Waters reply, I don't like the repeated DeleteFile LogError pattern. I would either write a helper method called DeleteFileAndLog(string file, string error) or I would write the code like this:
public static void HandleUploadedFile(string filename)
{
try
{
string errorMessage = TestForInvalidFile(filename);
if (errorMessage != null)
{
LogError(errorMessage);
DeleteFile(filename);
}
else
{
MoveToSafeFolder(filename);
}
}
catch (Exception err)
{
LogError(err.Message);
DeleteFile(filename);
}
finally { /* */ }
}
private static string TestForInvalidFile(filename)
{
if (!IsValidFormat(filename))
return "invalid file format.";
if (!IsValidFolder(filename))
return "invalid folder.";
if (!IsVirusFree(filename))
return "has viruses";
if (!IsValidSize(filename))
return "invalid size.";
// ... etc ...
return null;
}
It's the elses above that throw my eye. Here's an alternative, inside the try {}
You can make this even shorter by returning after MoveToSafeFolder (Even though you're returning the finally block will be executed.) Then you don't need to assign an empty string to errorMessage, and you don't need to check is errorString empty before deleting the file and logging the message). I didn't do it here because many find early returns offensive, and I'd agree in this instance, since having the finally block execute after the return is unintuitive for many people.
Hope this helps
string errorMessage = "invalid file format";
if (IsValidFileFormat(filename))
{
errorMessage = "invalid folder ID";
int folderID = GetFolderIDFromFilename(filename);
if (folderID > 0)
{
errorMessage = "failed virus test";
if (HasNoViruses(filename))
{
errorMessage = "file size invalid";
if (VerifyFileSize(filename))
{
// file is OK
MoveToSafeFolder(filename);
errorMessage = "";
}
}
}
}
if (!string.IsNullOrEmpty(errorMessage))
{
DeleteFile(filename);
LogError(errorMessage);
}
I would to something like this:
public enum FileStates {
MoveToSafeFolder = 1,
InvalidFileSize = 2,
FailedVirusTest = 3,
InvalidFolderID = 4,
InvalidFileFormat = 5,
}
public static void HandleUploadedFile(string filename) {
try {
switch (Handledoc(filename)) {
case FileStates.FailedVirusTest:
deletefile(filename);
logerror("Virus");
break;
case FileStates.InvalidFileFormat:
deletefile(filename);
logerror("Invalid File format");
break;
case FileStates.InvalidFileSize:
deletefile(filename);
logerror("Invalid File Size");
break;
case FileStates.InvalidFolderID:
deletefile(filename);
logerror("Invalid Folder ID");
break;
case FileStates.MoveToSafeFolder:
MoveToSafeFolder(filename);
break;
}
}
catch (Exception ex) {
logerror("unknown error", ex.Message);
}
}
private static FileStates Handledoc(string filename) {
if (isvalidfileformat(filename)) {
return FileStates.InvalidFileFormat;
}
if ((getfolderidfromfilename(filename) <= 0)) {
return FileStates.InvalidFolderID;
}
if ((HasNoViruses(filename) == false)) {
return FileStates.FailedVirusTest;
}
if ((VerifyFileSize(filename) == false)) {
return FileStates.InvalidFileSize;
}
return FileStates.MoveToSafeFolder;
}
How about this?
public static void HandleUploadedFile(string filename)
{
try
{
if(!IsValidFileFormat(filename))
{ DeleteAndLog(filename, "invalid file format"); return; }
if(GetFolderIDFromFilename(filename)==0)
{ DeleteAndLog(filename, "invalid folder ID"); return; }
if(!HasNoViruses(filename))
{ DeleteAndLog(filename, "failed virus test"); return; }
if(!!VerifyFileSize(filename))
{ DeleteAndLog(filename, "file size invalid"); return; }
// --------------------------------------------------------
MoveToSafeFolder(filename);
}
catch (Exception ex) { LogError("unknown error", ex.Message); throw; }
finally { // do some things }
}
private void DeleteAndLog(string fileName, string logMessage)
{
DeleteFile(fileName);
LogError(logMessage));
}
or, even better, ... this:
public static void HandleUploadedFile(string filename)
{
try
{
if(ValidateUploadedFile(filename))
MoveToSafeFolder(filename);
}
catch (Exception ex) { LogError("unknown error", ex.Message); throw; }
finally { // do some things }
}
private bool ValidateUploadedFile(string fileName)
{
if(!IsValidFileFormat(filename))
{ DeleteAndLog(filename, "invalid file format"); return false; }
if(GetFolderIDFromFilename(filename)==0)
{ DeleteAndLog(filename, "invalid folder ID"); return false; }
if(!HasNoViruses(filename))
{ DeleteAndLog(filename, "failed virus test"); return false; }
if(!!VerifyFileSize(filename))
{ DeleteAndLog(filename, "file size invalid"); return false; }
// ---------------------------------------------------------------
return true;
}
private void DeleteAndLog(string fileName, string logMessage)
{
DeleteFile(fileName);
LogError(logMessage));
}
NOTE: You shouldn't be catching and swallowing generic Exception without rethrowing it...

Resources