示例#1
0
        public static void MigrateDB()
        {
            SQLSvrDbi.DbConnectionString = Configuration.Configurator.GetDBConnString(SourceDBConnName);
            GemFireXDDbi.DbConnectionString = Configuration.Configurator.GetDBConnString(DestDBConnName);

            try
            {
                if (MigrateTables)
                    MigrateDbTables();
                if (MigrateViews)
                    MigrateDbViews();
                if (MigrateIndexes)
                    MigrateDbIndexes();
                if (MigrateProcedures)
                    MigrateDbStoredProcedures();
                if (MigrateFunctions)
                    MigrateDbFunctions();
                if (MigrateTriggers)
                    MigrateDbTriggers();
            }
            catch (ThreadAbortException e)
            {
                Result = Result.Aborted;
                OnMigrateEvent(new MigrateEventArgs(Result.Aborted, "Operation aborted!"));
            }
            catch (Exception e)
            {
                Helper.Log(e);
            }
            finally
            {
                dbTableList.Clear();
            }
        }
        public Yield GetTags(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
            string type = DreamContext.Current.GetParam("type", "");
            string fromStr = DreamContext.Current.GetParam("from", "");
            string toStr = DreamContext.Current.GetParam("to", "");
            bool showPages = DreamContext.Current.GetParam("pages", false);
            string partialName = DreamContext.Current.GetParam("q", "");

            // parse type
            TagType tagType = TagType.ALL;
            if(!string.IsNullOrEmpty(type) && !SysUtil.TryParseEnum(type, out tagType)) {
                throw new DreamBadRequestException("Invalid type parameter");
            }

            // check and validate from date
            DateTime from = (tagType == TagType.DATE) ? DateTime.Now : DateTime.MinValue;
            if(!string.IsNullOrEmpty(fromStr) && !DateTime.TryParse(fromStr, out from)) {
                throw new DreamBadRequestException("Invalid from date parameter");
            }

            // check and validate to date
            DateTime to = (tagType == TagType.DATE) ? from.AddDays(30) : DateTime.MaxValue;
            if(!string.IsNullOrEmpty(toStr) && !DateTime.TryParse(toStr, out to)) {
                throw new DreamBadRequestException("Invalid to date parameter");
            }

            // execute query
            var tags = TagBL.GetTags(partialName, tagType, from, to);
            XDoc doc = TagBL.GetTagListXml(tags, "tags", null, showPages);
            response.Return(DreamMessage.Ok(doc));
            yield break;
        }
        public override void Validate( String action, IEntity target, EntityPropertyInfo info, Result result )
        {
            Object obj = target.get( info.Name );

            Boolean isNull = false;
            if (info.Type == typeof( String )) {
                if (obj == null) {
                    isNull = true;
                }
                else if (strUtil.IsNullOrEmpty( obj.ToString() )) {
                    isNull = true;
                }
            }
            else if (obj == null) {
                isNull = true;
            }

            if (isNull) {
                if (strUtil.HasText( this.Message )) {
                    result.Add( this.Message );
                }
                else {
                    EntityInfo ei = Entity.GetInfo( target );
                    String str = "[" + ei.FullName + "] : property \"" + info.Name + "\" ";
                    result.Add( str + "can not be null" );
                }
            }
        }
