Example #1
0
        public async Task <Ret> CheckConnectivityAsync()
        {
            try
            {
                var uri    = new UriString(Settings.Endpoint).Combine(ApiInfo.Prefix, "/Status");
                var client = WebRequest.CreateHttp(uri.ToString());
                using (var response = await client.GetResponseAsync())
                    using (var stream = response.GetResponseStream())
                    {
                        try
                        {
                            // Checando se a resposta é uma entidade (Entity) válida.
                            EntityParser.ParseEntity(stream);

                            // TODO: Futuramente a entidade pode ser investigada para
                            // determinar se é uma entidade compatível com a esperada
                            // para a consulta de status.

                            return(Ret.Ok());
                        }
                        catch (Exception ex)
                        {
                            ex.Trace();
                            return(Ret.Ok(HttpStatusCode.UnsupportedMediaType));
                        }
                    }
            }
            catch (Exception ex)
            {
                return(ex);
            }
        }
Example #2
0
        public async Task <Ret <Result> > TransferAsync(
            UriString route,
            string method      = MethodNames.Get,
            Entity requestData = null)
        {
            try
            {
                Ret ret = null;
                await DoRequestAsync(route, method, null, requestData, webResponse =>
                {
                    var isRedirect = ((int)webResponse.StatusCode / 100) == 3;
                    if (isRedirect)
                    {
                        var location = webResponse.Headers[HttpResponseHeader.Location];
                        var uri      = new Uri(location, UriKind.RelativeOrAbsolute);
                        ret          = Ret.Ok(uri, webResponse.StatusCode);
                    }
                    else
                    {
                        using (var stream = webResponse.GetResponseStream())
                        {
                            var entity = EntityParser.ParseEntity(stream);
                            ret        = Ret.Ok(entity, webResponse.StatusCode);
                        }
                    }
                });

                return(ret);
            }
            catch (Exception ex)
            {
                ex.Trace();
                return(ex);
            }
        }
Example #3
0
    // Use this for initialization
    void Start()
    {
        float account = 0;

        for (int i = 0; i < ms_count; i++)
        {
            account += ms_setRate[i];
        }

        m_stateAndRet = new Ret[ms_count];
        m_rateCounter = new float[ms_count];
        for (int i = 0; i < ms_count; i++)
        {
            ms_setRate[i] = ms_setRate[i] / account;

            m_stateAndRet[i] = new Ret(ms_count);

            for (int j = 0; j < ms_count; j++)
            {
                m_stateAndRet[i].ret[j] = 1f / ms_count;
            }
        }

        InitUI();

        m_lastTime = Time.realtimeSinceStartup;
    }
        private CswNbtView _getSiInspectionUserView(bool ReInit)
        {
            CswNbtView Ret = _getSystemView(CswEnumNbtSystemViewName.SIInspectionsbyUser);

            if (null == Ret)
            {
                CswNbtNode ChemSwAdminRoleNode = _CswNbtResources.Nodes.makeRoleNodeFromRoleName(CswNbtObjClassRole.ChemSWAdminRoleName);
                Ret = new CswNbtView(_CswNbtResources);
                Ret.saveNew(CswEnumNbtSystemViewName.SIInspectionsbyUser.ToString(), CswEnumNbtViewVisibility.Role, ChemSwAdminRoleNode.NodeId);
                Ret.Category = SiViewCategory;
                Ret.ViewMode = CswEnumNbtViewRenderingMode.List;
                ReInit       = true;
            }
            if (ReInit)
            {
                Ret.Root.ChildRelationships.Clear();
                CswNbtMetaDataObjectClass InspectionDesignOc = _CswNbtResources.MetaData.getObjectClass(CswEnumNbtObjectClass.InspectionDesignClass);
                CswNbtViewRelationship    InspectionDesignVr = Ret.AddViewRelationship(InspectionDesignOc, true);

                _addDefaultInspectionDesignViewPropsAndFilters(Ret, InspectionDesignVr, InspectionDesignOc);

                CswNbtMetaDataObjectClassProp InspectorOcp = InspectionDesignOc.getObjectClassProp(CswNbtObjClassInspectionDesign.PropertyName.Inspector);
                Ret.AddViewPropertyAndFilter(InspectionDesignVr, InspectorOcp, "me");

                Ret.save();
            }
            return(Ret);
        }
        private CswNbtView _siLocationsListView(bool ReInit)
        {
            CswNbtView Ret = _getSystemView(CswEnumNbtSystemViewName.SILocationsList);

            if (null == Ret)
            {
                CswNbtNode ChemSwAdminRoleNode =
                    _CswNbtResources.Nodes.makeRoleNodeFromRoleName(CswNbtObjClassRole.ChemSWAdminRoleName);
                Ret = new CswNbtView(_CswNbtResources);
                Ret.saveNew(CswEnumNbtSystemViewName.SILocationsList.ToString(), CswEnumNbtViewVisibility.Role,
                            ChemSwAdminRoleNode.NodeId);
                Ret.Category = SiViewCategory;
                Ret.ViewMode = CswEnumNbtViewRenderingMode.List;
                ReInit       = true;
            }
            if (ReInit)
            {
                Ret.Root.ChildRelationships.Clear();
                CswNbtMetaDataObjectClass     LocationOc          = _CswNbtResources.MetaData.getObjectClass(CswEnumNbtObjectClass.LocationClass);
                CswNbtViewRelationship        LocationVr          = Ret.AddViewRelationship(LocationOc, true);
                CswNbtMetaDataObjectClassProp LocationLocationOcp = LocationOc.getObjectClassProp(CswNbtObjClassLocation.PropertyName.Location);
                CswNbtViewProperty            LocationLocationVp  = Ret.AddViewProperty(LocationVr, LocationLocationOcp);
                LocationLocationVp.SortBy = true;
                Ret.save();
            }
            return(Ret);
        }
