/// <summary>Initializes a new instance of the <see cref="TextMessage"/> class.</summary>
 /// <param name="_message">The message.</param>
 /// <param name="fromNumber">The number.</param>
 /// <param name="toNumber"></param>
 /// <param name="_dateTime">The date time.</param>
 /// <param name="_sentOrRecieved">The sent or recieved status.</param>
 /// <param name="_filePath">Path of the file.</param>
 public TextMessage(MessageFormat format, string _message, string fromNumber, string toNumber, DateTime _dateTime, MessageStatus _sentOrRecieved, string _filePath)
     : base(_message, fromNumber, toNumber, _dateTime)
 {
     Format = format;
     sentOrRecieved = _sentOrRecieved;
     filePath = _filePath;
 }
        /// <summary>Initializes a new instance of the <see cref="ImportMessagesForm"/> class.</summary>
        /// <param name="_format">The message format to import.</param>
        public ImportMessagesForm(MessageFormat _format)
        {
            InitializeComponent();

            format = _format;
            lblMessageFormat.Text = format.ToString();
        }
 /// <summary>Initializes a new instance of the <see cref="TextMessageRecursiveProvider"/> class.</summary>
 /// <param name="name">The name.</param>
 /// <param name="path">The directory path.</param>
 /// <param name="format">The format.</param>
 public TextMessageRecursiveProvider(string name, string path, MessageFormat format)
     : base(name)
 {
     Path = path;
     Format = format;
     CreateProviders(Path);
 }