示例#4
0
        public Result Search(N2.Persistence.Search.Query query)
        {
            if (!query.IsValid())
                return Result.Empty;

            var s = accessor.GetSearcher();
            try
            {
                var q = CreateQuery(query);
                var hits = s.Search(q, query.SkipHits + query.TakeHits);

                var result = new Result();
                result.Total = hits.totalHits;
                var resultHits = hits.scoreDocs.Skip(query.SkipHits).Take(query.TakeHits).Select(hit =>
                {
                    var doc = s.Doc(hit.doc);
                    int id = int.Parse(doc.Get("ID"));
                    ContentItem item = persister.Get(id);
                    return new Hit { Content = item, Score = hit.score };
                }).Where(h => h.Content != null).ToList();
                result.Hits = resultHits;
                result.Count = resultHits.Count;
                return result;
            }
            finally
            {
                //s.Close();
            }
        }
        public virtual Result Buy( int buyerId, int creatorId, ForumTopic topic )
        {
            Result result = new Result();
            if (userIncomeService.HasEnoughKeyIncome( buyerId, topic.Price ) == false) {
                result.Add( String.Format( alang.get( typeof( ForumApp ), "exIncome" ), KeyCurrency.Instance.Name ) );
                return result;
            }

            // 日志:买方减少收入
            UserIncomeLog log = new UserIncomeLog();
            log.UserId = buyerId;
            log.CurrencyId = KeyCurrency.Instance.Id;
            log.Income = -topic.Price;
            log.DataId = topic.Id;
            log.ActionId = actionId;
            db.insert( log );

            // 日志:卖方增加收入
            UserIncomeLog log2 = new UserIncomeLog();
            log2.UserId = creatorId;
            log2.CurrencyId = KeyCurrency.Instance.Id;
            log2.Income = topic.Price;
            log2.DataId = topic.Id;
            log2.ActionId = actionId;
            db.insert( log2 );

            userIncomeService.AddKeyIncome( buyerId, -topic.Price );
            userIncomeService.AddKeyIncome( creatorId, topic.Price );

            return result;
        }
        public Yield GetServiceById(DreamContext context, DreamMessage request, Result<DreamMessage> response) {

            bool privateDetails = PermissionsBL.IsUserAllowed(DekiContext.Current.User, Permissions.ADMIN);

            //Private feature requires api-key
            var identifier = context.GetParam("id");
            uint serviceId = 0;
            if(identifier.StartsWith("=")) {
                var serviceInfo = DekiContext.Current.Instance.RunningServices[XUri.Decode(identifier.Substring(1))];
                if(serviceInfo != null) {
                    serviceId = serviceInfo.ServiceId;
                }
            } else {
                if(!uint.TryParse(identifier, out serviceId)) {
                    throw new DreamBadRequestException(string.Format("Invalid id '{0}'", identifier));
                }
            }
            ServiceBE service = ServiceBL.GetServiceById(serviceId);
            DreamMessage responseMsg = null;
            if(service == null) {
                responseMsg = DreamMessage.NotFound(string.Format(DekiResources.SERVICE_NOT_FOUND, identifier));
            } else {
                responseMsg = DreamMessage.Ok(ServiceBL.GetServiceXmlVerbose(DekiContext.Current.Instance, service, null, privateDetails));
            }
            response.Return(responseMsg);
            yield break;
        }
示例#7
0
文件: CMD.cs 项目: gotatsu/Wox
        private List<Result> GetHistoryCmds(string cmd, Result result)
        {
            IEnumerable<Result> history = CMDStorage.Instance.CMDHistory.Where(o => o.Key.Contains(cmd))
                .OrderByDescending(o => o.Value)
                .Select(m =>
                {
                    if (m.Key == cmd)
                    {
                        result.SubTitle = string.Format(context.API.GetTranslation("wox_plugin_cmd_cmd_has_been_executed_times"), m.Value);
                        return null;
                    }

                    var ret = new Result
                    {
                        Title = m.Key,
                        SubTitle =  string.Format(context.API.GetTranslation("wox_plugin_cmd_cmd_has_been_executed_times"), m.Value),
                        IcoPath = "Images/cmd.png",
                        Action = (c) =>
                        {
                            ExecuteCmd(m.Key);
                            return true;
                        }
                    };
                    return ret;
                }).Where(o => o != null).Take(4);
            return history.ToList();
        }
示例#8
0
        public override Result Process(Result result)
        {
            if(result.Line.StartsWith("#"))
            {

                if(result.Line.StartsWith(Constants.HeaderField))
                {
                    LogContext.Storage.Insert(GetStorageKey(result), new FieldParser().ParseFields(result.Line));
                }

                result.Canceled = true;
                return result;
            }

            try
            {
                var parsedLine = ParseLine(result);
                result.EventTimeStamp = parsedLine.TimeStamp;

                foreach(var field in parsedLine.Fields)
                {
                    var token = FieldToJToken.Parse(field);
                    result.Json.Add(field.Key, token);
                }

                return result;
            }
            catch(Exception ex)
            {
                Log.ErrorException("Line: " + result.Line + " could not be parsed.", ex);
                result.Canceled = true;
                return result;
            }
        }