Example #6
0
        public async Task <Ret <byte[]> > TransferBytesAsync(
            UriString route,
            string method      = MethodNames.Get,
            byte[] requestData = null
            )
        {
            try
            {
                Ret ret = null;
                await DoRequestAsync(route, method, "application/octet-stream", requestData, async webResponse =>
                {
                    if (webResponse.StatusCode == HttpStatusCode.OK)
                    {
                        using (var stream = webResponse.GetResponseStream())
                            using (var memory = new MemoryStream())
                            {
                                await stream.CopyToAsync(memory);
                                ret = Ret.Ok(memory.ToArray(), webResponse.StatusCode);
                            }
                    }
                    else
                    {
                        ret = Ret.Fail(webResponse.StatusCode);
                    }
                });

                return(ret);
            }
            catch (Exception ex)
            {
                ex.Trace();
                return(ex);
            }
        }
Example #7
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (Ret != 0)
            {
                hash ^= Ret.GetHashCode();
            }
            if (userMoney_ != null)
            {
                hash ^= UserMoney.GetHashCode();
            }
            if (userDraw_ != null)
            {
                hash ^= UserDraw.GetHashCode();
            }
            hash ^= awards_.GetHashCode();
            if (userDrawInfo_ != null)
            {
                hash ^= UserDrawInfo.GetHashCode();
            }
            if (userItem_ != null)
            {
                hash ^= UserItem.GetHashCode();
            }
            return(hash);
        }
Example #8
0
        public static void Run()
        {
            int min    = 1000;
            int index  = 0;
            int index2 = 0;
            E   e      = new E(0, 0);

            for (int i = 1; i < Size; i++)
            {
                Console.WriteLine("Бежим по i = {0}", i);
                if (ls.Exists(x => x == i))
                {
                    Console.WriteLine("{0} содержится в стеке", i);
                    Ret ret = SearchMin(i);

                    if (ret.Mass < min)
                    {
                        min = ret.Mass;
                        if (min < 1000)
                        {
                            index  = i;
                            index2 = ret.number;
                            Console.WriteLine("Зашли в if, index = {0}", i);
                        }
                    }
                }
            }
            ls.Add(index2);
            qw.Enqueue(new E(index, index2));
            Console.WriteLine("Добавили в стек {0}, к дереву вершина {1} - {2} \n", min, index, index2);
        }
Example #9
0
 public string Run()
 {
     ret = new Ret();
     Directory.SetCurrentDirectory(Global.pwd);
     if (File.Exists(Global.path))
     {
         ret.msg.Add(GetFileInfo(Global.path));
     }
     else if (Directory.Exists(Global.path))
     {
         DirectoryInfo directory = new DirectoryInfo(Global.path);
         foreach (FileInfo f in directory.GetFiles())
         {
             ret.msg.Add(GetFileInfo(Path.Combine(Global.path, f.Name)));
         }
         foreach (DirectoryInfo d in directory.GetDirectories())
         {
             ret.msg.Add(GetDirectoryInfo(Path.Combine(Global.path, d.Name)));
         }
     }
     else
     {
         ret.code = -1;
     }
     return(Global.json_encode(ret));
 }
Example #10
0
        public Ret <ICollection <Group> > Create(Bulk <GroupForm.Create> forms)
        {
            var result = new List <Group>();

            // Validando
            foreach (var form in forms)
            {
                var name = form.Name?.Trim();

                if (string.IsNullOrWhiteSpace(name))
                {
                    return(Ret.Fail(HttpStatusCode.BadRequest, $"O nome de grupo deve ser informado."));
                }

                if (Db.Groups.Any(x => x.Name == name))
                {
                    return(Ret.Fail(HttpStatusCode.Conflict, $"Já existe um grupo de usuário com este nome."));
                }
            }

            // Editando
            foreach (var form in forms)
            {
                var group = new Group
                {
                    Id   = Db.GenerateId(),
                    Name = form.Name.Trim()
                };
                Db.Groups.Add(group);
                result.Add(group);
            }

            return(result);
        }
