File Read-Write Error in iOS - ios

I have used following code for file reading and writing.
private void StorePuzzleData ()
{
FileInfo fileInfo = new FileInfo (Application.persistentDataPath + "\\" + difficultyLevel + puzzleId + ".txt");
if (fileInfo.Exists)
fileInfo.Delete ();
string fileData = string.Empty;
foreach (CellInformation cellInfo in cellInfoList)
fileData += cellInfo.RowIndex + "#" + cellInfo.ColIndex + "#" + cellInfo.number + "#" + cellInfo.CellColor + "#" + cellInfo.CellDisplayColor + "#" + (cellInfo.IsGroupComplete ? 1 : 0) + ",";
StreamWriter streamWriter = fileInfo.CreateText ();
streamWriter.WriteLine (fileData);
streamWriter.Close ();
DataStorage.StorePuzzleTimePassed (difficultyLevel, puzzleId, GameController.gamePlayTime);
}
private void ReadPuzzleData ()
{
// format: rownumber, colnumber, number, cellcolor, celldisplaycolor, isgroupcomplete
StreamReader streamReader = File.OpenText (Application.persistentDataPath + "\\" + difficultyLevel + puzzleId + ".txt");
string fileData = streamReader.ReadLine ();
}
But I am getting following error in actual iOS device running. This code working correct in iMac as well in android device.
Please give me some suggestion what changes I need to do to make this correct.

It seems you're using Windows-style paths in a Unix-like (Apple Mac OS) environment. Notice that on windows you have paths with a backslash like
C:\Users\Maxi\Desktop
On Unix-like system however something like
/var/mobile/Containers
You notice that in your faulty path you have mixed forward and backward slashes, which makes the path invalid.
/var/mobile/Containers/Data/Application/2.....\debutan1.txt
The correct way to always generate the correct path is to use the Path.Combine(string, string) function. This will combine two paths using the correct directory path seperator, which can also be seperatly accessed through Path.DirectorySeparatorChar.
So, in order to make your code correct, you would do
using System.IO; /* must be imported */
private void StorePuzzleData ()
{
FileInfo fileInfo = new FileInfo (Path.Combine(Application.persistentDataPath, difficultyLevel + puzzleId + ".txt"));
if (fileInfo.Exists)
fileInfo.Delete ();
string fileData = string.Empty;
foreach (CellInformation cellInfo in cellInfoList)
fileData += cellInfo.RowIndex + "#" + cellInfo.ColIndex + "#" + cellInfo.number + "#" + cellInfo.CellColor + "#" + cellInfo.CellDisplayColor + "#" + (cellInfo.IsGroupComplete ? 1 : 0) + ",";
StreamWriter streamWriter = fileInfo.CreateText ();
streamWriter.WriteLine (fileData);
streamWriter.Close ();
DataStorage.StorePuzzleTimePassed (difficultyLevel, puzzleId, GameController.gamePlayTime);
}
private void ReadPuzzleData ()
{
// format: rownumber, colnumber, number, cellcolor, celldisplaycolor, isgroupcomplete
StreamReader streamReader = File.OpenText (Path.Combine(Application.persistentDataPath, difficultyLevel + puzzleId + ".txt"));
string fileData = streamReader.ReadLine ();
}
If this still gives an "Access denied" error it must be because of filepermissions. Post the output of ls -la <thatpath> then.

Related

Screenshot is not attached to the extend report when ran in Jenkins only