示例#9
0
 //获取用户的所有有效订单数据
 public Result<List<OrderViewModel>> GetUserAllOrder(int userId,List<int> orderStatus)
 {
     var result = new Result<List<OrderViewModel>>();
     result.Data= orderDataAccess.GetUserAllOrder(userId, orderStatus);
     result.Status = new Status() {Code = "1"};
     return result;
 }
        /// <summary>
        /// Searches for the specified show and its episode.
        /// </summary>
        /// <param name="ep">The episode.</param>
        public void Search(Episode ep)
        {
            _td = new TaskDialog
                {
                    Title           = "Searching...",
                    Instruction     = "{0} S{1:00}E{2:00}".FormatWith(ep.Show.Name, ep.Season, ep.Number),
                    Content         = "Searching for the episode...",
                    CommonButtons   = TaskDialogButton.Cancel,
                    ShowProgressBar = true
                };

            _td.SetMarqueeProgressBar(true);
            _td.Destroyed   += TaskDialogDestroyed;
            _td.ButtonClick += TaskDialogDestroyed;

            _active = true;
            new Thread(() =>
                {
                    Thread.Sleep(500);

                    if (_active)
                    {
                        _res = _td.Show().CommonButton;
                    }
                }).Start();

            _os.SearchAsync(ep);

            Utils.Win7Taskbar(state: TaskbarProgressBarState.Indeterminate);
        }
示例#11
0
文件: Main.cs 项目: xxy1991/cozy
 public override List<Result> Query(Query query)
 {
     if (query.RawQuery == "h mem")
     {
         var rl = new List<Result>();
         var r = new Result();
         r.Title = GetTotalPhysicalMemory();
         r.SubTitle = "Copy this number to the clipboard";
         r.IcoPath = "[Res]:sys";
         r.Score = 100;
         r.Action = e =>
         {
             context_.Api.HideAndClear();
             try
             {
                 Clipboard.SetText(r.Title);
                 return true;
             }
             catch (System.Runtime.InteropServices.ExternalException)
             {
                 return false;
             }
         };
         rl.Add(r);
         return rl;
     }
     return null;
 }
示例#12
0
 static Result Optimize(Result current, Func<double[],double> evaluator)
 {
     bool[,] tried = new bool[current.vector.Length, 2];
     int coordinate = 0;
     int direction = 0;
     bool cont = false;
     Result newResult = null;
     while(true)
     {
         if (tried.Cast<bool>().All(z => z)) break;
         coordinate = rnd.Next(current.vector.Length);
         direction = rnd.Next(2);
         if (tried[coordinate, direction]) continue;
         tried[coordinate, direction] = true;
         newResult = Shift(current, coordinate, direction, evaluator);
         if (newResult.value > current.value)
         {
             cont = true;
             break;
         }
     }
     if (!cont) return null;
     for (int i=0;i<10;i++)
     {
         var veryNew = Shift(newResult, coordinate, direction, evaluator);
         if (veryNew.value <= newResult.value) return newResult;
         newResult = veryNew;
     }
     return newResult;
 }
示例#13
0
        public static void Main()
        {
            maps = mapIndices
               .Select(z => Problems.LoadProblems()[z].ToMap(Seed))
               .ToArray();

            var vector = new double[WeightedMetric.KnownFunctions.Count()];
            for (int i=0;i<WeightedMetric.KnownFunctions.Count();i++)
            {
                var test = WeightedMetric.Test.Where(z => z.Function == WeightedMetric.KnownFunctions.ElementAt(i)).FirstOrDefault();
                if (test == null) continue;
                vector[i] = test.Weight;
            }

            Console.Write(Print(vector)+"\t BASELINE");
            baseline = Run(vector);
            var current = new Result { vector = vector, value = 1 };
            Console.WriteLine("  OK");
            while (true)
            {
                var newCurrent = Optimize(current, Evaluate);
                if (newCurrent != null)
                {
                    current = newCurrent;
                    Console.WriteLine(Print(current.vector) + "\t OPT\t" + current.value);
                    continue;
                }
                else
                {
                    Console.WriteLine(Print(current.vector) + "\t END\t" + current.value);
                    Console.ReadKey();
                    break;
                }
            }
        }
