How to clear browser cache before every test run? I tried with driver.manage().deleteAllCookies(); in setUp method after creating the driver instance, it is working for firefox, but for IE no use. Is there any solution for IE please provide me..
There is a driver capability you can set as follows:
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
It worked for me on IE11.
Source:
http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/ie/InternetExplorerDriver.html
Use the below code to clear cache in IE
try {
Runtime.getRuntime().exec("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255");
} catch (IOException e) {
e.printStackTrace();
}
Using this post, How To: Execute command line in C#, get STD OUT results, I came up with this C# code to delete cookies (and as a side effect it deletes all IE browser data).
public static void DeleteIECookiesAndData()
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "RunDll32.exe";
p.StartInfo.Arguments = "InetCpl.cpl,ClearMyTracksByProcess 2";
p.Start();
p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
It isn't pretty at all, but it works. Maybe some pieces could be removed. (please let me know if you find a better way to do this).
IE Browser clears the cache for each element after every page load
ieCapabilities.setCapability(InternetExplorerDriver.ENABLE_ELEMENT_CACHE_CLEANUP, true);
This will do session clean up:
ieCapabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
Using java you can achieve that:
protected void deleteCookie(String cookieName) {
String cookieDomain = CTPropertiesManager.getProperty("site.properties", "site.cookie.domain");
try {
//get all cookies
Cookie cookies[] = request.getCookies();
Cookie ctCookie=null;
if (cookies !=null) {
for(int i=0; i<cookies.length; i++) {
ctCookie=cookies[i];
if (ctCookie.getName().trim().equals(cookieName)) {
if ( cookieDomain != null ) {
ctCookie.setDomain(cookieDomain);
}
ctCookie.setPath("/ct");
ctCookie.setMaxAge(0);
response.addCookie(ctCookie);
}
} //end for
}//end if cookie
} catch(Exception e) {
CTLogManager.log(e);
}
}//end deleteCookie()
For deleting cache
You can create one bat file which clear your browser or application cache before test start. after creating bat file just call in your code before test start.
Related
I created a class that connected to the API to retrieve the required data using httpclient. That file was called in the code behind file of the view and worked perfectly. Than I decided to implement the MVVM approach. As a result, I moved the code that initialized the rest service class to the view-model.
After doing that, i stopped getting the data. To investigate, I stated the the debugging session with the breakpoint placed at the line where i initialize the rest service class. Than i executed that line. By doing that, I found out that a huge android mono exception is thrown and the debugging session if stopped. The app exits the debugging session.
This has happened for the first time since i stated developing my app in Xamarin Forms. I have no idea about why it is breaking like that. Your help will be greatly appreciated.
This is the code that was working properly.
In the view code behind file
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SubtaskPage : ContentPage
{
protected override void OnAppearing()
{
base.OnAppearing();
PopulateSubtaskData();
}
private async void PopulateSubtaskData()
{
lstSubtasks.IsRefreshing = true;
try
{
RestService rs = new RestService();
SResponse = await rs.GetSubtasksAsync(Convert.ToInt32(Application.Current.Properties["UserId"]));
if (SResponse.Status == 1)
{
lstSubtasks.ItemsSource = SResponse.Subtasks;
}
else
{
await DisplayAlert("Error", SResponse.Message, "Ok");
}
}
catch (Exception E)
{
Debug.WriteLine(#"GetSubtasksAsync -> ERROR {0}", E.Message);
}
lstSubtasks.IsRefreshing = false;
}
}
The rest service class is as follows
This class is in a separate folder named "Services". ip and url have been changed for security reason.
class RestService
{
HttpClient client;
public List<Ticket> Tickets { get; private set; }
string Server1 = "server ip";
string Server2 = "server ip";
public RestService()
{
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
}
public async Task<SubtasksResponse> GetSubtasksAsync(int UserId)
{
SubtasksResponse SubtaskResponse = new SubtasksResponse();
string ApiUrl = "URL";
string Url = "";
HttpResponseMessage response;
if (CrossConnectivity.Current.IsConnected)
{
Url = await GetActiveServerAsync();
if (Url != "")
{
var uri = string.Format(Url + ApiUrl, UserId);
try
{
response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
SubtaskResponse.Subtasks = JsonConvert.DeserializeObject<List<Ticket>>(content);
SubtaskResponse.Status = 1;
}
else
{
SubtaskResponse.Subtasks = null;
SubtaskResponse.Status = 0;
SubtaskResponse.Message = "Attempt to fetch data from server was unsuccessful. Please try again";
}
}
catch (Exception E)
{
SubtaskResponse.Subtasks = null;
SubtaskResponse.Status = 0;
SubtaskResponse.Message = "Error occured while fetching data from the server. Please try again";
}
}
else
{
SubtaskResponse.Subtasks = null;
SubtaskResponse.Status = 0;
SubtaskResponse.Message = "Remote Server Not Responding! Please try again later";
}
}
else
{
SubtaskResponse.Subtasks = null;
SubtaskResponse.Status = 0;
SubtaskResponse.Message = "No Network Connection Found! Please connect to a network and try again";
}
return SubtaskResponse;
}
}
}
This was working fine until I added the view model into the mix.
This is how I am calling the function in the view model.
async Task<SubtasksResponse> PopulateSubtaskList()
{
RestService rs = new RestService();
IsBusy = true;
_subtaskList = await rs.GetSubtasksAsync(Convert.ToInt32(Application.Current.Properties["UserId"]));
IsBusy = false;
return _subtaskList;
}
"RestService rs = new RestService();" this is the line where the code breaks.
Here is the image of the exception that occurs when the code breaks.
Hope you get the clear picture of the situation. Please let me know if additional information is required.
Thanks
Don't do this. If you want to call rest from a mvvm Xamarin Forms app I can advice Refit. All the difficult work is already done for you and abstracted away. With a few lines of code you are up and running.
BTW the error message you are showing probably has nothing to do with your code but is a bug in a recent Xamarin version. See here: https://bugzilla.xamarin.com/show_bug.cgi?id=56787
Found the answer on this page (https://releases.xamarin.com/common-issues-in-the-xamarin-15-2-2-release-being-tracked-by-the-xamarin-team/).
The solution is as follows
Download the missing Mono.Posix file and unzip the archive.
Right-click the Mono.Posix.dll file in Explorer and select Properties.
Check the Digital Signatures tab to ensure the file shows a valid Xamarin Inc. signature.
At the bottom of the General tab, if an Unblock checkbox appears, enable it and select OK. (This checkbox appears depending on how the file was downloaded.)
For Visual Studio 2017, copy the Mono.Posix.dll file into the “Xamarin.VisualStudio” extension directory. For example, for a default installation of the Enterprise edition, copy the file into:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Extensions\Xamarin.VisualStudio
For Visual Studio 2015, copy the file into the “Xamarin\Xamarin” extension directory:
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Xamarin\Xamarin\
Quit and restart Visual Studio.
For more detail, visit the link given above.
I am using Telerik reports in our app and it is being accessed mostly through an RDP session running in "app mode". Everything works fine locally but when I put it on the TS machine it freezes after the print dialog comes up.
The standard print dialog comes up and you can choose the printer and hit ok but then a small box opens with header of Printing... and then never does anything.
I am not sure what code to post since its fine locally, let me know what you want to see. also printing other things like the Telerik grids and charts are fine.
Found the answer on my own.
I created a standard printdialog screen and "rolled my own" print method and all seems to be good. Hope this helps someone else.
private void reportViewer1_Print(object sender, CancelEventArgs e)
{
this.Cursor = Cursors.WaitCursor;
e.Cancel = true;
try
{
PrintDialog pd = new PrintDialog();
pd.PrinterSettings = new System.Drawing.Printing.PrinterSettings();
var result = pd.ShowDialog();
if (result ==DialogResult.OK)
{
// Print the report using the custom print controller
var reportProcessor
= new Telerik.Reporting.Processing.ReportProcessor();
reportProcessor.PrintReport(this.reportViewer1.ReportSource, pd.PrinterSettings);
}
}
catch (Exception ex)
{
Program.ExceptionHandler(ex);
}
this.Cursor = Cursors.Default;
}
I have a HP Scanjet 7000 (duplex & ADF scanner) and a HP Scanjet 5500c (only ADF) and a scanner program I'm developing which uses WIA 2.0 on Windows 7.
The problem is that the code works perfectly on the older scanner model, but on the newer one the code seems to run just fine through the first page, then fail on the second. If I step through the code around the following line;
image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatTIFF, false);
the old scanner stops and waits for another call to be made on the same reference, but the newer one just runs through all it's pages from the feeder in one continuous operation.
I notice if I'm using the default scanning program in Windows 7, the newer one returns a single .tif file which contains all the separate pages. The older one returns separate .jpg files (one for each page).
This indicates to me that the newer scanner is scanning through its whole feeder before it is ready to return a collection of images where the older one returns ONE image between each page scanned.
How can I support this behavior in code? The following is part of the relevant code which works on the older scanner model:
public static List<Image> Scan(string scannerId)
{
List<Image> images = new List<Image>();
List<String> tmp_imageList = new List<String>();
bool hasMorePages = true;
bool useAdf = true;
bool duplex = false;
int pages = 0;
string fileName = null;
string fileName_duplex = null;
WIA.DeviceManager manager = null;
WIA.Device device = null;
WIA.DeviceInfo device_infoHolder = null;
WIA.Item item = null;
WIA.ICommonDialog wiaCommonDialog = null;
manager = new WIA.DeviceManager();
// select the correct scanner using the provided scannerId parameter
foreach (WIA.DeviceInfo info in manager.DeviceInfos)
{
if (info.DeviceID == scannerId)
{
// Find scanner to connect to
device_infoHolder = info;
break;
}
}
while (hasMorePages)
{
wiaCommonDialog = new WIA.CommonDialog();
// Connect to scanner
device = device_infoHolder.Connect();
if (device.Items[1] != null)
{
item = device.Items[1] as WIA.Item;
try
{
if ((useAdf) || (duplex))
SetupADF(device, duplex); //Sets the right properties in WIA
WIA.ImageFile image = null;
WIA.ImageFile image_duplex = null;
// scan image
image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatTIFF, false);
if (duplex)
{
image_duplex = (ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatPNG, false);
}
// save (front) image to temp file
fileName = Path.GetTempFileName();
tmp_imageList.Add(fileName);
File.Delete(fileName);
image.SaveFile(fileName);
image = null;
// add file to images list
images.Add(Image.FromFile(fileName));
if (duplex)
{
fileName_duplex = Path.GetTempFileName();
tmp_imageList.Add(fileName_duplex);
File.Delete(fileName_duplex);
image_duplex.SaveFile(fileName_duplex);
image_duplex = null;
// add file_duplex to images list
images.Add(Image.FromFile(fileName_duplex));
}
if (useAdf || duplex)
{
hasMorePages = HasMorePages(device); //Returns true if the feeder has more pages
pages++;
}
}
catch (Exception exc)
{
throw exc;
}
finally
{
wiaCommonDialog = null;
manager = null;
item = null;
device = null;
}
}
}
device = null;
return images;
}
Any help on this issue would be very much appreciated! I can't seem to find a working solution on the web. Just unanswered forum posts from people with the same problem.
we had a very similar problem and various solutions, e.g. by setting certain properties, did not help. The main problem was that the scanner (ADF) retracted all pages on startup, regardless of what was happening in the program code.
The process repeatedly led to errors, since "too much" was made before the next page was scanned. This applies in particular to the fact that another "Connect" was attempted.
For this reason, we have modified the code so that the individual pages can be read in as quickly as possible:
public List<Image> Scan(string deviceID)
{
List<Image> images = new List<Image>();
WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
WIA.Device device = this.Connect(deviceID);
if (device == null)
return images;
WIA.Item item = device.Items[1] as WIA.Item;
List<WIA.ImageFile> wiaImages = new List<ImageFile>();
try
{
// scan images
do
{
WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatJPEG, false);
wiaImages.Add(image);
} while (true);
}
catch (System.Runtime.InteropServices.COMException ex)
{
if ((uint)ex.ErrorCode != WIA_PROPERTIES.WIA_ERROR_PAPER_EMPTY)
throw ex;
}
catch (Exception ex)
{
throw ex;
}
foreach (WIA.ImageFile image in wiaImages)
this.DoImage(images, image);
return images;
}
I see you're calling a method called SetupADF, which is not shown, that presumably sets some properties on the device object. Have you tried setting WIA_DPS_PAGES (property 3096) and/or WIA_DPS_SCAN_AHEAD_PAGES (property 3094)?
I have a blog post about scanning from an ADF in Silverlight, and I believe a commenter came up against the same issue you're having. Setting WIA_DPS_PAGES to 1 fixed it for him. I ended up modifying my code's SetDeviceProperties method to set WIA_DPS_PAGES to 1 and WIA_DPS_SCAN_AHEAD_PAGES to 0.
After alot of trial and error I stumbled upon a solution which worked for reasons I'm not quite sure of. It seems like the ShowTransfer() method was unable to convert the page to .png or .tiff WHILE scanning. Setting the format to JPEG or BMP actually solved the issue for me:
image = (ImageFile)scanDialog.ShowTransfer(item, wiaFormatJPEG, false);
I think I saw somewhere on the web that this method actually returns BMP regardless of the format specified. Might be that converting the image to png or tiff is too heavy as opposed to using bmp or jpeg.
On a sidenote, I'm setting the property setting: 3088 to 0x005 (adf AND duplex mode).
I want to add named data cache programmatically in appfabric.
I kept following code for this :-
try
{
//This can also be kept in a config file
var config = new DataCacheFactoryConfiguration();
config.SecurityProperties = new DataCacheSecurity();
config.Servers = new List<DataCacheServerEndpoint> { new DataCacheServerEndpoint(Environment.MachineName, 22233) };
DataCacheFactory dcf = new DataCacheFactory(config);
if (dcf != null)
{
var state = InitialSessionState.CreateDefault();
state.ImportPSModule(new string[] { "DistributedCacheAdministration", "DistributedCacheConfiguration" });
state.ThrowOnRunspaceOpenError = true;
var rs = RunspaceFactory.CreateRunspace(state);
rs.Open();
var pipe = rs.CreatePipeline();
pipe.Commands.Add(new Command("Use-CacheCluster"));
var cmd = new Command("New-Cache");
cmd.Parameters.Add(new CommandParameter("Name", "Vaibhav"));
cmd.Parameters.Add(new CommandParameter("Expirable", false));
pipe.Commands.Add(cmd);
var output = pipe.Invoke();
}
}
catch (Exception e)
{
//throw new Exception
}
But this is not working as expected when i try to access the DataCache (using: dcf.GetCache("Vaibhav");) it is giving Cache not found error. When i created the Cache using powershell it worked fine and i was able to access the Cache, but i want to implement this programmactically and not by Command Prompt(powershell)
Please suggest a proper way to implement this....
Thanks in Advance
Vaibhav
You actually have to Start the Visual Studio as admin to be able to create Cache programatically.
How do I open a custom control panel programmatically, like custom.cpl? Specifically, how do I open a 64-bit cpl when running as 32-bit application?
Vista added support for canonical names so you don't have to hard code dll filenames and tab indexs
Example:
WinExec("%systemroot%\system32\control.exe /name Microsoft.WindowsUpdate", SW_NORMAL);
(Names are always in english)
See MSDN for a list
XP/2000 supports "control.exe mouse" and a few other keywords, see the same MSDN page for a list (You can probably find some undocumented ones by running strings on control.exe)
Since I didn't find a good answer here on SO, here's the solution of my research:
Start a new application "control" that gets the name of the control panel as its first parameter:
::ShellExecute(m_hWnd, NULL, _T("control.exe"), _T("access.cpl"), NULL, SW_SHOW);
just use this....
ProcessStartInfo startInfo = new ProcessStartInfo("appwiz.cpl");
startInfo.UseShellExecute = true;
Process.Start(startInfo);
Step1 :
Read System Directory from the machine.
Step2 :
Use Process to start ControlPanel
**Process.Start(System.Environment.SystemDirectory + #"\appwiz.cpl");**
As i previously mentioned in another Question:
If you type "Start Control" or "Control" into Command Prompt it will open Control Panel.
Therefore just run a Process.
This Code (Bellow) worked perfectly for me:
public Form1()
{
InitializeComponent();
}
#region Variables
Process p;
#endregion Variables
[...]
void myMethod()
{
try
{
p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.Start();
p.StandardInput.WriteLine("start control");
p.StandardInput.Flush();
p.StandardInput.Close();
Console.WriteLine(p.StandardOutput.ReadToEnd());
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}