When using remote-webdriver instance of BrowserStack, only when ran in Jenkins, the failed screenshot is not attached to the report. please help. folder structure is ExtentReport\Screenshots
I tried Extent Report: Not able to see the screenshots on other machine
this but it's not resolve the issue.
public void onTestFailure(ITestResult result) {
testMap.get().fail(result.getThrowable());
//add screenshot for failed test.
WebDriver driver= WebDriverFactory.getDriver();
//experimental to get screenshot
driver = new Augmenter().augment(driver);
String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
String destination = System.getProperty("user.dir") + "/ExtentReport/" + "/Screenshots/" + result.getMethod().getMethodName() + dateName + ".png";
File finalDestination = new File(destination);
try {
FileUtils.copyFile(source, finalDestination);
} catch (IOException e) {
e.printStackTrace();
}
testMap.get().addScreenCaptureFromPath(destination,result.getMethod().getMethodName());
}
Different operating systems use different characters as file and path separators. When our application has to run on multiple platforms, we need to handle these correctly.
To handle this issue Java provide File.separator.
So, instead of
String destination = System.getProperty("user.dir") + "/ExtentReport/" + "/Screenshots/" + result.getMethod().getMethodName() + dateName + ".png";
Try this:
String destination = System.getProperty("user.dir") + File.separator + "ExtentReport" + File.separator +"Screenshots" + File.separator + result.getMethod().getMethodName() + dateName + ".png";
To use it you will have to add this import
import java.io.File;
Based on the answer of ravi creed,
HTML : Unable to view the base64 image in html report
String base64Screenshot ="data:image/png;base64," + ((TakesScreenshot) Objects.requireNonNull(driver)).getScreenshotAs(OutputType.BASE64);
testMap.get().addScreenCaptureFromBase64String(base64Screenshot).getModel().getMedia().get(0);
I managed to solve this using above code.Once click on base64 img, it opens the actual screenshot.

Directions API is not working on a physical device

I write an app on Xamarin.Android. Directions API works perfectly when debugging on emulator. But it doesn't work when testing on a physical device. I suppose the problem can be in http request. Is somebody familiar with such a problem?
public async Task<string> GetDirectionJsonAsync(LatLng location, LatLng destLocation, string mapkey)
{
// Origin of route
string str_origin = "origin=" + location.Latitude.ToString() + "," + location.Longitude.ToString();
// Destination of route
string str_destination = "destination=" + destLocation.Latitude.ToString() + "," + destLocation.Longitude.ToString();
// Mode
string mode = "mode=driving";
string parameters = str_origin + "&" + str_destination + "&" + mode + "&key=" + mapkey;
// Output
string output = "json";
string url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
var handler = new HttpClientHandler();
HttpClient client = new HttpClient(handler);
string jsonString = await client.GetStringAsync(url);
return jsonString;
}

Changing synchronous call to async await(Asynchronous ) MvC controller

I am new to C# Asp.net mvc asynchronous programming. I need to uplaod vidoe to my server but it video upload is locked when I uploading the video. I can not do another tasks in parallel. I have tried like this but it is not working.
public async Task<ActionResult> upload()
{
if (Request.Files.Count > 0)
{
int chunk = Request["chunk"] != null ?
int.Parse(Request["chunk"]) : 0;
string fileName = Request["name"] != null ? Request["name"] :
string.Empty;
string upath = "";
if (Request.Headers["UName"] != null)
upath = Request.Headers["UName"].ToString();
//if (CloudSettings.EnableCloudStorage && upath != "")
// _fileName = upath.Substring(0, 3) + "-" + _fileName; // void duplication in cloud storage
long AlbumID = 0;
if (Request.Headers["MediaID"] != null)
AlbumID = Convert.ToInt64(Request.Headers["MediaID"]);
string uploadPath = "";
// default path
if (upath == "")
uploadPath = UrlConfig.Published_Video_Path(); // direct upload to published area
else
uploadPath = UrlConfig.Published_Video_Path(upath); // source video path
FileStream fs;
using (fs = new FileStream(Path.Combine(uploadPath, fileName), chunk == 0 ? FileMode.Create : FileMode.Append))
{
byte[] buffer = new byte[Request.Files[0].InputStream.Length];
await Request.Files[0].InputStream.ReadAsync(buffer, 0, buffer.Length);
await fs.WriteAsync(buffer, 0, buffer.Length);
}
string url = "";
string filetype = System.IO.Path.GetExtension(fileName);
string fileIndex = fileName.Replace(filetype, "");
string elementid = UtilityBLL.ReplaceSpaceWithHyphin(fileIndex);
//eturn fileName; // "Success";
return this.Content("{\"jsonrpc\" : \"2.0\", \"result\" : \"OK\", \"id\" : \"id\", \"fname\" : \"" + fileName + "\", \"url\" : \"" + url + "\", \"filetype\" : \"" + filetype + "\", \"filename\" : \"" + fileName + "\", \"fileIndex\" : \"" + fileIndex + "\", \"eleid\" : \"" + elementid + "\"}", "text/plain");
}
else
{
return this.Content("failed", "text/plain");
}
}