示例#14
0
		public Result<bool> Delete(string aSourceId, string rev, Result<bool> aResult)
		{
			ArgCheck.NotNullNorEmpty("aSourceId", aSourceId);

			Coroutine.Invoke(DeleteHelper, aSourceId, rev, aResult);
			return aResult;
		}
 public Yield GetArchiveFiles(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
     PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.ADMIN);
     IList<AttachmentBE> removedFiles = AttachmentBL.Instance.GetResources(DeletionFilter.DELETEDONLY, null, null);
     XDoc responseXml = AttachmentBL.Instance.GetFileXml(removedFiles, true, "archive", null, null);            
     response.Return(DreamMessage.Ok(responseXml));
     yield break;
 }
 public Yield GetSiteStatus(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
     PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.UPDATE);
     var status = new XDoc("status")
         .Elem("state", DekiContext.Current.Instance.Status);
     response.Return(DreamMessage.Ok(status));
     yield break;
 }
 public void OnSpecificationEnd(SpecificationInfo specification, Result result)
 {
   switch (result.Status)
   {
     case Status.Passing:
       _writer.WriteTestFinished(GetSpecificationName(specification), TimeSpan.Zero);
       break;
     case Status.NotImplemented:
       _writer.WriteTestIgnored(GetSpecificationName(specification), "(Not Implemented)");
       break;
     case Status.Ignored:
       _writer.WriteTestIgnored(GetSpecificationName(specification), "(Ignored)");
       break;
     default:
       if (result.Exception != null)
       {
         _writer.WriteTestFailed(GetSpecificationName(specification), 
           result.Exception.Message, result.Exception.StackTrace);
       }
       else
       {
         _writer.WriteTestFailed(GetSpecificationName(specification), "FAIL", "");
       }
       _failureOccured = true;
       break;
   }
 }
		public static AddressBookParsedResult parse(Result result)
		{
			string text = result.Text;
			if (text == null || !text.StartsWith("MECARD:"))
			{
				return null;
			}
			string[] array = AbstractDoCoMoResultParser.matchDoCoMoPrefixedField("N:", text, true);
			if (array == null)
			{
				return null;
			}
			string value_Renamed = AddressBookDoCoMoResultParser.parseName(array[0]);
			string pronunciation = AbstractDoCoMoResultParser.matchSingleDoCoMoPrefixedField("SOUND:", text, true);
			string[] phoneNumbers = AbstractDoCoMoResultParser.matchDoCoMoPrefixedField("TEL:", text, true);
			string[] emails = AbstractDoCoMoResultParser.matchDoCoMoPrefixedField("EMAIL:", text, true);
			string note = AbstractDoCoMoResultParser.matchSingleDoCoMoPrefixedField("NOTE:", text, false);
			string[] addresses = AbstractDoCoMoResultParser.matchDoCoMoPrefixedField("ADR:", text, true);
			string text2 = AbstractDoCoMoResultParser.matchSingleDoCoMoPrefixedField("BDAY:", text, true);
			if (text2 != null && !ResultParser.isStringOfDigits(text2, 8))
			{
				text2 = null;
			}
			string url = AbstractDoCoMoResultParser.matchSingleDoCoMoPrefixedField("URL:", text, true);
			string org = AbstractDoCoMoResultParser.matchSingleDoCoMoPrefixedField("ORG:", text, true);
			return new AddressBookParsedResult(ResultParser.maybeWrap(value_Renamed), pronunciation, phoneNumbers, emails, note, addresses, org, text2, null, url);
		}
示例#19
0
 private void FireOnResult(Result newResult)
 {
     if (OnResult != null)
     {
         OnResult(newResult);
     }
 }