Exemple #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Response"/> class. 
        /// Initializes a new instance of the <see cref="Response"/> struct.
        /// </summary>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <param name="targets">
        /// The targets.
        /// </param>
        /// <param name="messageFormat">
        /// The message format.
        /// </param>
        /// <param name="messageType">
        /// Type of the message.
        /// </param>
        public Response(string message, IEnumerable<string> targets, MessageFormat messageFormat, MessageType messageType)
        {
            this.Message = message;
            this.Targets = targets;

            this.MessageType = messageType;
            this.MessageFormat = messageFormat;
        }
 public PrivateMessageReceivedEventArgs(IUser user, IServer server, MessageFormat format, MessageBroadcast broadcast, string message)
 {
     this.User = user;
     this.Server = server;
     this.Format = format;
     this.Broadcast = broadcast;
     this.Message = message;
 }
 /// <summary>Initializes a new instance of the <see cref="TextMessageProvider"/> class.</summary>
 /// <param name="name">The name.</param>
 /// <param name="path">The path.</param>
 /// <param name="format">The message format.</param>
 public TextMessageProvider(string name, string path, MessageFormat format)
 {
     Name = name;
     Path = path;
     MessageFormat messageFormat = format;
     IMessageParser messageParser = messageFormat == MessageFormat.Motorola ? (IMessageParser) new MotorolaTextMessageParser() : new NokiaTextMessageParser();
     textMessageReader = new TextMessageReader { MessageParser = messageParser };
 }
 /// <summary>Adds the phone node.</summary>
 /// <param name="phoneName">Name of the phone.</param>
 /// <param name="path">The path of phone folder.</param>
 /// <param name="format">The format of messages within folder.</param>
 private void AddPhoneNode(string phoneName, string path, MessageFormat format)
 {
     MobilePhone phone = new MobilePhone(phoneName, format, path);
     TreeNode node = tvParents.Nodes[0].Nodes.Add(phoneName);
     node.Tag = phone;
     phone.MessagesRetrieved += new EventHandler(MessageFolder_MessagesRetrieved);
     phone.MessagesRetrievalProgress += new EventHandler<MessageFolder.MessagesRetrievalProgressEventArgs>(MessageFolder_MessagesRetrieved);
     tvParents.SelectedNode = node;//select each node to add the folders
 }
 public PublicMessageReceivedEventArgs(IUser fromUser, IServer server, IChannel channel, MessageFormat format, MessageBroadcast broadcast, string message)
 {
     this.FromUser = fromUser;
     this.Server = server;
     this.Channel = channel;
     this.Format = format;
     this.Broadcast = broadcast;
     this.Message = message;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="CarDeliveryNetwork.Api.ClientProxy.OpenApi"/> class.
        /// </summary>
        /// <param name="uri">The uri of the target service.</param>
        /// <param name="apiKey">Your API key.</param>
        /// <param name="app">The application constructing this OpenApi instance.</param>
        public OpenApi(string uri, string apiKey = null, string app = null)
        {
            if (string.IsNullOrWhiteSpace(uri))
                throw new ArgumentException("uri string cannot be null or empty");

            _interfaceFormat = MessageFormat.Json;
            Uri = uri;
            ApiKey = apiKey;
            App = app;
        }
        /// <summary>Create and initialise form to edit existing message or to create new message.</summary>
        /// <param name="path">The location of file representing the message.</param>
        /// <param name="_format">Format of the message.</param>
        public NewEditMessage(string path, MessageFormat _format)
        {
            InitializeComponent();
            filePath = path;
            format = _format;

            List<string> contacts = Contacts.RetrieveContacts();
            contacts.Sort();
            cbxFromContacts.DataSource = new List<string>(contacts);
            cbxToContacts.DataSource = new List<string>(contacts);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="StringSenderMessage"/> class.
 /// If the value of <paramref name="messageFormat"/> is <see cref="Messaging.MessageFormat.Binary"/>,
 /// then the value of the <see cref="BinaryValue"/> property will be the result of
 /// a call to <see cref="Convert.FromBase64String"/>. Otherwise, the value of the
 /// <see cref="BinaryValue"/> property will be the result of a call to the
 /// <see cref="Encoding.GetBytes(string)"/> method of <paramref name="encoding"/>.
 /// If <paramref name="encoding"/> is null, <see cref="Encoding.UTF8"/> is used.
 /// </summary>
 /// <param name="stringValue">The string value of the message.</param>
 /// <param name="messageFormat">The message's format.</param>
 /// <param name="encoding">
 /// The encoding to use when converting the string value to a byte array if
 /// <paramref name="messageFormat"/> is not <see cref="Messaging.MessageFormat.Binary"/>.
 /// </param>
 /// <param name="priority">The priority of the message.</param>
 public StringSenderMessage(string stringValue, MessageFormat messageFormat, Encoding encoding = null, byte? priority = null)
 {
     _stringValue = stringValue;
     _binaryValue =
         new Lazy<byte[]>(
             () =>
             stringValue == null
                 ? null
                 : messageFormat == MessageFormat.Binary
                     ? Convert.FromBase64String(stringValue)
                     : (encoding ?? Encoding.UTF8).GetBytes(stringValue));
     _messageFormat = messageFormat;
     _priority = priority;
 }
        /// <summary>Initializes a new instance of the <see cref="TextMessageListViewItem"/> class.</summary>
        /// <param name="_message">The TextMessage whose details are to be displayed.</param>
        public TextMessageListViewItem(TextMessage _message)
            : base()
        {
            message = _message;
            format = message.Format;

            string toNamesAndNumbers = NamesAndNumbers(message.To);
            string fromNamesAndNumbers = NamesAndNumbers(message.From);
            string fromNumber = fromNamesAndNumbers;
            string toNumber = toNamesAndNumbers;

            //TODO: use Reflector to see the internals of new ListViewItem(string[]) - in regards to SubItems and the default item
            /*
            public ListViewItem(string[] items, int imageIndex) : this()
            {
            this.ImageIndexer.Index = imageIndex;
            if ((items != null) && (items.Length > 0))
            {
            this.subItems = new ListViewSubItem[items.Length];
            for (int i = 0; i < items.Length; i++)
            {
            this.subItems[i] = new ListViewSubItem(this, items[i]);
            }
            this.SubItemCount = items.Length;
            }
            }
            */

            ListViewSubItem fromNumberItem = new ListViewSubItem(this, fromNumber);
            fromNumberItem.Name = "FromNumber";
            SubItems.Add(fromNumberItem);
            ListViewSubItem messageItem = new ListViewSubItem(this, message.MessageText);
            messageItem.Name = "Message";
            SubItems.Add(messageItem);
            string dateString = message.DateTime.Date.ToShortDateString();
            ListViewSubItem dateItem = new ListViewSubItem(this, dateString);
            dateItem.Name = "Date";
            SubItems.Add(dateItem);
            string timeString = message.DateTime.TimeOfDay.ToString();
            ListViewSubItem timeItem = new ListViewSubItem(this, timeString);
            timeItem.Name = "Time";
            SubItems.Add(timeItem);
            ListViewSubItem toNumberItem = new ListViewSubItem(this, toNumber);
            toNumberItem.Name = "ToNumber";
            SubItems.Add(toNumberItem);
            ListViewSubItem fileNameItem = new ListViewSubItem(this, message.FileName);
            fileNameItem.Name = "FileName";
            SubItems.Add(fileNameItem);
            SubItems.RemoveAt(0);//remove initial default entry
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="BinarySenderMessage"/> class. If
 /// <paramref name="messageFormat"/> is <see cref="Messaging.MessageFormat.Binary"/>,
 /// the value of <see cref="StringValue"/> will be the result of a base 64 encoding
 /// operation on <paramref name="binaryValue"/>. Otherwise, <paramref name="encoding"/>
 /// (or <see cref="Encoding.UTF8"/> if null) will be used to obtain the value of
 /// <see cref="StringValue"/>.
 /// </summary>
 /// <param name="binaryValue">The binary value of the message.</param>
 /// <param name="messageFormat">The message's format.</param>
 /// <param name="encoding">
 /// The encoding to use when converting the binary value to a string if 
 /// <paramref name="messageFormat"/> is not <see cref="Messaging.MessageFormat.Binary"/>.
 /// </param>
 /// <param name="priority">The priority of the message.</param>
 public BinarySenderMessage(byte[] binaryValue, MessageFormat messageFormat, Encoding encoding = null, byte? priority = null)
 {
     _binaryValue = binaryValue;
     _stringValue =
         new Lazy<string>(
             () =>
             binaryValue == null
                 ? null
                 : messageFormat == MessageFormat.Binary
                     ? Convert.ToBase64String(binaryValue)
                     : (encoding ?? Encoding.UTF8).GetString(binaryValue));
     _messageFormat = messageFormat;
     _priority = priority;
 }
Exemple #14
0
        public Request(IUser user, IServer server, MessageFormat messageFormat, MessageBroadcast messageBroadcast, string message, IConnection connection)
        {
            Contract.Requires<ArgumentNullException>(user != null, "user");
            Contract.Requires<ArgumentNullException>(server != null, "server");
            Contract.Requires<ArgumentNullException>(message != null, "message");
            Contract.Requires<ArgumentNullException>(connection != null, "connection");

            this.User = user;
            this.Server = server;
            this.Format = messageFormat;
            this.Broadcast = messageBroadcast;
            this.Message = message;
            this.connection = connection;
        }
        /// <summary>Retrieves the file extention.</summary>
        /// <param name="format">The format.</param>
        /// <returns>The file extention.</returns>
        private static string RetrieveFileExtention(MessageFormat format)
        {
            string result;
            FieldInfo fieldInfo = format.GetType().GetField(format.ToString());
            if (!formatFileType.TryGetValue(format, out result)) {
                object[] attribArray = fieldInfo.GetCustomAttributes(typeof(MessageNameFormatAttribute), false);
                if (attribArray.Length != 0) {
                    MessageNameFormatAttribute attrib = attribArray[0] as MessageNameFormatAttribute;
                    result = attrib.fileExtention;
                    formatFileType[format] = result;
                }
            }

            return result;
        }
        public static string GetInformation(MessageFormat information)
        {
            string bilgi = null;

            switch (information)
            {
            case MessageFormat.OK:
                bilgi = "Başarıyla tamamlanmıştır."; break;

            case MessageFormat.Err:
                bilgi = "Bir hata oluştu."; break;

            case MessageFormat.Val:
                bilgi = "Lütfen tüm alanları doğru formatta doldurunuz.";
                break;
            }
            return(bilgi);
        }
Exemple #17
0
        /// <exception cref="NGit.Api.Errors.PatchApplyException"></exception>
        private FilePath GetFile(string path, bool create)
        {
            FilePath f = new FilePath(GetRepository().WorkTree, path);

            if (create)
            {
                try
                {
                    FileUtils.CreateNewFile(f);
                }
                catch (IOException e)
                {
                    throw new PatchApplyException(MessageFormat.Format(JGitText.Get().createNewFileFailed
                                                                       , f), e);
                }
            }
            return(f);
        }
Exemple #18
0
 /// <param name="upstream">the upstream branch</param>
 /// <returns>
 ///
 /// <code>this</code>
 /// </returns>
 /// <exception cref="NGit.Api.Errors.RefNotFoundException">NGit.Api.Errors.RefNotFoundException
 ///     </exception>
 public virtual NGit.Api.RebaseCommand SetUpstream(string upstream)
 {
     try
     {
         ObjectId upstreamId = repo.Resolve(upstream);
         if (upstreamId == null)
         {
             throw new RefNotFoundException(MessageFormat.Format(JGitText.Get().refNotResolved
                                                                 , upstream));
         }
         upstreamCommit = walk.ParseCommit(repo.Resolve(upstream));
         return(this);
     }
     catch (IOException ioe)
     {
         throw new JGitInternalException(ioe.Message, ioe);
     }
 }
Exemple #19
0
        public Transport(TransportInfo transportInfo, Action onFailure, MessageFormat messageFormat)
        {
            if (onFailure == null)
            {
                throw new ArgumentNullException("onFailure");
            }
            m_OnFailure     = onFailure;
            m_MessageFormat = messageFormat;
            m_JailedTag     = (transportInfo.JailStrategy ?? JailStrategy.None).CreateTag();

            var factory = new QueueConnectionFactory();

            (factory as ConnectionFactory).setConnectionURLs(transportInfo.Broker);
            m_Connection = factory.createQueueConnection(transportInfo.Login, transportInfo.Password);
            ((Connection)m_Connection).setConnectionStateChangeListener(new GenericConnectionStateChangeListener(connectionStateHandler));
            ((Connection)m_Connection).setPingInterval(30);
            m_Connection.start();
        }
Exemple #20
0
        public virtual void TestQuotingForSubSectionNames()
        {
            string resultPattern = "[testsection \"{0}\"]\n\ttestname = testvalue\n";
            string result;
            Config config = new Config();

            config.SetString("testsection", "testsubsection", "testname", "testvalue");
            result = MessageFormat.Format(resultPattern, "testsubsection");
            NUnit.Framework.Assert.AreEqual(result, config.ToText());
            config.Clear();
            config.SetString("testsection", "#quotable", "testname", "testvalue");
            result = MessageFormat.Format(resultPattern, "#quotable");
            NUnit.Framework.Assert.AreEqual(result, config.ToText());
            config.Clear();
            config.SetString("testsection", "with\"quote", "testname", "testvalue");
            result = MessageFormat.Format(resultPattern, "with\\\"quote");
            NUnit.Framework.Assert.AreEqual(result, config.ToText());
        }
Exemple #21
0
    public bool Equals(DiagnosticDescriptor?other)
    {
        if (ReferenceEquals(this, other))
        {
            return(true);
        }

        return
            (other != null &&
             Category == other.Category &&
             DefaultSeverity == other.DefaultSeverity &&
             Description.Equals(other.Description) &&
             HelpLinkUri == other.HelpLinkUri &&
             Id == other.Id &&
             IsEnabledByDefault == other.IsEnabledByDefault &&
             MessageFormat.Equals(other.MessageFormat) &&
             Title.Equals(other.Title));
    }
Exemple #22
0
        public void Test4112104()
        {
            MessageFormat format = new MessageFormat("");

            try
            {
                // This should NOT throw an exception
                if (format.Equals(null))
                {
                    // It also should return false
                    Errln("MessageFormat.Equals(null) returns false");
                }
            }
            catch (ArgumentNullException e)
            {
                Errln("MessageFormat.Equals(null) throws " + e);
            }
        }
Exemple #23
0
        /// <summary>
        /// Commit dedicated path only
        /// This method can be called several times to add multiple paths.
        /// </summary>
        /// <remarks>
        /// Commit dedicated path only
        /// This method can be called several times to add multiple paths. Full file
        /// paths are supported as well as directory paths; in the latter case this
        /// commits all files/ directories below the specified path.
        /// </remarks>
        /// <param name="only">path to commit</param>
        /// <returns>
        ///
        /// <code>this</code>
        /// </returns>
        public virtual NGit.Api.CommitCommand SetOnly(string only)
        {
            CheckCallable();
            if (all)
            {
                throw new JGitInternalException(MessageFormat.Format(JGitText.Get().illegalCombinationOfArguments
                                                                     , "--only", "--all"));
            }
            string o = only.EndsWith("/") ? Sharpen.Runtime.Substring(only, 0, only.Length -
                                                                      1) : only;

            // ignore duplicates
            if (!this.only.Contains(o))
            {
                this.only.AddItem(o);
            }
            return(this);
        }
Exemple #24
0
        /// <summary>
        /// Waits up to the specified timeout for the given
        /// <see cref="Predicate"/>
        /// to
        /// become <code>true</code>.
        /// <p/>
        /// The timeout time is multiplied by the
        /// <see cref="GetWaitForRatio()"/>
        /// .
        /// </summary>
        /// <param name="timeout">the timeout in milliseconds to wait for the predicate.</param>
        /// <param name="failIfTimeout">
        /// indicates if the test should be failed if the
        /// predicate times out.
        /// </param>
        /// <param name="predicate">the predicate ot evaluate.</param>
        /// <returns>
        /// the effective wait, in milli-seconds until the predicate become
        /// <code>true</code> or <code>-1</code> if the predicate did not evaluate
        /// to <code>true</code>.
        /// </returns>
        protected internal virtual long WaitFor(int timeout, bool failIfTimeout, HTestCase.Predicate
                                                predicate)
        {
            long started  = Time.Now();
            long mustEnd  = Time.Now() + (long)(GetWaitForRatio() * timeout);
            long lastEcho = 0;

            try
            {
                long waiting = mustEnd - Time.Now();
                System.Console.Out.WriteLine(MessageFormat.Format("Waiting up to [{0}] msec", waiting
                                                                  ));
                bool eval;
                while (!(eval = predicate.Evaluate()) && Time.Now() < mustEnd)
                {
                    if ((Time.Now() - lastEcho) > 5000)
                    {
                        waiting = mustEnd - Time.Now();
                        System.Console.Out.WriteLine(MessageFormat.Format("Waiting up to [{0}] msec", waiting
                                                                          ));
                        lastEcho = Time.Now();
                    }
                    Sharpen.Thread.Sleep(100);
                }
                if (!eval)
                {
                    if (failIfTimeout)
                    {
                        NUnit.Framework.Assert.Fail(MessageFormat.Format("Waiting timed out after [{0}] msec"
                                                                         , timeout));
                    }
                    else
                    {
                        System.Console.Out.WriteLine(MessageFormat.Format("Waiting timed out after [{0}] msec"
                                                                          , timeout));
                    }
                }
                return((eval) ? Time.Now() - started : -1);
            }
            catch (Exception ex)
            {
                throw new RuntimeException(ex);
            }
        }
Exemple #25
0
 public string GenerateProtoFile(IEnumerable <Type> clrTypes, string protoFileDirectory = null)
 {
     try
     {
         FireEvent(ProtoGenerationStarted);
         TypeSchema typeSchema = TypeSchemaGenerator.CreateTypeSchema(clrTypes);
         protoFileDirectory = protoFileDirectory ?? OutputDirectory;
         DirectoryInfo outputDir          = new DirectoryInfo(protoFileDirectory);
         string        nameSpace          = GetNamespace(clrTypes);
         string        targetNamespace    = string.IsNullOrEmpty(TargetNamespace) ? $"{nameSpace}.Protobuf" : TargetNamespace;
         string        filePath           = Path.Combine(outputDir.FullName, $"{nameSpace}.proto");
         string        moveExistingFileTo = new FileInfo(filePath).FullName.GetNextFileName();
         if (File.Exists(filePath))
         {
             File.Move(filePath, moveExistingFileTo);
         }
         StringBuilder protoMessages = new StringBuilder();
         protoMessages.AppendLine("syntax = \"proto3\";");
         protoMessages.AppendLine($"package {targetNamespace};");
         foreach (Type type in typeSchema.Tables)
         {
             ProtocolBufferType protoType  = new ProtocolBufferType(type, PropertyNumberer, PropertyFilter);
             StringBuilder      properties = new StringBuilder();
             foreach (ProtocolBufferProperty prop in protoType.Properties)
             {
                 string propertyFormat = prop.IsRepeated ? ArrayPropertyFormat : PropertyFormat;
                 properties.Append(propertyFormat.NamedFormat(prop));
             }
             ProtocolBufferTypeModel model = new ProtocolBufferTypeModel {
                 TypeName = protoType.TypeName, Properties = properties.ToString()
             };
             protoMessages.Append(MessageFormat.NamedFormat(model));
         }
         protoMessages.ToString().SafeWriteToFile(filePath);
         FireEvent(ProtoGenerationComplete);
         return(filePath);
     }
     catch (Exception ex)
     {
         Message = ex.Message;
         FireEvent(ProtoGenerationError);
         return(string.Empty);
     }
 }
Exemple #26
0
 /// <summary>Delete file or folder</summary>
 /// <param name="f">
 /// <code>File</code>
 /// to be deleted
 /// </param>
 /// <param name="options">
 /// deletion options,
 /// <code>RECURSIVE</code>
 /// for recursive deletion of
 /// a subtree,
 /// <code>RETRY</code>
 /// to retry when deletion failed.
 /// Retrying may help if the underlying file system doesn't allow
 /// deletion of files being read by another thread.
 /// </param>
 /// <exception cref="System.IO.IOException">
 /// if deletion of
 /// <code>f</code>
 /// fails. This may occur if
 /// <code>f</code>
 /// didn't exist when the method was called. This can therefore
 /// cause IOExceptions during race conditions when multiple
 /// concurrent threads all try to delete the same file. This
 /// exception is not thrown when IGNORE_ERRORS is set.
 /// </exception>
 public static void Delete(FilePath f, int options)
 {
     if ((options & SKIP_MISSING) != 0 && !f.Exists())
     {
         return;
     }
     if ((options & RECURSIVE) != 0 && f.IsDirectory())
     {
         FilePath[] items = f.ListFiles();
         if (items != null)
         {
             foreach (FilePath c in items)
             {
                 Delete(c, options);
             }
         }
     }
     if (!f.Delete())
     {
         if ((options & RETRY) != 0 && f.Exists())
         {
             for (int i = 1; i < 10; i++)
             {
                 try
                 {
                     Sharpen.Thread.Sleep(100);
                 }
                 catch (Exception)
                 {
                 }
                 // ignore
                 if (f.Delete())
                 {
                     return;
                 }
             }
         }
         if ((options & IGNORE_ERRORS) == 0)
         {
             throw new IOException(MessageFormat.Format(JGitText.Get().deleteFileFailed, f.GetAbsolutePath
                                                            ()));
         }
     }
 }
Exemple #27
0
        /// <summary>Low-level decoding ASCII characters from a byte array.</summary>
        /// <remarks>Low-level decoding ASCII characters from a byte array.</remarks>
        /// <param name="source">The Base64 encoded data</param>
        /// <param name="off">The offset of where to begin decoding</param>
        /// <param name="len">The length of characters to decode</param>
        /// <returns>decoded data</returns>
        /// <exception cref="System.ArgumentException">the input is not a valid Base64 sequence.
        ///     </exception>
        public static byte[] DecodeBytes(byte[] source, int off, int len)
        {
            byte[] outBuff = new byte[len * 3 / 4];
            // Upper limit on size of output
            int outBuffPosn = 0;

            byte[] b4     = new byte[4];
            int    b4Posn = 0;

            for (int i = off; i < off + len; i++)
            {
                byte  sbiCrop   = unchecked ((byte)(source[i] & unchecked ((int)(0x7f))));
                sbyte sbiDecode = DEC[sbiCrop];
                if (unchecked ((sbyte)EQUALS_SIGN_DEC) <= sbiDecode)
                {
                    b4[b4Posn++] = sbiCrop;
                    if (b4Posn > 3)
                    {
                        outBuffPosn += Decode4to3(b4, 0, outBuff, outBuffPosn);
                        b4Posn       = 0;
                        // If that was the equals sign, break out of 'for' loop
                        if (sbiCrop == EQUALS_SIGN)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    if (sbiDecode != WHITE_SPACE_DEC)
                    {
                        throw new ArgumentException(MessageFormat.Format(JGitText.Get().badBase64InputCharacterAt
                                                                         , i, source[i] & unchecked ((int)(0xff))));
                    }
                }
            }
            if (outBuff.Length == outBuffPosn)
            {
                return(outBuff);
            }
            byte[] @out = new byte[outBuffPosn];
            System.Array.Copy(outBuff, 0, @out, 0, outBuffPosn);
            return(@out);
        }
Exemple #28
0
        /// <summary>Save the configuration as a Git text style configuration file.</summary>
        /// <remarks>
        /// Save the configuration as a Git text style configuration file.
        /// <p>
        /// <b>Warning:</b> Although this method uses the traditional Git file
        /// locking approach to protect against concurrent writes of the
        /// configuration file, it does not ensure that the file has not been
        /// modified since the last read, which means updates performed by other
        /// objects accessing the same backing file may be lost.
        /// </remarks>
        /// <exception cref="System.IO.IOException">the file could not be written.</exception>
        public override void Save()
        {
            byte[] @out;
            string text = ToText();

            if (utf8Bom)
            {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bos.Write(unchecked ((int)(0xEF)));
                bos.Write(unchecked ((int)(0xBB)));
                bos.Write(unchecked ((int)(0xBF)));
                bos.Write(Sharpen.Runtime.GetBytesForString(text, RawParseUtils.UTF8_CHARSET.Name
                                                                ()));
                @out = bos.ToByteArray();
            }
            else
            {
                @out = Constants.Encode(text);
            }
            LockFile lf = new LockFile(GetFile(), fs);

            if (!lf.Lock())
            {
                throw new LockFailedException(GetFile());
            }
            try
            {
                lf.SetNeedSnapshot(true);
                lf.Write(@out);
                if (!lf.Commit())
                {
                    throw new IOException(MessageFormat.Format(JGitText.Get().cannotCommitWriteTo, GetFile
                                                                   ()));
                }
            }
            finally
            {
                lf.Unlock();
            }
            snapshot = lf.GetCommitSnapshot();
            hash     = Hash(@out);
            // notify the listeners
            FireConfigChangedEvent();
        }
Exemple #29
0
        public virtual void TestStandardFormat_LargeObject_CorruptZLibStream()
        {
            int type = Constants.OBJ_BLOB;

            byte[]   data = GetRng().NextBytes(streamThreshold + 5);
            ObjectId id   = new ObjectInserter.Formatter().IdFor(type, data);

            byte[] gz = CompressStandardFormat(type, data);
            gz[gz.Length - 1] = 0;
            gz[gz.Length - 2] = 0;
            Write(id, gz);
            ObjectLoader ol;

            {
                FileInputStream fs = new FileInputStream(Path(id));
                try
                {
                    ol = UnpackedObject.Open(fs, Path(id), id, wc);
                }
                finally
                {
                    fs.Close();
                }
            }
            try
            {
                byte[]      tmp = new byte[data.Length];
                InputStream @in = ol.OpenStream();
                try
                {
                    IOUtil.ReadFully(@in, tmp, 0, tmp.Length);
                }
                finally
                {
                    @in.Close();
                }
                NUnit.Framework.Assert.Fail("Did not throw CorruptObjectException");
            }
            catch (CorruptObjectException coe)
            {
                NUnit.Framework.Assert.AreEqual(MessageFormat.Format(JGitText.Get().objectIsCorrupt
                                                                     , id.Name, JGitText.Get().corruptObjectBadStream), coe.Message);
            }
        }
Exemple #30
0
 /// <summary>Get the HTTP response code from the request.</summary>
 /// <remarks>
 /// Get the HTTP response code from the request.
 /// <p>
 /// Roughly the same as <code>c.getResponseCode()</code> but the
 /// ConnectException is translated to be more understandable.
 /// </remarks>
 /// <param name="c">connection the code should be obtained from.</param>
 /// <returns>
 /// r HTTP status code, usually 200 to indicate success. See
 /// <see cref="Sharpen.HttpURLConnection">Sharpen.HttpURLConnection</see>
 /// for other defined constants.
 /// </returns>
 /// <exception cref="System.IO.IOException">communications error prevented obtaining the response code.
 ///     </exception>
 public static int Response(HttpURLConnection c)
 {
     try
     {
         return(c.GetResponseCode());
     }
     catch (ConnectException ce)
     {
         string host = c.GetURL().GetHost();
         // The standard J2SE error message is not very useful.
         //
         if ("Connection timed out: connect".Equals(ce.Message))
         {
             throw new ConnectException(MessageFormat.Format(JGitText.Get().connectionTimeOut,
                                                             host));
         }
         throw new ConnectException(ce.Message + " " + host);
     }
 }
Exemple #31
0
        public virtual void TestStandardFormat_SmallObject_TrailingGarbage()
        {
            ObjectId id = ObjectId.ZeroId;

            byte[] data = GetRng().NextBytes(300);
            try
            {
                byte[] gz = CompressStandardFormat(Constants.OBJ_BLOB, data);
                byte[] tr = new byte[gz.Length + 1];
                System.Array.Copy(gz, 0, tr, 0, gz.Length);
                UnpackedObject.Open(new ByteArrayInputStream(tr), Path(id), id, wc);
                NUnit.Framework.Assert.Fail("Did not throw CorruptObjectException");
            }
            catch (CorruptObjectException coe)
            {
                NUnit.Framework.Assert.AreEqual(MessageFormat.Format(JGitText.Get().objectIsCorrupt
                                                                     , id.Name, JGitText.Get().corruptObjectBadStream), coe.Message);
            }
        }
Exemple #32
0
        private static string GetContentType(MessageFormat format)
        {
            var contentType = string.Empty;

            if (format.Equals(MessageFormat.Json))
            {
                contentType = "application/json";
            }
            else if (format.Equals(MessageFormat.Xml))
            {
                contentType = "text/xml";
            }
            else if (format.Equals(MessageFormat.Binary))
            {
                contentType = "application/octet-stream";
            }

            return(contentType);
        }
Exemple #33
0
        public void Test4114743()
        {
            String        originalPattern = "initial pattern";
            MessageFormat mf             = new MessageFormat(originalPattern);
            String        illegalPattern = "ab { '}' de";

            try
            {
                mf.ApplyPattern(illegalPattern);
                Errln("illegal pattern: \"" + illegalPattern + "\"");
            }
            catch (ArgumentException foo)
            {
                if (illegalPattern.Equals(mf.ToPattern()))
                {
                    Errln("pattern after: \"" + mf.ToPattern() + "\"");
                }
            }
        }
Exemple #34
0
        /// <summary>General-purpose http PUT command to the httpfs server.</summary>
        /// <param name="filename">The file to operate upon</param>
        /// <param name="command">The command to perform (SETACL, etc)</param>
        /// <param name="params">Parameters, like "aclspec=..."</param>
        /// <exception cref="System.Exception"/>
        private void PutCmd(string filename, string command, string @params)
        {
            string user = HadoopUsersConfTestHelper.GetHadoopUsers()[0];

            // Remove leading / from filename
            if (filename[0] == '/')
            {
                filename = Sharpen.Runtime.Substring(filename, 1);
            }
            string pathOps = MessageFormat.Format("/webhdfs/v1/{0}?user.name={1}{2}{3}&op={4}"
                                                  , filename, user, (@params == null) ? string.Empty : "&", (@params == null) ? string.Empty
                                 : @params, command);
            Uri url = new Uri(TestJettyHelper.GetJettyURL(), pathOps);
            HttpURLConnection conn = (HttpURLConnection)url.OpenConnection();

            conn.SetRequestMethod("PUT");
            conn.Connect();
            NUnit.Framework.Assert.AreEqual(HttpURLConnection.HttpOk, conn.GetResponseCode());
        }
        private static string GetMessageAsString(byte[] body, MessageFormat messageFormat)
        {
            var messageAsString = string.Empty;

            if (messageFormat.Equals(MessageFormat.Json))
            {
                messageAsString = Encoding.Default.GetString(body);
            }
            else if (messageFormat.Equals(MessageFormat.Xml))
            {
                messageAsString = Encoding.Default.GetString(body);
            }
            else if (messageFormat.Equals(MessageFormat.Binary))
            {
                messageAsString = Convert.ToBase64String(body);
            }

            return(messageAsString);
        }
Exemple #36
0
        private void printTokenErrorRank()
        {
            printHeader("Tokens with the highest number of errors");
            printStream.append("\n");

            SortedSet <string> toks = TokensOrderedByNumberOfErrors;
            int maxTokenSize        = 5;

            int count = 0;
            IEnumerator <string> tokIterator = toks.GetEnumerator();

            while (tokIterator.MoveNext() && count++ < 20)
            {
                string tok = tokIterator.Current;
                if (tok.Length > maxTokenSize)
                {
                    maxTokenSize = tok.Length;
                }
            }

            int tableSize = 31 + maxTokenSize;

            string format = "| %" + maxTokenSize + "s | %6s | %5s | %7s |\n";

            printLine(tableSize);
            printStream.append(string.format(format, "Token", "Errors", "Count", "% Err"));
            printLine(tableSize);

            // get the first 20 errors
            count       = 0;
            tokIterator = toks.GetEnumerator();
            while (tokIterator.MoveNext() && count++ < 20)
            {
                string tok         = tokIterator.Current;
                int    ocurrencies = getTokenFrequency(tok);
                int    errors      = getTokenErrors(tok);
                string rate        = MessageFormat.format("{0,number,#.##%}", (double)errors / ocurrencies);

                printStream.append(string.format(format, tok, errors, ocurrencies, rate));
            }
            printLine(tableSize);
            printFooter("Tokens with the highest number of errors");
        }
 /// <summary>Read the cache file into memory.</summary>
 /// <remarks>Read the cache file into memory.</remarks>
 /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
 public virtual void Read()
 {
     changed   = false;
     statDirty = false;
     if (!cacheFile.Exists())
     {
         header = null;
         entries.Clear();
         lastCacheTime = 0;
         return;
     }
     cache = new RandomAccessFile(cacheFile, "r");
     try
     {
         FileChannel channel = cache.GetChannel();
         ByteBuffer  buffer  = ByteBuffer.AllocateDirect((int)cacheFile.Length());
         buffer.Order(ByteOrder.BIG_ENDIAN);
         int j = channel.Read(buffer);
         if (j != buffer.Capacity())
         {
             throw new IOException(MessageFormat.Format(JGitText.Get().couldNotReadIndexInOneGo
                                                        , j, buffer.Capacity()));
         }
         buffer.Flip();
         header = new GitIndex.Header(buffer);
         entries.Clear();
         for (int i = 0; i < header.entries; ++i)
         {
             GitIndex.Entry entry    = new GitIndex.Entry(this, buffer);
             GitIndex.Entry existing = entries.Get(entry.name);
             entries.Put(entry.name, entry);
             if (existing != null)
             {
                 entry.stages |= existing.stages;
             }
         }
         lastCacheTime = cacheFile.LastModified();
     }
     finally
     {
         cache.Close();
     }
 }
Exemple #38
0
        public virtual void TestGlobFilter()
        {
            CreateHttpFSServer(false);
            FileSystem fs = FileSystem.Get(TestHdfsHelper.GetHdfsConf());

            fs.Mkdirs(new Path("/tmp"));
            fs.Create(new Path("/tmp/foo.txt")).Close();
            string user = HadoopUsersConfTestHelper.GetHadoopUsers()[0];
            Uri    url  = new Uri(TestJettyHelper.GetJettyURL(), MessageFormat.Format("/webhdfs/v1/tmp?user.name={0}&op=liststatus&filter=f*"
                                                                                      , user));
            HttpURLConnection conn = (HttpURLConnection)url.OpenConnection();

            NUnit.Framework.Assert.AreEqual(conn.GetResponseCode(), HttpURLConnection.HttpOk);
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.GetInputStream
                                                                                 ()));

            reader.ReadLine();
            reader.Close();
        }
Exemple #39
0
        /// <exception cref="NGit.Errors.MissingObjectException"></exception>
        /// <exception cref="NGit.Errors.IncorrectObjectTypeException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        private static byte[] Read(Repository db, AnyObjectId treeish, string path)
        {
            ObjectReader or = db.NewObjectReader();

            try
            {
                TreeWalk tree = TreeWalk.ForPath(or, path, AsTree(or, treeish));
                if (tree == null)
                {
                    throw new FileNotFoundException(MessageFormat.Format(JGitText.Get().entryNotFoundByPath
                                                                         , path));
                }
                return(Read(or, tree.GetObjectId(0)));
            }
            finally
            {
                or.Release();
            }
        }
        /// <exception cref="System.IO.IOException"></exception>
        internal static void Delete(FilePath file, int depth)
        {
            if (!file.Delete() && file.IsFile())
            {
                throw new IOException(MessageFormat.Format(JGitText.Get().fileCannotBeDeleted, file
                                                           ));
            }
            FilePath dir = file.GetParentFile();

            for (int i = 0; i < depth; ++i)
            {
                if (!dir.Delete())
                {
                    break;
                }
                // ignore problem here
                dir = dir.GetParentFile();
            }
        }
Exemple #41
0
 /// <exception cref="System.IO.IOException"></exception>
 internal virtual int ReadLength()
 {
     IOUtil.ReadFully(@in, lineBuffer, 0, 4);
     try
     {
         int len = RawParseUtils.ParseHexInt16(lineBuffer, 0);
         if (len != 0 && len < 4)
         {
             throw new IndexOutOfRangeException();
         }
         return(len);
     }
     catch (IndexOutOfRangeException)
     {
         throw new IOException(MessageFormat.Format(JGitText.Get().invalidPacketLineHeader
                                                    , string.Empty + (char)lineBuffer[0] + (char)lineBuffer[1] + (char)lineBuffer[2]
                                                    + (char)lineBuffer[3]));
     }
 }
Exemple #42
0
        /// <exception cref="System.IO.IOException"></exception>
        internal virtual PacketLineIn.AckNackResult ReadACK(MutableObjectId returnedId)
        {
            string line = ReadString();

            if (line.Length == 0)
            {
                throw new PackProtocolException(JGitText.Get().expectedACKNAKFoundEOF);
            }
            if ("NAK".Equals(line))
            {
                return(PacketLineIn.AckNackResult.NAK);
            }
            if (line.StartsWith("ACK "))
            {
                returnedId.FromString(Sharpen.Runtime.Substring(line, 4, 44));
                if (line.Length == 44)
                {
                    return(PacketLineIn.AckNackResult.ACK);
                }
                string arg = Sharpen.Runtime.Substring(line, 44);
                if (arg.Equals(" continue"))
                {
                    return(PacketLineIn.AckNackResult.ACK_CONTINUE);
                }
                else
                {
                    if (arg.Equals(" common"))
                    {
                        return(PacketLineIn.AckNackResult.ACK_COMMON);
                    }
                    else
                    {
                        if (arg.Equals(" ready"))
                        {
                            return(PacketLineIn.AckNackResult.ACK_READY);
                        }
                    }
                }
            }
            throw new PackProtocolException(MessageFormat.Format(JGitText.Get().expectedACKNAKGot
                                                                 , line));
        }
Exemple #43
0
 /// <summary>Sets default values for not explicitly specified options.</summary>
 /// <remarks>
 /// Sets default values for not explicitly specified options. Then validates
 /// that all required data has been provided.
 /// </remarks>
 /// <param name="state">the state of the repository we are working on</param>
 /// <exception cref="NGit.Api.Errors.NoMessageException">if the commit message has not been specified
 ///     </exception>
 private void ProcessOptions(RepositoryState state)
 {
     if (committer == null)
     {
         committer = new PersonIdent(repo);
     }
     if (author == null)
     {
         author = committer;
     }
     // when doing a merge commit parse MERGE_HEAD and MERGE_MSG files
     if (state == RepositoryState.MERGING_RESOLVED)
     {
         try
         {
             parents = repo.ReadMergeHeads();
         }
         catch (IOException e)
         {
             throw new JGitInternalException(MessageFormat.Format(JGitText.Get().exceptionOccurredDuringReadingOfGIT_DIR
                                                                  , Constants.MERGE_HEAD, e), e);
         }
         if (message == null)
         {
             try
             {
                 message = repo.ReadMergeCommitMsg();
             }
             catch (IOException e)
             {
                 throw new JGitInternalException(MessageFormat.Format(JGitText.Get().exceptionOccurredDuringReadingOfGIT_DIR
                                                                      , Constants.MERGE_MSG, e), e);
             }
         }
     }
     if (message == null)
     {
         // as long as we don't suppport -C option we have to have
         // an explicit message
         throw new NoMessageException(JGitText.Get().commitMessageNotSpecified);
     }
 }
        public MessageFormat <TaskDTO> Update(TaskDTO taskDTO)
        {
            MessageFormat <TaskDTO> result = new MessageFormat <TaskDTO>();

            taskDTO.ModifiedOn = DateTime.Now;
            Domain.Task task = DatabaseAutomapperConfiguration.TaskDTOToTask(taskDTO);
            try
            {
                DatabaseContext.Tasks.Update(task);
                DatabaseContext.SaveChanges();
                result.Message = "Updated Successfully";
                result.Data    = taskDTO;
                result.Success = true;
                return(result);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
Exemple #45
0
        public static string SetMessageFormat(string message, MessageFormat format)
        {
            string formatedMessage;

            switch (format)
            {
            case MessageFormat.DateAndTime:
                formatedMessage = $"[{DateTime.Now}] {message}";
                break;

            case MessageFormat.Uppercase:
                formatedMessage = $"{message}".ToUpper();
                break;

            default:
                formatedMessage = message;
                break;
            }
            return(formatedMessage);
        }
 /// <summary>
 /// Synchronously sends the specified binary message.
 /// </summary>
 /// <param name="source">The <see cref="ISender"/> from which to send the message.</param>
 /// <param name="message">The message to send.</param>
 /// <param name="messageFormat">The message's format.</param>
 public static void Send(this ISender source, byte[] message, MessageFormat messageFormat)
 {
     source.SendAsync(message, messageFormat).Wait();
 }
Exemple #47
0
		private Message[] PeekMessages(MessageQueue activeQueue, bool blnDynamicConnection, MessageFormat eMessageFormat, System.Type CustomType)
		{
			Message objMessage;
			Message[] arrCurrentMessages = new Message[0];
			Message[] arrCopyOfMessages = null;
			IMessageFormatter objFormatter = null ;
			MessagePropertyFilter objMessagePropertyFilter = new MessagePropertyFilter();
			int intArrayIndex;

			// Message Formatter
			switch (eMessageFormat)
			{
				case MessageFormat.XMLSerialize:
					if (CustomType == null)
					{
						objFormatter = new XmlMessageFormatter();
					}
					else
					{
					// objFormatter = new XmlMessageFormatter(new Type() [CustomType]);
					}

					break;
				case MessageFormat.ActiveXSerialize:
					objFormatter = new ActiveXMessageFormatter();
					break;
				case MessageFormat.BinarySerialize:
					objFormatter = new BinaryMessageFormatter();
					break;
			}

			// Messages in Private Queue
			// Ensure these properties are received (CorrelationID defaults to False)
			objMessagePropertyFilter.SetDefaults();
			objMessagePropertyFilter.CorrelationId = true;
			objMessagePropertyFilter.AppSpecific = true;
			objMessagePropertyFilter.ArrivedTime = true;
			activeQueue.MessageReadPropertyFilter = objMessagePropertyFilter;

			// Message Formatter
			activeQueue.Formatter = objFormatter;

			// Dynamic Connection whilst gathering messages
			if (blnDynamicConnection == true)
			{
				IEnumerator objMessageEnumerator = activeQueue.GetEnumerator();
				intArrayIndex = 0;
				while (objMessageEnumerator.MoveNext())
				{
					objMessage = (Message) objMessageEnumerator.Current;
					if (intArrayIndex > 0)
					{
						arrCopyOfMessages = new Message[intArrayIndex];
						arrCurrentMessages.CopyTo(arrCopyOfMessages,0);
						arrCurrentMessages=arrCopyOfMessages;
					}
					arrCurrentMessages[intArrayIndex] = objMessage;
					intArrayIndex += 1;
				}
			}
			else // Snapshot of messages currently in Queue
			{
				arrCurrentMessages = null ;
				try
				{
					arrCurrentMessages = activeQueue.GetAllMessages();
				}
				catch (System.Messaging.MessageQueueException excM)
				{
					throw excM;
				}
			}

			return arrCurrentMessages;

		}
 /// <summary>
 /// Asynchronously sends the specified binary message.
 /// </summary>
 /// <param name="source">The <see cref="ISender"/> from which to send the message.</param>
 /// <param name="message">The message to send.</param>
 /// <param name="messageFormat">The message's format.</param>
 public static Task SendAsync(this ISender source, byte[] message, MessageFormat messageFormat)
 {
     return source.SendAsync(new BinarySenderMessage(message, messageFormat));
 }
Exemple #49
0
 /// <summary>
 /// Shortens the URL.
 /// </summary>
 /// <param name="user">The user.</param>
 /// <param name="channel">The channel.</param>
 /// <param name="messageType">Type of the message.</param>
 /// <param name="messageFormat">The message format.</param>
 /// <param name="message">The message.</param>
 /// <param name="arguments">The arguments.</param>
 private void ShortenUrl(User user, string channel, MessageType messageType, MessageFormat messageFormat, string message, Dictionary<string, string> arguments)
 {
     foreach (IUrlShortenerProvider provider in this.providers)
     {
         if(arguments.ContainsKey(provider.Trigger))
         {
             try
             {
                 var url = UrlRegex.Match(message).Groups["url"].Value;
                 string shortUrl;
                 shortUrl = this.GetShortUrl(url, provider);
                 var response = new Response(shortUrl, new[] { channel ?? user.Nick }, messageFormat, messageType);
                 this.SendResponse(response);
             }
             catch (Exception e)
             {
                 Trace.TraceError(e.Source);
                 Trace.TraceError(e.Message);
             }
         }
     }
 }
Exemple #50
0
        /// <summary>
        /// Lists the admins.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="channel">The channel.</param>
        /// <param name="messageType">Type of the message.</param>
        /// <param name="messageFormat">The message format.</param>
        /// <param name="message">The message.</param>
        /// <param name="arguments">The arguments.</param>
        private void ListAdmins(User user, string channel, MessageType messageType, MessageFormat messageFormat, string message, Dictionary<string, string> arguments)
        {
            var admins = this.userService.ListAdmins().Select(a => string.Format("{0} : {1}", a.Nick, a.Email));

            foreach (var admin in admins)
            {
                var response = new Response(admin, new[] { channel ?? user.Nick }, MessageFormat.Message, MessageType.Both);
                this.IrcClient.SendResponse(response);
            }
        }
 /// <summary>
 /// Returns a serial representation of the object in the specified format.
 /// </summary>
 /// <param name="format">Format to serialize to.</param>
 /// <returns>The serialized object.</returns>
 public string ToString(MessageFormat format)
 {
     return Serialization.Serialize(this, format);
 }
 /// <summary>
 /// Reads the JSON or XML document and returns the deserialized object.
 /// </summary>
 /// <param name="serializedObject">The serialized object.</param>
 /// <param name="format">The format of the serialized object.</param>
 /// <returns>The deserialized object.</returns>
 public static DeviceRegistration FromString(string serializedObject, MessageFormat format)
 {
     return Serialization.Deserialise<DeviceRegistration>(serializedObject, format);
 }
Exemple #53
0
 /// <summary>
 /// Joins the channel.
 /// </summary>
 /// <param name="user">The user.</param>
 /// <param name="channel">The channel.</param>
 /// <param name="messageType">Type of the message.</param>
 /// <param name="messageFormat">The message format.</param>
 /// <param name="message">The message.</param>
 /// <param name="arguments">The arguments.</param>
 private void JoinChannel(User user, string channel, MessageType messageType, MessageFormat messageFormat, string message, Dictionary<string, string> arguments)
 {
     if (arguments.ContainsKey("channel"))
     {
         if (arguments.ContainsKey("key"))
         {
             this.IrcClient.Join(arguments["channel"], arguments["key"]);
         }
         else
         {
             this.IrcClient.Join(arguments["channel"]);
         }
     }
 }
        /// <summary>
        /// Sends the forecast.
        /// </summary>
        /// <param name="targets">The targets.</param>
        /// <param name="messageFormat">The message format.</param>
        /// <param name="messageType">Type of the message.</param>
        /// <param name="forecast">The forecast.</param>
        /// <returns>
        /// The forecasts.
        /// </returns>
        private static IEnumerable<IResponse> CreateForecastResponses(IEnumerable<string> targets, MessageFormat messageFormat, MessageType messageType, IForecast forecast)
        {
            try
            {
                var responses = new List<IResponse>();

                foreach (var day in forecast.TextualForecast.ForecastDays)
                {
                    responses.Add(new Response(day.ForecastTextMetric, targets, messageFormat, messageType));
                }

                return responses;
            }
            catch (Exception e)
            {
                Trace.TraceError(e.TargetSite.Name);
                Trace.TraceError(e.Message);
            }

            return Enumerable.Empty<IResponse>();
        }
        /// <summary>
        /// Builds the responses to send.
        /// </summary>
        /// <param name="targets">The targets.</param>
        /// <param name="messageFormat">The message format.</param>
        /// <param name="messageType">Type of the message.</param>
        /// <returns>
        /// The <see cref="IEnumerable" />.
        /// </returns>
        private IEnumerable<IResponse> BuildResponses(IEnumerable<string> targets, MessageFormat messageFormat, MessageType messageType)
        {
            var receivers = targets.ToArray();
            var wundergroundResponse = this.ExecuteRequest();
            var responses = new List<IResponse>();

            try
            {
                if (wundergroundResponse.Response.Features.Conditions)
                {
                    responses.AddRange(CreateConditionsResponse(receivers, messageFormat, messageType, wundergroundResponse.CurrentObservation));
                }

                if (wundergroundResponse.Response.Features.Forecast)
                {
                    responses.AddRange(CreateForecastResponses(receivers, messageFormat, messageType, wundergroundResponse.Forecast));
                }

                return responses;
            }
            catch (Exception e)
            {
                Trace.TraceError(e.TargetSite.Name);
                Trace.TraceError(e.Message);
            }

            return Enumerable.Empty<IResponse>();
        }
        /// <summary>
        /// Sends the conditions.
        /// </summary>
        /// <param name="targets">The targets.</param>
        /// <param name="messageFormat">The message format.</param>
        /// <param name="messageType">Type of the message.</param>
        /// <param name="currentObservation">The current observation.</param>
        /// <returns>
        /// The <see cref="IEnumerable" />.
        /// </returns>
        private static IEnumerable<IResponse> CreateConditionsResponse(IEnumerable<string> targets, MessageFormat messageFormat, MessageType messageType, ICurrentObservation currentObservation)
        {
            try
            {
                var conditions = "{0}. {1}. {2}, feels like {2}, wind chill {3}.".FormatWith(
                    currentObservation.DisplayLocation.Full,
                    currentObservation.ObservationTime,
                    currentObservation.Temperature,
                    currentObservation.FeelsLike,
                    currentObservation.Wind);

                var response = new Response(conditions, targets, messageFormat, messageType);

                return new[] { response };
            }
            catch (Exception e)
            {
                Trace.TraceError(e.TargetSite.Name);
                Trace.TraceError(e.Message);
            }

            return Enumerable.Empty<IResponse>();
        }
        /// <summary>
        /// Gets the weather.
        /// </summary>
        /// <param name="targets">The targets.</param>
        /// <param name="messageFormat">The message format.</param>
        /// <param name="messageType">Type of the message.</param>
        /// <param name="message">The message.</param>
        /// <param name="arguments">The arguments.</param>
        /// <returns>
        /// Responses to send back.
        /// </returns>
        public override IEnumerable<IResponse> GetWeather(IEnumerable<string> targets, MessageFormat messageFormat, MessageType messageType, string message, Dictionary<string, string> arguments)
        {
            if (this.ParseArguments(arguments))
            {
                return this.BuildResponses(targets, messageFormat, messageType);
            }

            return Enumerable.Empty<IResponse>();
        }
Exemple #58
0
 /// <summary>
 /// Sends a message to a chat room.
 /// </summary>
 public static void SendMessage(string token, string room, string from, string message, bool notify, BackgroundColor color, MessageFormat messageFormat)
 {
     // create a local instance of HipChatClient, as then we get the validation
     var client = new HipChatClient(token, room);
     client.SendMessage(message, from, notify, color);
 }
Exemple #59
0
        /// <summary>
        /// Interactive ruby.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="channel">The channel.</param>
        /// <param name="messageType">Type of the message.</param>
        /// <param name="messageFormat">The message format.</param>
        /// <param name="message">The message.</param>
        /// <param name="args">The arguments.</param>
        private void InteractiveRuby(User user, string channel, MessageType messageType, MessageFormat messageFormat, string message, Dictionary<string, string> args)
        {
            message = message.Remove(0, "!irb".Length);

            if (args.ContainsKey("start"))
            {
                this.irbService.CreateSession(user, channel);
            }
            else if (args.ContainsKey("stop"))
            {
                this.irbService.RemoveSession(user);
            }
            else if (!string.IsNullOrEmpty(message) && this.interactiveSessions.Contains(user.Nick))
            {
                this.irbService.WriteToSession(user, message);
            }
        }
Exemple #60
0
 public HipChatClient(string token, string room, MessageFormat messageFormat)
     : this(token, room)
 {
     this.messageFormat = messageFormat;
 }