How to check-out/check-in a file into a ClearCase snapshot view using an Ant script?

I would like to update a file under ClearCase source control. This needs to happen from an Ant script.
I have created a snapshot view for this purpose. ccupdate updates it just fine.
I have tried using cccheckout but it fails with the following error cleartool: Error: To operate on UCM branch, must be set to an activity and a UCM view..
Is there a way to check-out a file in a snapshot view, replace it and check-in the new version? If this involves creating/switching to an activity, please include this in your answer.
The Apache Ant ClearCase Tasks (2003!) are pre-UCM area.
That means they have no notion of "UCM view" (snapshot or dynamic) or activities.
If you are staying with ant, you could try (not tested) a tasks library like clearantlib, which allows you to execute any cleartool command (with ccexec)
That way you can use a cleartool setact in order to set a UCM activity in the UCM view.
Your checkout will proceed only when an activity is set.
As clearantlib is only a thin wrapper around cleartool command line, you're on your own. Following some snippet of production code for the 'checkout part', that might be helpful for writing your own ant task - otherwise you need to use a bunch of ant <exec> parts calling cleartool. Checkout specific versions in a clearcase snapshotview means create and set a configspec. For the update part use ProcessBuilder with the relevant cleartool commands :
/**
*
* #param modulinfos
* #param jobid
* #param snapshotpath
*/
private void createConfSpec(ArrayList<String> modulinfos, String jobid, String snapshotpath)
{
/*
element * CHECKEDOUT
element "/at_vobt2/Foo/.../" v_1_4_00_49a
element "/at_vobt2/FooBar/.../" v_1_3_02_06c
element "/at_vobt2/Foo Base/.../" v_1_3_01_28b
element * /main/LATEST
load "/vobt2/Foo"
load "/vobt2/FooBar"
load "/vobt2/FooBase"
*/
StringBuilder sb = new StringBuilder("element * CHECKEDOUT");
for (String string : modulinfos)
{
sb.append(nl).append("element \"/" + string.split("#")[0] + "/" + string.split("#")[1] + "/.../\" " + string.split("#")[2]);
}
sb.append(nl).append("element * /main/LATEST");
for (String string : modulinfos)
{
sb.append(nl).append("load \"/" + string.split("#")[0] + "/" + string.split("#")[1] + "\"");
}
sb.append(nl);
File file = new File(snapshotpath + "\\" + jobid + ".confspec");
BufferedWriter writer = null;
try
{
writer = new BufferedWriter(new FileWriter(file));
writer.write(sb.toString());
writer.close();
getLogger().debug("Create ConfigSpec : " + nl + sb.toString() + "File => " + file.getPath());
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* #param snapshotpath
* #return
* #throws IOException
*/
private boolean checkSnapshotView(String snapshotpath) throws IOException
{
boolean isReady = false;
// use pushd/popd cause cmd doesn't support UNC !
ProcessBuilder pb = new ProcessBuilder
(
"cmd", "/c",
"pushd " + snapshotpath + " && cleartool lsview -l -pro -cview && popd"
);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null)
{
sb.append(line).append(nl);
}
isReady = !StringUtils.containsIgnoreCase(sb.toString(), "cleartool: Error: Cannot get view info for current view");
getLogger().debug("Check Snapshotview : " + snapshotpath + nl + sb.toString());
return isReady;
}
/**
*
* #param jobid
* #param snapshotpath
* #throws IOException
*/
private void createSnapshotView(String jobid, String snapshotpath) throws IOException
{
ProcessBuilder pb = new ProcessBuilder
(
"cmd", "/c",
"cleartool mkview -snapshot -tag " + "snapshot" + jobid + " " + snapshotpath
);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null)
{
sb.append(line).append(nl);
}
getLogger().debug("Create Snapshotview : " + nl + sb.toString());
}
/**
*
* #param snapshotpath
* #param configspecpath
* #throws IOException
*/
private void setConfigSpec(String snapshotpath, String configspecpath) throws IOException
{
// use pushd/popd cause cmd doesn't support UNC !
ProcessBuilder pb = new ProcessBuilder
(
"cmd", "/c",
"pushd " + snapshotpath + " && cleartool setcs " + configspecpath + " && popd"
);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null)
{
sb.append(line).append(nl);
}
getLogger().debug("Update Snapshotview : " + nl + sb.toString());
}