示例#20
0
        /// <summary>
        /// 检查上传的图片是否合法
        /// </summary>
        /// <param name="postedFile"></param>
        /// <param name="errors"></param>
        public static void checkUploadPic( HttpFile postedFile, Result errors )
        {
            if (postedFile == null) {
                errors.Add( lang.get( "exPlsUpload" ) );
                return;
            }

            // 检查文件大小
            if (postedFile.ContentLength <= 1) {
                errors.Add( lang.get( "exPlsUpload" ) );
                return;
            }

            int uploadMax = 1024 * 1024 * config.Instance.Site.UploadPicMaxMB;
            if (postedFile.ContentLength > uploadMax) {
                errors.Add( lang.get( "exUploadMax" ) + " " + config.Instance.Site.UploadPicMaxMB + " MB" );
                return;
            }

            // TODO: (flash upload) application/octet-stream
            //if (postedFile.ContentType.ToLower().IndexOf( "image" ) < 0) {
            //    errors.Add( lang.get( "exPhotoFormatTip" ) );
            //    return;
            //}

            // 检查文件格式
            if (Uploader.isAllowedPic( postedFile ) == false) {
                errors.Add( lang.get( "exUploadType" ) + ":" + postedFile.FileName + "(" + postedFile.ContentType + ")" );
            }
        }
    public void OnSpecificationEnd(SpecificationInfo specification, Result result)
    {
      switch (result.Status)
      {
        case Status.Passing:
          break;
        case Status.NotImplemented:
          _writer.WriteTestIgnored(GetSpecificationName(specification), "(Not Implemented)");
          break;
        case Status.Ignored:
          _writer.WriteTestIgnored(GetSpecificationName(specification), "(Ignored)");
          break;
        default:
          if (result.Exception != null)
          {
            _writer.WriteTestFailed(GetSpecificationName(specification),
                                    result.Exception.Message,
                                    result.Exception.ToString());
          }
          else
          {
            _writer.WriteTestFailed(GetSpecificationName(specification), "FAIL", "");
          }
          _failureOccurred = true;
          break;
      }
      var duration = TimeSpan.FromMilliseconds(_timingListener.GetSpecificationTime(specification));

      _writer.WriteTestFinished(GetSpecificationName(specification), duration);
    }
        /// <summary>
        /// Interface implementation that takes a Static Driver Verifier log stream and converts
        ///  its data to a SARIF json stream. Read in Static Driver Verifier data from an input
        ///  stream and write Result objects.
        /// </summary>
        /// <param name="input">Stream of a Static Driver Verifier log</param>
        /// <param name="output">SARIF json stream of the converted Static Driver Verifier log</param>
        public override void Convert(Stream input, IResultLogWriter output)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            Result result = ProcessSdvDefectStream(input);
            var results = new Result[] { result };

            var tool = new Tool
            {
                Name = "StaticDriverVerifier",
            };

            var fileInfoFactory = new FileInfoFactory(null);
            Dictionary<string, FileData> fileDictionary = fileInfoFactory.Create(results);

            output.Initialize(id: null, correlationId: null);

            output.WriteTool(tool);
            if (fileDictionary != null && fileDictionary.Count > 0) { output.WriteFiles(fileDictionary); }

            output.OpenResults();
            output.WriteResults(results);
            output.CloseResults();
        }
示例#23
0
        public void KeyRatios()
        {
            // for calculation check see : https://docs.google.com/spreadsheets/d/1vYEfSleUjF4It_sB-obzRsosTXHEWrdFbhbHDNlNOCM/edit?usp=sharing
            rt = new Results();

            // get some trades
            List<Trade> fills = new List<Trade>(new Trade[] {
                // go long
                new TradeImpl(sym,p,s), // 100 @ $100
                // increase bet
                new TradeImpl(sym,p+inc,s*2),// 300 @ $100.066666
                // take some profits
                new TradeImpl(sym,p+inc*2,s*-1), // 200 @ 100.0666 (profit = 100 * (100.20 - 100.0666) = 13.34) / maxMIU(= 300*100.06666) = .04% ret
                // go flat (round turn)
                new TradeImpl(sym,p+inc*2,s*-2), // 0 @ 0
                // go short
                new TradeImpl(sym,p,s*-2), // -200 @ 100
                // decrease bet
                new TradeImpl(sym,p,s), // -100 @100
                // exit (round turn)
                new TradeImpl(sym,p+inc,s), // 0 @ 0 (gross profit = -0.10*100 = -$10)
                // do another entry
                new TradeImpl(sym,p,s)
            });

            // compute results
            rt = Results.ResultsFromTradeList(fills, g.d);
            // check ratios
#if DEBUG
            g.d(rt.ToString());
#endif
            Assert.AreEqual(-16.413m,rt.SharpeRatio, "bad sharpe ratio");
            Assert.AreEqual(-26.909m, rt.SortinoRatio, "bad sortino ratio");
        }
示例#24
0
        public Result<bool> delete_tacgia(int matacgia)
        {
            Result<bool> rs = new Result<bool>();
            try
            {
                var dt = db.tbl_tacgias.Where(o => o.matg == matacgia);
                if (dt.Count() > 0)
                {
                    foreach (tbl_tacgia item in dt)
                    {
                        db.tbl_tacgias.DeleteOnSubmit(item);
                    }
                    db.SubmitChanges();
                    rs.data = true;
                    rs.errcode = ErrorCode.sucess;
                }
                else
                {
                    rs.data = false;
                    rs.errcode = ErrorCode.NaN;
                    rs.errInfor = Constants.empty_data;
                }

                return rs;
            }
            catch (Exception e)
            {
                rs.data = false;
                rs.errcode = ErrorCode.fail;
                rs.errInfor = e.ToString();
                return rs;
            }
        }
 public Yield GetPageTags(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
     PageBE page = PageBL.AuthorizePage(DekiContext.Current.User, Permissions.READ, false);
     XUri href = DekiContext.Current.ApiUri.At("pages", page.ID.ToString(), "tags");
     XDoc doc = TagBL.GetTagListXml(TagBL.GetTagsForPage(page), "tags", href, false);
     response.Return(DreamMessage.Ok(doc));
     yield break;
 } 
