/// <summary>Call this after all the data has been added.</summary> /// <remarks>Call this after all the data has been added.</remarks> public virtual void Finish() { try { outStream.Close(); } catch (IOException e) { Log.W(Database.Tag, "Exception closing output stream", e); } blobKey = new BlobKey(sha1Digest.Digest()); md5DigestResult = md5Digest.Digest(); }
/// <summary> /// 解压文件 /// </summary> /// <param name="inputZip"></param> /// <param name="destinationDirectory"></param> public static void UnzipFile(string inputZip, string destinationDirectory) { int buffer = 2048; List <string> zipFiles = new List <string>(); File sourceZipFile = new File(inputZip); File unzipDirectory = new File(destinationDirectory); CreateDir(unzipDirectory.AbsolutePath); ZipFile zipFile; zipFile = new ZipFile(sourceZipFile, ZipFile.OpenRead); IEnumeration zipFileEntries = zipFile.Entries(); while (zipFileEntries.HasMoreElements) { ZipEntry entry = (ZipEntry)zipFileEntries.NextElement(); string currentEntry = entry.Name; File destFile = new File(unzipDirectory, currentEntry); if (currentEntry.EndsWith(Constant.SUFFIX_ZIP)) { zipFiles.Add(destFile.AbsolutePath); } File destinationParent = destFile.ParentFile; CreateDir(destinationParent.AbsolutePath); if (!entry.IsDirectory) { if (destFile != null && destFile.Exists()) { continue; } BufferedInputStream inputStream = new BufferedInputStream(zipFile.GetInputStream(entry)); int currentByte; // buffer for writing file byte[] data = new byte[buffer]; var fos = new System.IO.FileStream(destFile.AbsolutePath, System.IO.FileMode.OpenOrCreate); BufferedOutputStream dest = new BufferedOutputStream(fos, buffer); while ((currentByte = inputStream.Read(data, 0, buffer)) != -1) { dest.Write(data, 0, currentByte); } dest.Flush(); dest.Close(); inputStream.Close(); } } zipFile.Close(); foreach (var zipName in zipFiles) { UnzipFile(zipName, destinationDirectory + File.SeparatorChar + zipName.Substring(0, zipName.LastIndexOf(Constant.SUFFIX_ZIP))); } }
private Object Post(string parameters) { try { conn = (HttpURLConnection)url.OpenConnection(); conn.RequestMethod = "POST"; conn.DoOutput = true; conn.DoInput = true; conn.Connect(); Android.Util.Log.Debug("SendToServer", "parametros " + parameters); byte[] bytes = Encoding.ASCII.GetBytes(parameters); OutputStream outputStream = new BufferedOutputStream(conn.OutputStream); outputStream.Write(bytes); outputStream.Flush(); outputStream.Close(); InputStream inputStream = new BufferedInputStream(conn.InputStream); return(ReadString(inputStream)); } catch (IOException e) { Android.Util.Log.Debug("SendToServer", "Problems to send data to server!! " + e.Message); return(false); } finally { conn.Disconnect(); } }
/** * Writes the chunks to a file as a contiguous stream. Useful for debugging. */ public void saveToFile(string path) { System.IO.FileStream fos = null; BufferedOutputStream bos = null; try { fos = new System.IO.FileStream(path, System.IO.FileMode.Create); bos = new BufferedOutputStream(fos); fos = null; // closing bos will also close fos int numChunks = NumChunks; for (int i = 0; i < numChunks; i++) { byte[] chunk = _chunks[i]; bos.Write(chunk); } } catch (System.IO.IOException) { //throw new RuntimeException(ioe); } finally { try { if (bos != null) { bos.Close(); } if (fos != null) { fos.Close(); } } catch (System.IO.IOException) { //throw new RuntimeException(ioe); } } }
/// <exception cref="System.IO.IOException"></exception> private static void Write(FilePath[] files, PackWriter pw) { long begin = files[0].GetParentFile().LastModified(); NullProgressMonitor m = NullProgressMonitor.INSTANCE; OutputStream @out; @out = new BufferedOutputStream(new FileOutputStream(files[0])); try { pw.WritePack(m, m, @out); } finally { @out.Close(); } @out = new BufferedOutputStream(new FileOutputStream(files[1])); try { pw.WriteIndex(@out); } finally { @out.Close(); } Touch(begin, files[0].GetParentFile()); }
public static void saveDecFile(byte[] encodedBytes, String path, string fileName) { try { System.IO.File.Copy(path, "/storage/emulated/0/movies/" + fileName); Java.IO.File file = new Java.IO.File(path); System.IO.FileStream fs = new System.IO.FileStream("/storage/emulated/0/movies/" + fileName, FileMode.Open); BufferedOutputStream bos = new BufferedOutputStream(fs); bos.Write(encodedBytes); bos.Flush(); bos.Close(); } catch (Java.IO.FileNotFoundException e) { e.PrintStackTrace(); } catch (Java.IO.IOException e) { e.PrintStackTrace(); } catch (Exception e) { // e.PrintStackTrace(); } }
/// <exception cref="System.IO.IOException"></exception> protected virtual void Copy(Socket4Adapter sock, IOutputStream rawout, int length , bool update) { var @out = new BufferedOutputStream(rawout); var buffer = new byte[BlobImpl.CopybufferLength]; var totalread = 0; while (totalread < length) { var stilltoread = length - totalread; var readsize = (stilltoread < buffer.Length ? stilltoread : buffer.Length); var curread = sock.Read(buffer, 0, readsize); if (curread < 0) { throw new IOException(); } @out.Write(buffer, 0, curread); totalread += curread; if (update) { _currentByte += curread; } } @out.Flush(); @out.Close(); }
private static string getData() { StringBuffer response = null; URL obj = new URL("http://192.168.1.17/easyserver/WebService.php"); switch (mFunction) { case "setUser": data = "function=" + URLEncoder.Encode(mFunction, "UTF-8") + "&name=" + URLEncoder.Encode(mName, "UTF-8") + "&age=" + URLEncoder.Encode(mAge, "UTF-8"); break; case "getUser": data = "function=" + URLEncoder.Encode(mFunction, "UTF-8"); break; } //creación del objeto de conexión HttpURLConnection con = (HttpURLConnection)obj.OpenConnection(); //Agregando la cabecera //Enviamos la petición por post con.RequestMethod = "POST"; con.DoOutput = true; con.DoInput = true; con.SetRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //Envio de datos //obtener el tamaño de los datos con.SetFixedLengthStreamingMode(data.Length); /* * OutputStream clase abstracta que es la superclase de todas las clases que * representan la salida de un flujo de bytes. Un flujo de salida acepta bytes de salida. * BufferOutputStream es la clase que implementa un flujo de salida con buffer */ OutputStream ouT = new BufferedOutputStream(con.OutputStream); byte[] array = Encoding.ASCII.GetBytes(data); ouT.Write(array); ouT.Flush(); ouT.Close(); /* * Obteniendo datos * BufferedRead Lee texto de una corriente de caracteres de entrada, * Un InputStreamReader es un puente de flujos de streams de caracteres: se lee los * bytes y los decodifica en caracteres */ BufferedReader iN = new BufferedReader(new InputStreamReader(con.InputStream)); string inputLine; response = new StringBuffer(); while ((inputLine = iN.ReadLine()) != null) { response.Append(inputLine); } iN.Close(); return(response.ToString()); }
public override double Evaluate(double[] x) { double score; // initialized below SetValues(x); if (GetCmd() != null) { EvaluateCmd(GetCmd()); score = InterpretCmdOutput(); } else { try { // TODO: Classify in memory instead of writing to tmp file File f = File.CreateTempFile("CRFClassifierEvaluator", "txt"); f.DeleteOnExit(); OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(f)); PrintWriter pw = IOUtils.EncodedOutputStreamPrintWriter(outputStream, null, true); classifier.ClassifyAndWriteAnswers(data, featurizedData, pw, classifier.MakeReaderAndWriter()); outputStream.Close(); BufferedReader br = new BufferedReader(new FileReader(f)); MultiClassChunkEvalStats stats = new MultiClassChunkEvalStats("O"); score = stats.Score(br, "\t"); log.Info(stats.GetConllEvalString()); f.Delete(); } catch (Exception ex) { throw new Exception(ex); } } return(score); }
/// <exception cref="System.IO.IOException"/> private static void WriteToIndexFile(string logLocation, bool isCleanup) { lock (typeof(TaskLog)) { // To ensure atomicity of updates to index file, write to temporary index // file first and then rename. FilePath tmpIndexFile = GetTmpIndexFile(currentTaskid, isCleanup); BufferedOutputStream bos = null; DataOutputStream dos = null; try { bos = new BufferedOutputStream(SecureIOUtils.CreateForWrite(tmpIndexFile, 0x1a4)); dos = new DataOutputStream(bos); //the format of the index file is //LOG_DIR: <the dir where the task logs are really stored> //STDOUT: <start-offset in the stdout file> <length> //STDERR: <start-offset in the stderr file> <length> //SYSLOG: <start-offset in the syslog file> <length> dos.WriteBytes(TaskLog.LogFileDetail.Location + logLocation + "\n" + TaskLog.LogName .Stdout.ToString() + ":"); dos.WriteBytes(System.Convert.ToString(prevOutLength) + " "); dos.WriteBytes(System.Convert.ToString(new FilePath(logLocation, TaskLog.LogName. Stdout.ToString()).Length() - prevOutLength) + "\n" + TaskLog.LogName.Stderr + ":" ); dos.WriteBytes(System.Convert.ToString(prevErrLength) + " "); dos.WriteBytes(System.Convert.ToString(new FilePath(logLocation, TaskLog.LogName. Stderr.ToString()).Length() - prevErrLength) + "\n" + TaskLog.LogName.Syslog.ToString () + ":"); dos.WriteBytes(System.Convert.ToString(prevLogLength) + " "); dos.WriteBytes(System.Convert.ToString(new FilePath(logLocation, TaskLog.LogName. Syslog.ToString()).Length() - prevLogLength) + "\n"); dos.Close(); dos = null; bos.Close(); bos = null; } finally { IOUtils.Cleanup(Log, dos, bos); } FilePath indexFile = GetIndexFile(currentTaskid, isCleanup); Path indexFilePath = new Path(indexFile.GetAbsolutePath()); Path tmpIndexFilePath = new Path(tmpIndexFile.GetAbsolutePath()); if (localFS == null) { // set localFS once localFS = FileSystem.GetLocal(new Configuration()); } localFS.Rename(tmpIndexFilePath, indexFilePath); } }
/// <summary>Write output to files.</summary> /// <exception cref="System.IO.IOException"/> /// <exception cref="System.Exception"/> protected override void Cleanup(Reducer.Context context) { Configuration conf = context.GetConfiguration(); Path dir = new Path(conf.Get(WorkingDirProperty)); FileSystem fs = dir.GetFileSystem(conf); { // write hex output Path hexfile = new Path(conf.Get(HexFileProperty)); OutputStream @out = new BufferedOutputStream(fs.Create(hexfile)); try { foreach (byte b in hex) { @out.Write(b); } } finally { @out.Close(); } } // If the starting digit is 1, // the hex value can be converted to decimal value. if (conf.GetInt(DigitStartProperty, 1) == 1) { Path outfile = new Path(dir, "pi.txt"); Log.Info("Writing text output to " + outfile); OutputStream outputstream = fs.Create(outfile); try { PrintWriter @out = new PrintWriter(new OutputStreamWriter(outputstream, Charsets. Utf8), true); // write hex text Print(@out, hex.GetEnumerator(), "Pi = 0x3.", "%02X", 5, 5); @out.WriteLine("Total number of hexadecimal digits is " + 2 * hex.Count + "."); // write decimal text BaileyBorweinPlouffe.Fraction dec = new BaileyBorweinPlouffe.Fraction(hex); int decDigits = 2 * hex.Count; // TODO: this is conservative. Print(@out, new _IEnumerator_168(decDigits, dec), "Pi = 3.", "%d", 10, 5); @out.WriteLine("Total number of decimal digits is " + decDigits + "."); } finally { outputstream.Close(); } } }
/** * 解压文件 * * @param filePath 压缩文件路径 */ public static void unzip(string filePath) { //isSuccess = false; File source = new File(filePath); if (source.Exists()) { ZipInputStream zis = null; BufferedOutputStream bos = null; try { zis = new ZipInputStream(new System.IO.FileStream(source.Path, System.IO.FileMode.Append)); ZipEntry entry = null; while ((entry = zis.NextEntry) != null && !entry.IsDirectory) { File target = new File(source.Parent, entry.Name); if (!target.ParentFile.Exists()) { // 创建文件父目录 target.ParentFile.Mkdirs(); } // 写入文件 bos = new BufferedOutputStream(new System.IO.FileStream(target.Path, System.IO.FileMode.Append)); int read = 0; byte[] buffer = new byte[1024 * 10]; while ((read = zis.Read(buffer, 0, buffer.Length)) != -1) { bos.Write(buffer, 0, read); } bos.Flush(); } zis.CloseEntry(); } catch (IOException e) { throw new RuntimeException(e); } finally { zis.Close(); bos.Close(); // isSuccess = true; } } }
/// <summary> /// Save file from URI to destination path /// </summary> /// <param name="context">Current context</param> /// <param name="uri">File URI</param> /// <param name="destinationPath">Destination path</param> /// <returns>Task for await</returns> private static void SaveFileFromUri(Context context, global::Android.Net.Uri uri, string destinationPath) { Stream stream = context.ContentResolver.OpenInputStream(uri); BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(System.IO.File.OpenWrite(destinationPath)); int bufferSize = 1024 * 4; byte[] buffer = new byte[bufferSize]; while (true) { int len = stream.Read(buffer, 0, bufferSize); if (len == 0) { break; } bos.Write(buffer, 0, len); } } catch (Exception ex) { System.Console.WriteLine(ex.ToString()); } finally { try { if (stream != null) { stream.Close(); } if (bos != null) { bos.Close(); } } catch (Exception ex) { System.Console.WriteLine(ex.ToString()); } } }
public static void saveFile(byte[] encodedBytes, String path) { try { Java.IO.File file = new Java.IO.File(path); System.IO.FileStream fs = new System.IO.FileStream(path, FileMode.Open); BufferedOutputStream bos = new BufferedOutputStream(fs); bos.Write(encodedBytes); bos.Flush(); bos.Close(); } catch (Java.IO.FileNotFoundException e) { e.PrintStackTrace(); } catch (Java.IO.IOException e) { e.PrintStackTrace(); } catch (Exception e) { // e.PrintStackTrace(); } }
/// <exception cref="NGit.Errors.TransportException"></exception> private void Sendpack(IList <RemoteRefUpdate> updates, ProgressMonitor monitor) { string pathPack = null; string pathIdx = null; PackWriter writer = new PackWriter(transport.GetPackConfig(), local.NewObjectReader ()); try { IList <ObjectId> need = new AList <ObjectId>(); IList <ObjectId> have = new AList <ObjectId>(); foreach (RemoteRefUpdate r in updates) { need.AddItem(r.GetNewObjectId()); } foreach (Ref r_1 in GetRefs()) { have.AddItem(r_1.GetObjectId()); if (r_1.GetPeeledObjectId() != null) { have.AddItem(r_1.GetPeeledObjectId()); } } writer.PreparePack(monitor, need, have); // We don't have to continue further if the pack will // be an empty pack, as the remote has all objects it // needs to complete this change. // if (writer.GetObjectCount() == 0) { return; } packNames = new LinkedHashMap <string, string>(); foreach (string n in dest.GetPackNames()) { packNames.Put(n, n); } string @base = "pack-" + writer.ComputeName().Name; string packName = @base + ".pack"; pathPack = "pack/" + packName; pathIdx = "pack/" + @base + ".idx"; if (Sharpen.Collections.Remove(packNames, packName) != null) { // The remote already contains this pack. We should // remove the index before overwriting to prevent bad // offsets from appearing to clients. // dest.WriteInfoPacks(packNames.Keys); dest.DeleteFile(pathIdx); } // Write the pack file, then the index, as readers look the // other direction (index, then pack file). // string wt = "Put " + Sharpen.Runtime.Substring(@base, 0, 12); OutputStream os = dest.WriteFile(pathPack, monitor, wt + "..pack"); try { os = new BufferedOutputStream(os); writer.WritePack(monitor, monitor, os); } finally { os.Close(); } os = dest.WriteFile(pathIdx, monitor, wt + "..idx"); try { os = new BufferedOutputStream(os); writer.WriteIndex(os); } finally { os.Close(); } // Record the pack at the start of the pack info list. This // way clients are likely to consult the newest pack first, // and discover the most recent objects there. // AList <string> infoPacks = new AList <string>(); infoPacks.AddItem(packName); Sharpen.Collections.AddAll(infoPacks, packNames.Keys); dest.WriteInfoPacks(infoPacks); } catch (IOException err) { SafeDelete(pathIdx); SafeDelete(pathPack); throw new TransportException(uri, JGitText.Get().cannotStoreObjects, err); } finally { writer.Release(); } }
public virtual void TestAbbreviateIsActuallyUnique() { // This test is far more difficult. We have to manually craft // an input that contains collisions at a particular prefix, // but this is computationally difficult. Instead we force an // index file to have what we want. // ObjectId id = Id("9d5b926ed164e8ee88d3b8b1e525d699adda01ba"); byte[] idBuf = ToByteArray(id); IList <PackedObjectInfo> objects = new AList <PackedObjectInfo>(); for (int i = 0; i < 256; i++) { idBuf[9] = unchecked ((byte)i); objects.AddItem(new PackedObjectInfo(ObjectId.FromRaw(idBuf))); } string packName = "pack-" + id.Name; FilePath packDir = new FilePath(((ObjectDirectory)db.ObjectDatabase).GetDirectory (), "pack"); FilePath idxFile = new FilePath(packDir, packName + ".idx"); FilePath packFile = new FilePath(packDir, packName + ".pack"); FileUtils.Mkdir(packDir, true); OutputStream dst = new BufferedOutputStream(new FileOutputStream(idxFile)); try { PackIndexWriter writer = new PackIndexWriterV2(dst); writer.Write(objects, new byte[Constants.OBJECT_ID_LENGTH]); } finally { dst.Close(); } new FileOutputStream(packFile).Close(); NUnit.Framework.Assert.AreEqual(id.Abbreviate(20), reader.Abbreviate(id, 2)); AbbreviatedObjectId abbrev8 = id.Abbreviate(8); ICollection <ObjectId> matches = reader.Resolve(abbrev8); NUnit.Framework.Assert.IsNotNull(matches); NUnit.Framework.Assert.AreEqual(objects.Count, matches.Count); foreach (PackedObjectInfo info in objects) { NUnit.Framework.Assert.IsTrue(matches.Contains(info), "contains " + info.Name); } try { db.Resolve(abbrev8.Name); NUnit.Framework.Assert.Fail("did not throw AmbiguousObjectException"); } catch (AmbiguousObjectException err) { NUnit.Framework.Assert.AreEqual(abbrev8, err.GetAbbreviatedObjectId()); matches = err.GetCandidates(); NUnit.Framework.Assert.IsNotNull(matches); NUnit.Framework.Assert.AreEqual(objects.Count, matches.Count); foreach (PackedObjectInfo info_1 in objects) { NUnit.Framework.Assert.IsTrue(matches.Contains(info_1), "contains " + info_1.Name ); } } NUnit.Framework.Assert.AreEqual(id, db.Resolve(id.Abbreviate(20).Name)); }
/// <exception cref="System.IO.IOException"/> public virtual void TestContainerLogPageAccess() { // SecureIOUtils require Native IO to be enabled. This test will run // only if it is enabled. Assume.AssumeTrue(NativeIO.IsAvailable()); string user = "******" + Runtime.CurrentTimeMillis(); FilePath absLogDir = null; FilePath appDir = null; FilePath containerDir = null; FilePath syslog = null; try { // target log directory absLogDir = new FilePath("target", typeof(TestContainerLogsPage).Name + "LogDir") .GetAbsoluteFile(); absLogDir.Mkdir(); Configuration conf = new Configuration(); conf.Set(YarnConfiguration.NmLogDirs, absLogDir.ToURI().ToString()); conf.Set(CommonConfigurationKeysPublic.HadoopSecurityAuthentication, "kerberos"); UserGroupInformation.SetConfiguration(conf); NodeHealthCheckerService healthChecker = new NodeHealthCheckerService(); healthChecker.Init(conf); LocalDirsHandlerService dirsHandler = healthChecker.GetDiskHandler(); // Add an application and the corresponding containers RecordFactory recordFactory = RecordFactoryProvider.GetRecordFactory(conf); long clusterTimeStamp = 1234; ApplicationId appId = BuilderUtils.NewApplicationId(recordFactory, clusterTimeStamp , 1); Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application app = Org.Mockito.Mockito.Mock <Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application >(); Org.Mockito.Mockito.When(app.GetAppId()).ThenReturn(appId); // Making sure that application returns a random user. This is required // for SecureIOUtils' file owner check. Org.Mockito.Mockito.When(app.GetUser()).ThenReturn(user); ApplicationAttemptId appAttemptId = BuilderUtils.NewApplicationAttemptId(appId, 1 ); ContainerId container1 = BuilderUtils.NewContainerId(recordFactory, appId, appAttemptId , 0); // Testing secure read access for log files // Creating application and container directory and syslog file. appDir = new FilePath(absLogDir, appId.ToString()); appDir.Mkdir(); containerDir = new FilePath(appDir, container1.ToString()); containerDir.Mkdir(); syslog = new FilePath(containerDir, "syslog"); syslog.CreateNewFile(); BufferedOutputStream @out = new BufferedOutputStream(new FileOutputStream(syslog) ); @out.Write(Sharpen.Runtime.GetBytesForString("Log file Content")); @out.Close(); Context context = Org.Mockito.Mockito.Mock <Context>(); ConcurrentMap <ApplicationId, Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application > appMap = new ConcurrentHashMap <ApplicationId, Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application >(); appMap[appId] = app; Org.Mockito.Mockito.When(context.GetApplications()).ThenReturn(appMap); ConcurrentHashMap <ContainerId, Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Container.Container > containers = new ConcurrentHashMap <ContainerId, Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Container.Container >(); Org.Mockito.Mockito.When(context.GetContainers()).ThenReturn(containers); Org.Mockito.Mockito.When(context.GetLocalDirsHandler()).ThenReturn(dirsHandler); MockContainer container = new MockContainer(appAttemptId, new AsyncDispatcher(), conf, user, appId, 1); container.SetState(ContainerState.Running); context.GetContainers()[container1] = container; ContainerLogsPage.ContainersLogsBlock cLogsBlock = new ContainerLogsPage.ContainersLogsBlock (context); IDictionary <string, string> @params = new Dictionary <string, string>(); @params[YarnWebParams.ContainerId] = container1.ToString(); @params[YarnWebParams.ContainerLogType] = "syslog"; Injector injector = WebAppTests.TestPage <ContainerLogsPage.ContainersLogsBlock>(typeof( ContainerLogsPage), cLogsBlock, @params, (Module[])null); PrintWriter spyPw = WebAppTests.GetPrintWriter(injector); Org.Mockito.Mockito.Verify(spyPw).Write("Exception reading log file. Application submitted by '" + user + "' doesn't own requested log file : syslog"); } finally { if (syslog != null) { syslog.Delete(); } if (containerDir != null) { containerDir.Delete(); } if (appDir != null) { appDir.Delete(); } if (absLogDir != null) { absLogDir.Delete(); } } }
public virtual void StarredExportPleco() { string stars = sharedPrefs.GetString("stars", ""); if (stars.Length < 2) { Toast.MakeText(this, "Starred list is empty. Nothing to export.", ToastLength.Long).Show(); return; } try { File dir = new File(global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "/ChineseReader"); dir.Mkdirs(); System.IO.FileStream os = new System.IO.FileStream(dir.AbsolutePath + "/chinesereader_starred.txt", System.IO.FileMode.Create, System.IO.FileAccess.Write); BufferedOutputStream bos = new BufferedOutputStream(os); StringBuilder english = new StringBuilder(); int oldIndex = 0, nIndex; while ((nIndex = stars.IndexOf("\n", oldIndex)) > -1) { english.Length = 0; int entry = Dict.BinarySearch(stars.SubstringSpecial(oldIndex, nIndex), false); oldIndex = nIndex + 1; if (entry == -1) { continue; } english.Append(Dict.GetCh(entry)).Append("\t").Append(Regex.Replace(Dict.GetPinyin(entry), @"(\\d)", "$1 ")).Append("\t"); string[] parts = Regex.Split(Regex.Replace(Dict.GetEnglish(entry), @"/", "; "), @"\\$"); int j = 0; foreach (string str in parts) { if (j++ % 2 == 1) { english.Append(" [ ").Append(Regex.Replace(str, @"(\\d)", "$1 ")).Append("] "); } else { english.Append(str); } } english.Append("\n"); bos.Write(Encoding.UTF8.GetBytes(english.ToString())); } os.Flush(); bos.Flush(); bos.Close(); os.Close(); Toast.MakeText(this, "Successfully exported to " + dir.AbsolutePath + "/chinesereader_starred.txt", ToastLength.Long).Show(); } catch (Exception e) { Toast.MakeText(this, "Could not export: " + e.Message, ToastLength.Long).Show(); } }
/** * Send Notification button click handler. This method parses the * DefaultFullSharedAccess connection string and generates a SaS token. The * token is added to the Authorization header on the POST request to the * notification hub. The text in the editTextNotificationMessage control * is added as the JSON body for the request to add a GCM message to the hub. * * @param v */ public static void SendNotification(string title, string _msg, string type, Dictionary <string, string> intent = null, string tag = null) { String msg = new String(_msg); //EditText notificationText = (EditText)findViewById(R.id.editTextNotificationMessage); //String json = "{\"data\":{\"message\":\"" + notificationText.getText().toString() + "\"}}"; StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.Append( "{" + "\"data\":" + "{"); if (intent != null) { foreach (var p in intent) { jsonBuilder.Append( $"\"{p.Key}\":\"{p.Value}\","); } } jsonBuilder.Append( $"\"{NotificationManager.Flags.Title}\":\"{title}\"," + $"\"{NotificationManager.Flags.Message}\":\"{msg}\"," + $"\"{NotificationManager.Flags.Type}\":\"{type}\"," + $"\"{NotificationManager.Flags.DeviceId}\":\"{AppData.AppDataConstants.DeviceId}\"," + $"\"{NotificationManager.Flags.UserId}\":\"{AppData.AppData.user.Id}\"" + "}" + "}"); String json = new String(jsonBuilder.ToString()); new Thread(new System.Action(() => { try { // Based on reference documentation... // http://msdn.microsoft.com/library/azure/dn223273.aspx ParseConnectionString(HubFullAccess); URL url = new URL("" + HubEndpoint + HubName + "/messages/?api-version=2015-01"); HttpURLConnection urlConnection = (HttpURLConnection)url.OpenConnection(); try { // POST request urlConnection.DoOutput = true;//.SetDoOutput(true); // Authenticate the POST request with the SaS token urlConnection.SetRequestProperty("Authorization", GenerateSasToken(new String(url.ToString())).ToString()); // Notification format should be GCM urlConnection.SetRequestProperty("ServiceBusNotification-Format", "gcm"); // Include any tags // Example below targets 3 specific tags // Refer to : https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-routing-tag-expressions/ // urlConnection.setRequestProperty("ServiceBusNotification-Tags", // "tag1 || tag2 || tag3"); // Send notification message if (tag != null) { urlConnection.SetRequestProperty("ServiceBusNotification-Tags", tag); } var jsonBytes = json.GetBytes(); urlConnection.SetFixedLengthStreamingMode(jsonBytes.Length); OutputStream bodyStream = new BufferedOutputStream(urlConnection.OutputStream /*.GetOutputStream()*/); bodyStream.Write(jsonBytes); bodyStream.Close(); //MainActivity.CurrentActivity.ToastNotify(urlConnection.ToString()); // Get reponse urlConnection.Connect(); int responseCode = (int)urlConnection.ResponseCode;//.GetResponseCode(); if ((responseCode != 200) && (responseCode != 201)) { BufferedReader br = new BufferedReader(new InputStreamReader((urlConnection.ErrorStream /*.getErrorStream()*/))); String line; StringBuilder builder = new StringBuilder("Send Notification returned " + responseCode + " : "); while ((line = new String(br.ReadLine())) != null) { builder.Append(line.ToString()); } MainActivity.CurrentActivity.ToastNotify(builder.ToString()); } } finally { urlConnection.Disconnect(); } } catch (Exception e) { MainActivity.CurrentActivity.ToastNotify("Exception Sending Notification : " + e.Message.ToString()); //if (isVisible) //{ // ToastNotify("Exception Sending Notification : " + e.getMessage().toString()); //} } })).Start(); }