Streaming mp4 videos from serversocket on AIR

I am trying to build a mini-webserver on an iPad inside an Adobe AIR application.
I am using the ServerSocket class to set up the webserver as shown by example at http://coenraets.org/blog/2010/07/creating-a-web-server-using-the-new-server-socket-api-in-air-2/.
I am trying to extend this by allowing the webserver to serve mp4 video files.
I have added the mimetype: mimeTypes[".mp4"] = "video/mp4";
but serving an mp4 to be played in a browser is not exactly the same as providing a html file.
Anyone can point me in the right direction for this? This is the code I currently have when the socket is responding:
private function webserverConnectionSocketDataHandler(evt:ProgressEvent):void{
try
{
var socket:Socket = evt.target as Socket;
var bytes:ByteArray = new ByteArray();
socket.readBytes(bytes);
var request:String = "" + bytes;
var filePath:String = request.substring(5, request.indexOf("HTTP/") - 1);
var file:File = File.applicationDirectory.resolvePath("AppStorage").resolvePath(filePath);
if (file.exists && !file.isDirectory)
{
//Range: bytes=0-131726
var offset:uint = 0;
var bytesRequested:uint = 0;
if(request.indexOf("Range: bytes=") >= 0){
offset = uint(request.split("Range: bytes=")[1].split("-")[0]);
bytesRequested = (request.split("Range: bytes=")[1].split("-")[1]);
}
if(bytesRequested == 0) bytesRequested = file.size;
var stream:FileStream = new FileStream();
stream.open( file, FileMode.READ );
var content:ByteArray = new ByteArray();
stream.readBytes(content, offset, bytesRequested);
stream.close();
if(bytesRequested != file.size){
socket.writeUTFBytes("HTTP/1.1 206 Partial Content\n");
socket.writeUTFBytes("Content-Type: " + getMimeType(filePath) + "\n\n");
socket.writeUTFBytes("Content-Range: " + offset + "-" + bytesRequested + "/" + file.size + "\n\n");
socket.writeUTFBytes("Content-Length: " + (bytesRequested-offset) + "\n\n");
socket.writeUTFBytes("Date: " + new Date().toLocaleTimeString() + "\n\n");
}else{
socket.writeUTFBytes("HTTP/1.1 200 OK\n");
socket.writeUTFBytes("Content-Type: " + getMimeType(filePath) + "\n\n");
socket.writeUTFBytes("Content-Length: " + file.size + "\n\n");
}
socket.writeBytes(content);
}
else
{
socket.writeUTFBytes("HTTP/1.1 404 Not Found\n");
socket.writeUTFBytes("Content-Type: text/html\n\n");
socket.writeUTFBytes("<html><body><h2>Page Not Found</h2></body></html>");
}
socket.flush();
socket.close();
}
catch (error:Error)
{
trace(error.message, "Error");
}
}
But that is not really working as expected. The goal is to be able to view an mp4 from inside my iPad application's AppStorage directory from inside my browser on PC. It works for html files, not for mp4.

Resources