示例#26
0
        public Result<bool> edit_tacgia(tacgia_ett tacgia)
        {
            Result<bool> rs = new Result<bool>();
            try
            {
                // find the only row to edit
                var dt = db.tbl_tacgias.Where(o => o.matg == tacgia.matacgia).SingleOrDefault();
                // if fields are null or "" then maintaining the old data;
                if (tacgia.tentacgia != null && tacgia.tentacgia != "")
                {
                    dt.tentg = tacgia.tentacgia;
                }
                if (tacgia.gioitinh != null && tacgia.gioitinh != "")
                {
                    dt.gioitinh = tacgia.gioitinh;
                }
                if (tacgia.diachi != null && tacgia.diachi != "")
                {
                    dt.diachi = tacgia.diachi;
                }

                db.SubmitChanges();
                rs.data = true;
                rs.errcode = ErrorCode.sucess;
                return rs;
            }
            catch (Exception e)
            {
                rs.data = false;
                rs.errcode = ErrorCode.fail;
                rs.errInfor = e.ToString();
                return rs;
            }
        }
        public void Store(Result result)
        {
            byte[] compressedString = StringCompression.Zip(result.CurrentHtml);

            if (compressedString.Length < 64000)
            {
                var resultEntity = new ResultEntity(
                    result.HttpStatusCode,
                    compressedString,
                    result.ElapsedTimeInMilliseconds,
                    result.HttpPostMethod,
                    result.Url,
                    result.ScenarioName,
                    result.TestRunGuid,
                    result.StepName,
                    result.Date);
                TableOperation insertOperation = TableOperation.Insert(resultEntity);
                _cloudTable.Execute(insertOperation);
            }
            else
            {
                var resultEntity = new ResultEntity(
                    result.HttpStatusCode,
                    StringCompression.Zip("The html was truncated before it was stored."),
                    result.ElapsedTimeInMilliseconds,
                    result.HttpPostMethod,
                    result.Url,
                    result.ScenarioName,
                    result.TestRunGuid,
                    result.StepName,
                    result.Date);
                TableOperation insertOperation = TableOperation.Insert(resultEntity);
                _cloudTable.Execute(insertOperation);
            }
        }
示例#28
0
 public Result Get([FromBody]HouseCategory value)
 {
     var r = new Result();
     try
     {
         using (var context = new GZJContext())
         {
             var entity = context.HouseCategories.SingleOrDefault(t => t.Id == value.Id);
             if (null == entity)
                 throw new Exception("数据不存在");
             r.data = new
             {
                 categoryname=entity.CategoryName,
                 id=entity.Id,
                 parentid=entity.ParentId,
                 memo=entity.Memo
             };
         }
         r.success = true;
         r.message = "";
     }
     catch (Exception ex)
     {
         r.message = ex.Message;
     }
     return r;
 }
示例#29
0
文件: Main.cs 项目: xxy1991/cozy
 public override List<Result> Query(Query query)
 {
     if (query.RawQuery == "mryj")
     {
         var model = Request(url_);
         var rl = new List<Result>();
         var r = new Result();
         r.Title = model.note;
         r.SubTitle = model.content;
         r.IcoPath = "[Res]:txt";
         r.Score = 100;
         r.Action = e =>
         {
             context_.Api.HideAndClear();
             try
             {
                 Clipboard.SetText(r.SubTitle);
                 return true;
             }
             catch (System.Runtime.InteropServices.ExternalException)
             {
                 return false;
             }
         };
         rl.Add(r);
         return rl;
     }
     return null;
 }
示例#30
0
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            if ((arguments == null) || (arguments.Count < 2))
            {
                result = Utility.WrongNumberOfArguments(
                    this, 1, arguments, "command");

                return ReturnCode.Error;
            }

            try
            {
                var processor = new CommandLineProcessor();
                var o = processor.Pharse(arguments.Select(argument => (string) argument).Skip(1).ToArray());
                if (!(o is string) && o is IEnumerable)
                    result = new StringList(o);
                else
                {
                    result = o == null ? "" : new Variant(o).ToString();
                }
            }
            catch (Exception exception)
            {
                Log.Error("Script error ", exception);
                result = "Error on command execution " + exception.Message;
            }
            return ReturnCode.Ok;
        }