Example #11
0
        public static Ret <Entity> Create(HttpStatusCode status, string message, Exception exception)
        {
            var causes      = EnumerateCauses(message, exception).Distinct();
            var description =
                causes.Any()
          ? string.Join(Environment.NewLine, causes)
          : null;

            var entity = new Entity();

            entity.Class = ClassNames.Status;
            if ((int)status >= 400)
            {
                entity.Class.Add(ClassNames.Error);
            }

            entity.Properties = new PropertyMap();
            entity.Properties.Add("Code", (int)status);
            entity.Properties.Add("Status", status.ToString());

            if (description != null)
            {
                entity.Properties.Add("Description", description);
            }

            if (exception != null)
            {
                entity.Properties.Add("StackTrace", exception.GetStackTrace());
            }

            return(Ret.Create(status, entity));
        }
Example #12
0
        /// <summary>
        /// Copia o arquivo embarcado para o fluxo de saída.
        /// </summary>
        /// <param name="resourcePath">
        /// O caminho do recurso procurado, com pastas separadas por contra-barra (\).
        /// Exemplo: "\My\Folder\MyFile.txt"
        /// </param>
        /// <param name="writer">Fluxo para escrita do arquivo embarcado.</param>
        /// <returns>
        /// O status de leitura do arquivo.
        /// Em geral 200-OK caso o arquivo seja lido com sucesso
        /// ou 404-NotFound caso o arquivo não exista embarcado.
        /// </returns>
        public Ret LoadResource(string resourcePath, TextWriter writer)
        {
            try
            {
                string realPath;

                realPath = resourcePath.Replace(@"/", @"\");
                realPath = ResourcePaths.FirstOrDefault(x => x.EqualsIgnoreCase(realPath));

                if (realPath == null)
                {
                    return(Ret.NotFound());
                }

                var assembly = typeof(ResourceLoader).Assembly;
                using (var input = assembly.GetManifestResourceStream(realPath))
                {
                    var reader = new StreamReader(input);
                    reader.CopyTo(writer);
                }

                return(Ret.OK());
            }
            catch (Exception ex)
            {
                return(ex);
            }
        }
Example #13
0
        /// <summary>
        /// Retourne tous les RobotAction de la MainStrategy et des sous stratégies
        /// </summary>
        /// <returns>une liste de RobotAction ou null si la stratégie n'est pas définie</returns>
        public List <RobotAction> GetAllRobotAction()
        {
            List <RobotAction> Ret = null;

            if (_subStrategies != null)
            {
                foreach (SubStrategy currentSubStrategy in _subStrategies)
                {
                    if (currentSubStrategy.GetAllActions() != null)
                    {
                        foreach (RobotAction currentRobotAction in currentSubStrategy.GetAllActions())
                        {
                            if (Ret == null)
                            {
                                Ret = new List <RobotAction>();
                            }

                            Ret.Add(currentRobotAction);
                        }
                    }
                }
            }

            return(Ret);
        }
Example #14
0
        public Ret <ProjectHeader> LoadProjectHeader(string folder = ".")
        {
            try
            {
                bool ok;

                var svn = new Svn();
                svn.User = SvnUser ?? Svn.DefaultUser;
                svn.Pass = SvnPass ?? Svn.DefaultPass;
                ok       = svn.Fill();
                if (!ok)
                {
                    Ret.Fail();
                }

                var pack = new PackDm.PackDm();
                pack.PackConf = PackConf;
                pack.PackInfo = PackInfo;
                ok            = pack.Fill();
                if (!ok)
                {
                    Ret.Fail();
                }

                var header = LoadProjectHeader(svn, pack);
                return(header);
            }
            catch (Exception ex)
            {
                return(ex);
            }
        }
Example #15
0
        public static async Task SendEntityStatusAsync(this IResponse res, Ret ret)
        {
            var req    = res.Context.Request;
            var entity = Entity.Create(ret);

            await WriteEntityAsync(res, entity, ret.Status.Code);
        }
        public async Task Invoke(HttpContext httpContext)
        {
            try
            {
                var req   = httpContext.Request;
                var query = httpContext.Request.Query;

                var path       = (string)query["path"];
                var reverseUri = (string)query["reverseUri"];

                var isShowInfoOnly = (req.Method == "GET" && reverseUri == null);
                if (isShowInfoOnly)
                {
                    await SendProxyAsync(httpContext);
                }
                else
                {
                    await EditProxyAsync(httpContext);
                }
            }
            catch (Exception ex)
            {
                await SendStatusAsync(httpContext, Ret.Fail(ex));
            }
        }
Example #17
0
 /// <summary>
 /// 检查阈值
 /// 阈值数量、是否有0或负值、是否非递增
 /// </summary>
 /// <param name="ret"></param>
 public void CheckThresholds(out Ret ret)
 {
     if (count == 0)
     {
         ret = new Ret(LogLevel.Error, RET_COUNT_IS_0, "Thresholds count is 0");
         return;
     }
     for (int i = 0; i < count; i++)
     {
         if (_thresholds[i] <= 0)
         {
             ret = new Ret(LogLevel.Warning, RET_THRESHOLD_IS_LESS_EQUAL_0, "Level:" + i + " threshold is less than or equal to 0");
             return;
         }
         if (i > 0)
         {
             if (_thresholds[i] <= _thresholds[i - 1])
             {
                 ret = new Ret(LogLevel.Warning, RET_THRESHOLD_IS_LESS_EQUAL_PRE, "Level:" + i + " threshold is less than or equal to the previous one");
                 return;
             }
         }
     }
     ret = Ret.ok;
 }
Example #18
0
File: Ui.cs Project: blobject/mff
        Tie()
        {
            Ret ret = this.Control.Tie(this.Turn(true));

            if (ret == Ret.Tie)
            {
                this.Say(Res.Response, "Tied.", false);
                this.Stop(Res.Prompt, "Save before quitting?", false);
                Pin(0, Height + 2);
                return(true);
            }
            if (ret == Ret.Tying)
            {
                this.Say(Res.Response,
                         $"{this.Turn(false)} proposed a tie", true);
                if (this.Ask(Res.Prompt, "Accept?", true, false))
                {
                    return(this.Tie());
                }
                this.Control.Untie();
                this.Say(Res.Response, "Tie declined", true);
                this.Say(Res.Prompt, null, true);
            }
            return(false);
        }
Example #19
0
 public override int GetHashCode() {
   int hash = 1;
   if (Ret != 0) hash ^= Ret.GetHashCode();
   if (Count != 0) hash ^= Count.GetHashCode();
   hash ^= awards_.GetHashCode();
   return hash;
 }
        //
        // GET: /BindEmail/

        public ActionResult Index(string code)
        {
            var ret = new Ret();

            if (string.IsNullOrWhiteSpace(code))
            {
                ret.msg = "该链接已失效";
                return(View(ret));
            }
            var svc    = ServiceLocator.Resolve <IModelService>("Internal");
            var verify =
                svc.SelectOrEmpty(new EmailVerifyQuery()
            {
                Code           = code,
                Type           = (int)EmailVerifyTypes.TenantRegister,
                OrderDirection = OrderDirection.Desc,
                OrderField     = "ID"
            }).FirstOrDefault();

            if (verify == null)
            {
                ret.msg = "该链接已失效";
            }
            else
            {
                svc.Update(new Tenant()
                {
                    ID = verify.ReferID, EmailVerified = true
                });
                svc.Delete(verify);
                ret.success = true;
                ret.msg     = "恭喜您,邮箱验证成功";
            }
            return(View(ret));
        }
Example #21
0
        /// <summary>
        /// Localizar os nomes de arquivos que conferem com o filtro indicado.
        /// </summary>
        /// <param name="pathFilter">
        /// Filtro para pesquisa de arquivos.
        ///
        /// São suportados os caracteres curinga:
        /// *, para indicar um trecho de nome, **, para indicar qualquer quantidade
        /// de pastas no caminho, e ?, para indicar um único caracter na posição.
        ///
        /// Por exemplo: O filtro "\Path\*.txt" retorna todos os arquivos TXT dentro da
        /// pasta "Path". O filtro "\Path\**\*.txt" retorna todos os arquivos TXT dentro
        /// da pasta "Path" ou em qualquer outra pasta na hierarquia de "Path".
        /// </param>
        /// <returns>
        /// O status da pesquisa mais os arquivos lidos.
        /// Em geral 200-OK com a lista dos arquivos lidos ou 404-NotFound com uma
        /// lista vazia caso nada seja encontrado.
        /// </returns>
        public Ret <string[]> FindResources(string pathFilter)
        {
            try
            {
                pathFilter = pathFilter.Replace(@"/", @"\");

                if (!pathFilter.StartsWith(@"\"))
                {
                    pathFilter = $@"\**\{pathFilter}";
                }

                var pattern = pathFilter
                              .Replace(@".", @"[.]")
                              .Replace(@"**", @"§")
                              .Replace(@"*", @"[^\]*")
                              .Replace(@"\§", @"(|\.*)")
                              .Replace(@"?", @".")
                              .Replace(@"\", @"\\")
                ;

                var regex = new Regex($"^{pattern}$", RegexOptions.IgnoreCase);

                var files = (
                    from path in ResourcePaths
                    where regex.IsMatch(path)
                    select path
                    ).ToArray();

                return(files.Length > 0 ? Ret.OK(files) : Ret.NotFound(files));
            }
            catch (Exception ex)
            {
                return(Ret.FailWithValue(ex, new string[0]));
            }
        }
Example #22
0
        public Ret <ICollection <Group> > Edit(Bulk <GroupForm.BulkEdit, Group> edits)
        {
            var result = new List <Group>();

            // Validando
            foreach (var edit in edits)
            {
                edit.Record = Db.Groups.FirstOrDefault(x => x.Id == edit.Record.Id);
                if (edit.Record == null)
                {
                    return(Ret.Fail(HttpStatusCode.NotFound, $"O grupo de usuário não existe."));
                }

                var form  = edit.Form;
                var group = edit.Record;

                var name = form.Name ?? group.Name;

                if (string.IsNullOrWhiteSpace(name))
                {
                    return(Ret.Fail(HttpStatusCode.BadRequest, $"O nome do grupo de usuário deve ser informado."));
                }
            }

            // Editando
            foreach (var edit in edits)
            {
                var form  = edit.Form;
                var group = edit.Record;
                group.Name = (form.Name ?? group.Name)?.Trim();
                result.Add(group);
            }

            return(result);
        }
Example #23
0
    public string Run()
    {
        HttpContext.Current.Server.ScriptTimeout = 3600;
        Ret ret = new Ret();

        outfile = Path.Combine(Path.GetTempPath(), Global.sessionid + "_out");
        infile  = Path.Combine(Path.GetTempPath(), Global.sessionid + "_in");
        mut     = new Mutex(false, Global.sessionid + "_test123");
        using (File.Create(infile));
        using (File.Create(outfile));
        Socket client;

        try
        {
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.Connect(Global.rhost, Global.rport);
        }
        catch (Exception e)
        {
            ret.code = -1;
            ret.msg  = Convert.ToBase64String(Encoding.UTF8.GetBytes(e.ToString()));
            return(Global.json_encode(ret));
        }

        client.Blocking = false;
        Thread read_thread = new Thread(this.ReadToFile);

        read_thread.Start(client);
        while (File.Exists(infile) && File.Exists(outfile))
        {
            byte[] data;
            try
            {
                mut.WaitOne();
                data = File.ReadAllBytes(infile);
                File.WriteAllText(infile, "");
            }
            catch (Exception)
            {
                break;
            }finally{
                mut.ReleaseMutex();
            }
            if (data.Length > 0)
            {
                try{
                    client.Send(data);
                }catch (SocketException) { break; }
            }
            Thread.Sleep(100);
        }
        try
        {
            client.Shutdown(SocketShutdown.Both);
            client.Close();
        }
        catch (Exception) { }
        read_thread.Join(5000);
        return(Global.json_encode(ret));
    }
Example #24
0
 /// <summary>
 /// Request for a preform
 /// Find an unoccupied preform first
 /// </summary>
 /// <param name="state"></param>
 /// <param name="ret"></param>
 /// <returns></returns>
 public T Request(object state, out Ret ret)
 {
     for (int i = 0; i < maxCount; i++)
     {
         // If null, init and use it
         if (_preforms[i] == null)
         {
             _preforms[i]            = new T();
             _preforms[i].isOccupied = true;
             _preforms[i].localID    = i;
             _preforms[i].OnRequest(state);
             ret = Ret.ok;
             return(_preforms[i]);
         }
         // If not occupied, use it
         if (_preforms[i].isOccupied == false)
         {
             _preforms[i].isOccupied = true;
             _preforms[i].localID    = i;
             _preforms[i].OnRequest(state);
             ret = Ret.ok;
             return(_preforms[i]);
         }
     }
     ret = new Ret(LogLevel.Warning, RET_NO_UNOCCUPIED_PREFORM, "no unoccupied preform");
     return(null);
 }
Example #25
0
        public Ret <Entity> RenderEntity(HttpContext httpContext, string path)
        {
            if (httpContext.Request.Method != "GET")
            {
                return(Ret.Fail(HttpStatusCode.MethodNotAllowed));
            }

            var query = injector.CreateInstance(PaperType);

            try
            {
                var entity = new Entity();

                RenderEntity(httpContext, query, entity);

                return(entity);
            }
            catch (Exception ex)
            {
                return(ex);
            }
            finally
            {
                (query as IDisposable)?.Dispose();
            }
        }
Example #26
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (Ret != 0)
            {
                hash ^= Ret.GetHashCode();
            }
            if (ManagerIp.Length != 0)
            {
                hash ^= ManagerIp.GetHashCode();
            }
            if (ManagerPort != 0)
            {
                hash ^= ManagerPort.GetHashCode();
            }
            if (Uid != 0L)
            {
                hash ^= Uid.GetHashCode();
            }
            if (Key.Length != 0)
            {
                hash ^= Key.GetHashCode();
            }
            return(hash);
        }
Example #27
0
        public static bool Parse <T>(this string text, out T ret)
            where T : struct, IComparable, IFormattable, IConvertible
        {
            string key = typeof(T) + "_" + text;

            if (!cache.ContainsKey(key))
            {
                T    def     = default(T);
                bool success = false;
                try
                {
                    def     = (T)Enum.Parse(typeof(T), text);
                    success = true;
                }
                catch (Exception e)
                {
                    DLog.LogError(e);
                    ret = default(T);
                    return(false);
                }

                cache.Add(key, new Ret(success, def));
            }

            Ret r = cache[key];

            ret = (T)r.value;
            return(r.success);
        }
Example #28
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (Ret != 0)
            {
                hash ^= Ret.GetHashCode();
            }
            if (ConId != 0L)
            {
                hash ^= ConId.GetHashCode();
            }
            if (Uid != 0L)
            {
                hash ^= Uid.GetHashCode();
            }
            if (Key.Length != 0)
            {
                hash ^= Key.GetHashCode();
            }
            if (Ip.Length != 0)
            {
                hash ^= Ip.GetHashCode();
            }
            if (Port != 0)
            {
                hash ^= Port.GetHashCode();
            }
            return(hash);
        }
Example #29
0
        private Ret <Entity> ExecuteMethod(HttpContext httpContext, MethodInfo method)
        {
            try
            {
                var target = injector.CreateInstance(PaperType);
                try
                {
                    var ret = CreateParameters(httpContext, method);
                    if (ret.IsFault())
                    {
                        return(Ret.Throw(ret));
                    }

                    object[] parameters = ret.Data;
                    method.Invoke(target, parameters);
                }
                finally
                {
                    (target as IDisposable)?.Dispose();
                }

                return(Ret.Ok());
            }
            catch (Exception ex)
            {
                return(Ret.Fail(ex));
            }
        }
Example #30
0
 private void OnAffairNetworkAnomaly(Ret ret)
 {
     if (onAffairNetworkAnomaly == null)
     {
         return;
     }
     onAffairNetworkAnomaly(ret);
 }
Example #31
0
        /// <summary>
        /// Preko ove metode se izvrsava storica GetAdvertRaw.
        /// SqlDataAdapter.Fill varijanta
        /// Tablica 1 (Id int , GenerationId int , LanguageId int , HashCode varchar(2147483647) , SystemStatus char(1) , Active bit , Source nvarchar(250) , Language nvarchar(50) , GroupType nvarchar(250) , GroupSubType nvarchar(250) , SourceCategory nvarchar(1200) , Title nvarchar(250) , AccommType nvarchar(250) , AccommSubType nvarchar(250) , VacationType nvarchar(250) , AdvertCode nvarchar(50) , UrlLink nvarchar(1200) , PictureUrl nvarchar(1200) , Stars nvarchar(50) , LocationDesc nvarchar(2147483647) , Country nvarchar(250) , Region nvarchar(250) , Subregion nvarchar(250) , Island nvarchar(250) , City nvarchar(250) , PriceOld nvarchar(250) , PriceFrom nvarchar(250) , PriceDesc nvarchar(250) , Date1 nvarchar(250) , Date2 nvarchar(250) , DateDesc nvarchar(500) , DaysNum nvarchar(50) , Description nvarchar(2147483647) , Activities nvarchar(2147483647) , Facilities nvarchar(2147483647) , Beach nvarchar(250) , BeachDistanceM nvarchar(250) , DistanceFromCentreM nvarchar(250) , PetsDesc nvarchar(250) , InfoDesc nvarchar(250) , )
        /// </summary>
        /// <returns>Strong-typed lista koja predstavlja podatke koje je storica vratila.</returns>
        /// <param name="Id">int </param>
        /// <param name="userId">uniqueidentifier </param>
        public static List<GetAdvertRaw.Ret> Execute(System.Int32? Id, System.Guid? userId)
        {
            DateTime startTime = DateTime.Now;

            string cnnStr = autogenerated_Common_dblibrary.GetConnectionString();
            System.Transactions.TransactionOptions opt = new System.Transactions.TransactionOptions();
            opt.IsolationLevel = GetIsolationLevel();
            System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope(scopeOption, opt);
            using (scope)
            {
                using (SqlConnection cnn = new SqlConnection(cnnStr))
                {
                    SqlCommand cmd = new SqlCommand("GetAdvertRaw", cnn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    if (commandTimeout > -1)
                    {
                        cmd.CommandTimeout = commandTimeout;
                    }

                    SqlParameter paramId = cmd.Parameters.Add("@Id", SqlDbType.Int);
                    if (Id != null) paramId.Value = Id;
                    else paramId.Value = DBNull.Value;

                    SqlParameter paramuserId = cmd.Parameters.Add("@userId", SqlDbType.UniqueIdentifier);
                    if (userId != null) paramuserId.Value = userId;
                    else paramuserId.Value = DBNull.Value;

                    List<Ret> retVal = new List<Ret>();
                    cnn.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        object tmp;
                        Ret rv = new Ret();
                        tmp = reader["Id"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Id = (System.Int32)tmp;
                        tmp = reader["GenerationId"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.GenerationId = (System.Int32?)tmp;
                        tmp = reader["LanguageId"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.LanguageId = (System.Int32?)tmp;
                        tmp = reader["HashCode"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.HashCode = (System.String)tmp;
                        tmp = reader["SystemStatus"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.SystemStatus = (System.String)tmp;
                        tmp = reader["Active"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Active = (System.Boolean)tmp;
                        tmp = reader["Source"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Source = (System.String)tmp;
                        tmp = reader["Language"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Language = (System.String)tmp;
                        tmp = reader["GroupType"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.GroupType = (System.String)tmp;
                        tmp = reader["GroupSubType"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.GroupSubType = (System.String)tmp;
                        tmp = reader["SourceCategory"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.SourceCategory = (System.String)tmp;
                        tmp = reader["Title"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Title = (System.String)tmp;
                        tmp = reader["AccommType"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.AccommType = (System.String)tmp;
                        tmp = reader["AccommSubType"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.AccommSubType = (System.String)tmp;
                        tmp = reader["VacationType"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.VacationType = (System.String)tmp;
                        tmp = reader["AdvertCode"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.AdvertCode = (System.String)tmp;
                        tmp = reader["UrlLink"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.UrlLink = (System.String)tmp;
                        tmp = reader["PictureUrl"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.PictureUrl = (System.String)tmp;
                        tmp = reader["Stars"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Stars = (System.String)tmp;
                        tmp = reader["LocationDesc"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.LocationDesc = (System.String)tmp;
                        tmp = reader["Country"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Country = (System.String)tmp;
                        tmp = reader["Region"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Region = (System.String)tmp;
                        tmp = reader["Subregion"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Subregion = (System.String)tmp;
                        tmp = reader["Island"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Island = (System.String)tmp;
                        tmp = reader["City"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.City = (System.String)tmp;
                        tmp = reader["PriceOld"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.PriceOld = (System.String)tmp;
                        tmp = reader["PriceFrom"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.PriceFrom = (System.String)tmp;
                        tmp = reader["PriceDesc"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.PriceDesc = (System.String)tmp;
                        tmp = reader["Date1"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Date1 = (System.String)tmp;
                        tmp = reader["Date2"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Date2 = (System.String)tmp;
                        tmp = reader["DateDesc"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.DateDesc = (System.String)tmp;
                        tmp = reader["DaysNum"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.DaysNum = (System.String)tmp;
                        tmp = reader["Description"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Description = (System.String)tmp;
                        tmp = reader["Activities"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Activities = (System.String)tmp;
                        tmp = reader["Facilities"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Facilities = (System.String)tmp;
                        tmp = reader["Beach"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Beach = (System.String)tmp;
                        tmp = reader["BeachDistanceM"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.BeachDistanceM = (System.String)tmp;
                        tmp = reader["DistanceFromCentreM"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.DistanceFromCentreM = (System.String)tmp;
                        tmp = reader["PetsDesc"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.PetsDesc = (System.String)tmp;
                        tmp = reader["InfoDesc"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.InfoDesc = (System.String)tmp;
                        retVal.Add(rv);
                    }
                    reader.Close();
                    scope.Complete();

                    DateTime endTime = DateTime.Now;
                    if (autogenerated_Common_dblibrary.EnableProfiling
                        && autogenerated_Common_dblibrary.StoredProcedureEnd != null)
                    {
                        autogenerated_Common_dblibrary.StoredProcedureEnd("GetAdvertRaw", endTime.Subtract(startTime).TotalMilliseconds);
                    }

                    return retVal;
                }
            }
        }
Example #32
0
        /// <summary>
        /// Preko ove metode se izvrsava storica GetResults.
        /// SqlDataAdapter.Fill varijanta
        /// Tablica 1 (Id int , Title nvarchar(250) , Description nvarchar(2147483647) , PictureUrl nvarchar(1200) , Price decimal(15, 2) , PriceOld decimal(15, 2) , City nvarchar(150) , LocationDesc nvarchar(500) , CurrencyId int , AdvertRawId int , MatchCount int , Priority int , fwcnt int , SourceTitle nvarchar(250) , SourceUrl varchar(50) , CurrencySymbol nvarchar(5) , Row bigint , )
        /// </summary>
        /// <returns>Strong-typed lista koja predstavlja podatke koje je storica vratila.</returns>
        /// <param name="query">nvarchar(-1) </param>
        /// <param name="languageId">int </param>
        /// <param name="top">int </param>
        /// <param name="startRowIndex">int </param>
        /// <param name="maximumRows">int </param>
        /// <param name="orderBy">int </param>
        public static List<GetResults.Ret> Execute(System.String query, System.Int32? languageId, System.Int32? top, System.Int32? startRowIndex, System.Int32? maximumRows, System.Int32? orderBy, out System.String queryMessage)
        {
            CachedRanker ranker = CachedRanker.Instance;

            DateTime startTime = DateTime.Now;

            string cnnStr = autogenerated_Common_dblibrary.GetConnectionString();
            System.Transactions.TransactionOptions opt = new System.Transactions.TransactionOptions();
            opt.IsolationLevel = GetIsolationLevel();
            System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope(scopeOption, opt);
            using (scope)
            {
                using (SqlConnection cnn = new SqlConnection(cnnStr))
                {
                    List<Int32> scores = ranker.Search(query, (int)languageId, (int)startRowIndex, (int)maximumRows);

                    if (scores.Count == 0)
                    {
                        queryMessage = "";
                        return new List<Ret>();
                    }

                    String[] res = new String[scores.Count];
                    for (int i = 0; i < scores.Count; ++i)
                    {
                        res[i] = scores[i].ToString();
                    }

                    String cmdStr= String.Format(
                        "SELECT ad.*, so.Title SourceTitle, So.Url SourceUrl, cu.Symbol CurrencySymbol, ag.UrlTag AgencyUrlTag , ac.UrlTag AccommodationUrlTag " +
                        "FROM Advert ad " +
                        "LEFT JOIN Currency cu ON cu.Id = ad.CurrencyId " +
                        "LEFT JOIN AgencyUrlTag ag ON ag.AgencyId = ad.AccommodationId " +
                        "LEFT JOIN AccommodationUrlTag ac ON ac.AccommodationId = ad.AccommodationId " +
                        "LEFT JOIN Source so ON so.Id = ad.SourceId " +
                        "WHERE ad.Id in ({0})",
                        String.Join(", ", res));

                    SqlCommand cmd = new SqlCommand(cmdStr, cnn);

                    if (commandTimeout > -1)
                    {
                        cmd.CommandTimeout = commandTimeout;
                    }

                    List<Ret> retVal = new List<Ret>();

                    //if (startRowIndex != 0 || maximumRows != 9)
                    //{
                    //    queryMessage = "";
                    //    return retVal;
                    //}

                    cnn.Open();
                    SqlDataReader reader = cmd.ExecuteReader();

                    Dictionary<int, Ret> retValMap = new Dictionary<int, Ret>();

                    while (reader.Read())
                    {
                        object tmp;
                        Ret rv = new Ret();
                        tmp = reader["Id"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Id = (System.Int32)tmp;
                        tmp = reader["Title"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Title = (System.String)tmp;
                        tmp = reader["AccommodationType"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.AccommType = (System.String)tmp;
                        tmp = reader["AdvertInfoId"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.AdvertInfoId = (System.Int32?)tmp;
                        tmp = reader["CapacityMin"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.CapacityMin = (System.Int32?)tmp;
                        tmp = reader["CapacityMax"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.CapacityMax = (System.Int32?)tmp;

                        tmp = reader["PlaceberryAdvert"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.PlaceberryAdvert = (System.Boolean)tmp;
                        tmp = reader["AgencyId"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.AgencyId = (System.Int32?)tmp;
                        tmp = reader["AgencyName"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.AgencyName = (System.String)tmp;
                        tmp = reader["AccommodationId"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.AccommodationId = (System.Int32?)tmp;

                        tmp = reader["Description"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Description = (System.String)tmp;
                        tmp = reader["LanguageId"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.LanguageId = (System.Int32)tmp;

                        tmp = reader["PictureUrl"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.PictureUrl = (System.String)tmp;
                        tmp = reader["Price"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Price = (System.Decimal?)tmp;
                        tmp = reader["PriceOld"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.PriceOld =  (System.Decimal?)tmp;

                        tmp = reader["Country"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Country = (System.String)tmp;
                        tmp = reader["Region"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Region = (System.String)tmp;
                        tmp = reader["Island"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.Island = (System.String)tmp;
                        tmp = reader["City"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.City = (System.String)tmp;

                        tmp = reader["CurrencyId"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.CurrencyId = (System.Int32?)tmp;
                        tmp = reader["AdvertRawId"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.AdvertRawId = (System.Int32?)tmp;

                        tmp = reader["SourceTitle"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.SourceTitle = (System.String)tmp;
                        tmp = reader["SourceUrl"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.SourceUrl = (System.String)tmp;
                        tmp = reader["CurrencySymbol"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.CurrencySymbol = (System.String)tmp;

                        tmp = reader["AgencyUrlTag"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.AgencyUrlTag = (System.String)tmp;
                        tmp = reader["AccommodationUrlTag"];
                        if (tmp == DBNull.Value) tmp = null;
                        rv.AccommodationUrlTag = (System.String)tmp;

                        retValMap[rv.Id] = rv;
                    }
                    reader.Close();
                    scope.Complete();

                    foreach (int id in scores)
                    {
                        retVal.Add(retValMap[id]);
                    }

                    queryMessage = string.Empty;

                    DateTime endTime = DateTime.Now;
                    if (autogenerated_Common_dblibrary.EnableProfiling
                        && autogenerated_Common_dblibrary.StoredProcedureEnd != null)
                    {
                        autogenerated_Common_dblibrary.StoredProcedureEnd("GetResults", endTime.Subtract(startTime).TotalMilliseconds);
                    }

                    return retVal;
                }
            }
        }
Example #33
0
 //格式化卡
 public Ret FormatGasCard(
     string factory,     //厂家
     string kmm,         //卡密码,写卡后返回新密码
     string kh,          //卡号
     string dqdm         //地区代码,从气表管理里取
     )
 {
     Ret ret = new Ret();
     try
     {
         ICard card = GetCard(factory);
         int r = card.FormatGasCard(Port, Baud, kmm, kh, dqdm);
         if (r < 0)
         {
             ret.Err = FindErrorInfo(r);
         }
         return ret;
     }
     catch (Exception e)
     {
         Log.Debug("FormatCard exception");
         ret.Exception = e.Message;
         return ret;
     }
 }