Example #1
0
        internal DataBlock <KeyType, ValType> ReadDataBlock(long offset)
        {
            fs_br.BaseStream.Seek(offset, SeekOrigin.Begin);
            string json = fs_br.ReadString();
            DataBlock <KeyType, ValType> db = SerializerHelper <DataBlock <KeyType, ValType> > .DeserializeFromJsonStream(json);

            return(db);
        }
Example #2
0
        public OldDataFileStream(FqStreamID FQSID, StreamFactory.StreamOp Op, CallerInfo Ci, ISync sync)
        {
            if (!typeof(IKey).IsAssignableFrom(typeof(KeyType)))
            {
                throw new InvalidDataException("KeyType must implement IKey");
            }
            if (!typeof(IValue).IsAssignableFrom(typeof(ValType)))
            {
                throw new InvalidDataException("ValType must implement IValue");
            }

            callerId     = Ci.friendlyName;
            callerSecret = Ci.secret;

            synchronizer = sync;

            isClosed = false;
            disposed = false;
            sha1     = new SHA1CryptoServiceProvider();
            index    = new Dictionary <IKey, List <TS_Offset> >();
            /* ts_index = new List<TS_Offset>(); */

            latest_tso = new TS_Offset(0, 0);

            // Get the current directory.
            string BaseDir = Path.GetFullPath((null != Ci.workingDir) ? Ci.workingDir : Directory.GetCurrentDirectory());

            targetDir = BaseDir + "/" + FQSID.ToString();
            if (!Directory.Exists(targetDir))
            {
                Directory.CreateDirectory(targetDir);
            }

            if (synchronizer != null)
            {
                synchronizer.SetLocalSource(targetDir);
            }

            md = new OldMetaData(targetDir, ".md");

            // Check if stream has to be CREATED
            if (!md.load)
            {
                if (FQSID.AppId == callerId)
                {
                    md.setOwner(FQSID.AppId);
                    md.SetReadAccess(FQSID.AppId);
                    md.SetWriteAccess(FQSID.AppId);
                    md.FlushMetaData();
                    Console.WriteLine("Created stream " + targetDir + " for " + callerId);
                }
                else
                {
                    throw new InvalidOperationException(callerId + " not permitted to create stream for " + FQSID.AppId);
                }
            }

            // Open stream for read or write
            if (Op == StreamFactory.StreamOp.Read)
            {
                if (!OpenForRead())
                {
                    throw new InvalidDataException("Couldn't open stream for reading");
                }
            }
            else
            {
                if (!OpenForWrite())
                {
                    throw new InvalidDataException("Couldn't open stream for writing");
                }
            }


            // Build index
            try
            {
                // permission checks succeeded

                // load index from file if present
                // TODO: if not and stream.dat is present: recreate index from stream.dat
                string IndexFQN = targetDir + "/index.dat";
                if (File.Exists(IndexFQN))
                {
                    FileStream iout = new FileStream(IndexFQN, FileMode.Open,
                                                     FileAccess.Read, FileShare.ReadWrite);

                    BinaryReader index_br = new BinaryReader(iout);

                    try
                    {
                        while (true)
                        {
                            string key  = index_br.ReadString();
                            IKey   ikey = SerializerHelper <KeyType> .DeserializeFromJsonStream(key) as IKey;

                            int num_offsets          = index_br.ReadInt32();
                            List <TS_Offset> offsets = new List <TS_Offset>(num_offsets);
                            for (int i = 0; i < num_offsets; i++)
                            {
                                long      ts     = index_br.ReadInt64();
                                long      offset = index_br.ReadInt64();
                                TS_Offset tso    = new TS_Offset(ts, offset);
                                offsets.Add(tso);
                                if (ts > latest_tso.ts)
                                {
                                    latest_tso = tso;
                                }
                            }
                            index[ikey] = offsets;
                        }
                        ;
                    }
                    catch (EndOfStreamException)
                    {
                        // done
                    }
                    finally
                    {
                        index_br.Close();
                    }
                }

                /*
                 * // load ts_index
                 * string TsIndexFQN = targetDir + "/ts_index.dat";
                 * if (File.Exists(TsIndexFQN))
                 * {
                 *  FileStream iout = new FileStream(TsIndexFQN, FileMode.Open,
                 *                                   FileAccess.Read, FileShare.ReadWrite);
                 *
                 *  BinaryReader index_br = new BinaryReader(iout);
                 *
                 *  try
                 *  {
                 *      while (true)
                 *      {
                 *          long ts = index_br.ReadInt64();
                 *          long offset = index_br.ReadInt64();
                 *          ts_index.Add(new TS_Offset(ts, offset));
                 *      };
                 *  }
                 *  catch (EndOfStreamException)
                 *  {
                 *      // done
                 *  }
                 *  finally
                 *  {
                 *      index_br.Close();
                 *  }
                 * }
                 */

                // create the FileStream
                fout = new FileStream(targetDir + "/stream.dat", FileMode.OpenOrCreate,
                                      FileAccess.Write, FileShare.ReadWrite);
                fout.Seek(0, SeekOrigin.End);

                fs_bw = new BinaryWriter(fout);

                fin = new FileStream(targetDir + "/stream.dat", FileMode.Open,
                                     FileAccess.Read, FileShare.ReadWrite);

                fs_br = new BinaryReader(fin);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to open file: " + targetDir + "/stream.dat");
                Console.WriteLine("{0} Exception caught.", e);
            }
        }
Example #3
0
        public override Tuple <bool, string> Send(Notification notification)
        {
            string error = "";
            bool   skipEmailSetupCheck = false;

            // if there is no user name, or password specified, then we assume that the default email configuration
            // setup on the cloud should be used (note that we don't check the smtp server here since there is
            // always a default value on the clients)
            if (string.IsNullOrWhiteSpace(base.smtpUsername) && string.IsNullOrWhiteSpace(base.smtpPassword))
            {
                skipEmailSetupCheck = true;
            }

            if (skipEmailSetupCheck)
            {
                if (string.IsNullOrWhiteSpace(notification.toAddress) ||
                    (this.serviceHostUri == null) ||
                    string.IsNullOrWhiteSpace(this.serviceHostUri.OriginalString))
                {
                    error = "Cannot send email. Email Setup not done correctly";
                    base.logger.Log(error);
                    return(new Tuple <bool, string>(false, error));
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(base.smtpUsername) ||
                    string.IsNullOrWhiteSpace(base.smtpServer) ||
                    string.IsNullOrWhiteSpace(base.smtpPassword) ||
                    string.IsNullOrWhiteSpace(notification.toAddress) ||
                    (this.serviceHostUri == null) ||
                    string.IsNullOrWhiteSpace(this.serviceHostUri.OriginalString))
                {
                    error = "Cannot send email. Email Setup not done correctly";
                    base.logger.Log(error);
                    return(new Tuple <bool, string>(false, error));
                }
            }

            try
            {
                // TODO: add support for attachments for cloud email relay
                EmailRequestInfo emailRequestInfo = new EmailRequestInfo(
                    base.smtpUsername,
                    base.smtpPassword,
                    base.smtpServer,
                    notification.toAddress,
                    notification.subject,
                    notification.body,
                    notification.attachmentList
                    );
                if (null != emailRequestInfo)
                {
                    string jsonString = emailRequestInfo.SerializeToJsonStream();
                    logger.Log("Sending cloud email : {0}", emailRequestInfo.ToString());
                    WebClient webClient = new WebClient();
                    webClient.Headers["Content-type"] = "application/json";
                    webClient.Encoding = Encoding.UTF8;
                    webClient.UseDefaultCredentials = true;
                    string      jsonEmailStatus = webClient.UploadString(new Uri(this.serviceHostUri.OriginalString + "/SendEmail"), "POST", jsonString);
                    EmailStatus emailStatus     = SerializerHelper <EmailStatus> .DeserializeFromJsonStream(jsonEmailStatus);

                    return(new Tuple <bool, string>(emailStatus.SendStatus == EmailSendStatus.SentSuccessfully, emailStatus.SendFailureMessage));
                }
            }
            catch (Exception exception)
            {
                error = string.Format("Exception while sending cloud email: {0}", exception.ToString());
                base.logger.Log(error);
                return(new Tuple <bool, string>(false, error));
            }

            return(new Tuple <bool, string>(true, ""));
        }