Exemple #1
0
        public static string Run(CommandParameter commandParam)
        {
            string result = "";
            try
            {
                Command command = FindCommand(commandParam.CommandName);

                if (command != null)
                {
                    lock (command.lockHelper)
                    {
                        #region 任务的通用校验
                        //如果任务需要校验callId
                        if (command.CallIdCheck)
                        {
                            //如果CallId为不合法的值,或者当前CallId代表的时间是上次CallId的10秒(估算值)以前,表示该CallId已经超过时限
                            if (commandParam.CallId <= 0 || commandParam.CallId <= command.LastCallId - GetDelayValue(command.LastCallId.ToString().Length, 10))
                                return Util.CreateErrorMessage(ErrorType.API_EC_CALLID, commandParam.ParamList);

                            command.LastCallId = commandParam.CallId;
                        }
                        #endregion
                        command.Run(commandParam, ref result);
                    }
                }
                else
                    result = Util.CreateErrorMessage(ErrorType.API_EC_METHOD, commandParam.ParamList);
            }
            catch
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_UNKNOWN, commandParam.ParamList);
            }
            return result;
        }
Exemple #2
0
        public override bool Run(CommandParameter commandParam, ref string result)
        {
            string[] actionList = { "connect", "qqgroup" };
            string action = "";

            foreach (string act in actionList)
            {
                if (commandParam.CloudParams.IndexOf(string.Format("\"{0}\"", act)) != -1)
                {
                    action = act;
                    break;
                }
            }
            int enable = commandParam.CloudParams.IndexOf(string.Format("\"{0}\"", "normal")) != -1 ? 1 : 0;

            DiscuzCloudConfigInfo config = DiscuzCloudConfigs.GetConfig();
            bool changed = false;
            switch (action)
            {
                case "connect": config.Connectenabled = enable; changed = true; break;
            }
            if (changed)
            {
                DiscuzCloudConfigs.SaveConfig(config);
                DiscuzCloudConfigs.ResetConfig();
            }
            result = CloudUtils.GetCloudResponse<bool>(true);
            return true;
        }
        public MoviePicker2()
        {
            Parameter = new CommandParameter {CanEditBeExecuted = true};
            InitializeComponent();

            SetupForm();
        }
Exemple #4
0
        public override bool Run(CommandParameter commandParam, ref string result)
        {
            DiscuzCloudConfigInfo config = DiscuzCloudConfigs.GetConfig();
            config.Cloudenabled = 1;
            DiscuzCloudConfigs.SaveConfig(config);
            DiscuzCloudConfigs.ResetConfig();

            result = CloudUtils.GetCloudResponse<bool>(Utils.UrlDecode(commandParam.CloudParams) == "[]");
            return true;
        }
Exemple #5
0
        public void TestFirstGuidConversionSuccess() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "9D2B0228-4D0D-4C23-8B49-01A698857709"
                    }
                }
            };

            Assert.AreEqual(new Guid("9D2B0228-4D0D-4C23-8B49-01A698857709"), parameter.First<Guid>());
        }
Exemple #6
0
        public void TestFirstEnumConversionSuccess() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "Six"
                    }
                }
            };

            Assert.AreEqual(ExecutableEnum.Six, parameter.First<ExecutableEnum>());
        }
        public void TestFirstDateTimeConversionSuccess() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "2014-04-14 13:50:59"
                    }
                }
            };

            Assert.AreEqual(DateTime.Parse("2014-04-14 13:50:59"), parameter.First<DateTime>());
        }
Exemple #8
0
        public void TestFirstGuidConversionFailed() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "Invalid"
                    }
                }
            };

            Assert.AreEqual(default(Guid), parameter.First<Guid>());
        }
Exemple #9
0
        public override bool Run(CommandParameter commandParam, ref string result)
        {
            if (commandParam.GetDNTParam("auth_token") == null)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return false;
            }

            string authToken = commandParam.GetDNTParam("auth_token").ToString().Replace("[", "+");
            string a = Discuz.Common.DES.Decode(authToken, commandParam.AppInfo.Secret.Substring(0, 10));
            string[] userstr = a.Split(',');
            if (userstr.Length != 3)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return false;
            }

            int olid = Utils.StrToInt(userstr[0], -1);
            OnlineUserInfo oluser = OnlineUsers.GetOnlineUser(olid);
            if (oluser == null)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_SESSIONKEY, commandParam.ParamList);
                return false;
            }
            string time = DateTime.Parse(oluser.Lastupdatetime).ToString("yyyy-MM-dd HH:mm:ss");
            if (time != userstr[1])
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return false;
            }
            byte[] md5_result = System.Security.Cryptography.MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(olid.ToString() + commandParam.AppInfo.Secret));

            StringBuilder sessionkey_builder = new StringBuilder();

            foreach (byte b in md5_result)
                sessionkey_builder.Append(b.ToString("x2"));

            string sessionkey = string.Format("{0}-{1}", sessionkey_builder.ToString(), oluser.Userid.ToString());
            SessionInfo session = new SessionInfo();
            session.SessionKey = sessionkey;
            session.UId = oluser.Userid;
            session.UserName = oluser.Username;
            session.Expires = Utils.StrToInt(userstr[2], 0);

            if (commandParam.Format == FormatType.JSON)
                result = string.Format(@"{{""session_key"":""{0}"",""uid"":{1},""user_name"":""{2}"",""expires"":{3}}}", sessionkey, commandParam.LocalUid, session.UserName, session.Expires);
            else
                result = SerializationHelper.Serialize(session);

            OnlineUsers.UpdateAction(olid, UserAction.Login.ActionID, 0, GeneralConfigs.GetConfig().Onlinetimeout);
            return true;
        }
Exemple #10
0
        public void TestHasManyEnumConversionFailed() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "Six",
                        "Seven",
                        "Invalid"
                    }
                }
            };

            Assert.IsFalse(parameter.HasMany<ExecutableEnum>());
        }
        public void TestFirstKnownTypeSuccess() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "1",
                        "Anything",
                        "Nothing"
                    }
                }
            };

            Assert.AreEqual("1", parameter.First<String>(false));
        }
        public void TestHashManyKnownTypeSuccess() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "1",
                        "Anything",
                        "Nothing"
                    }
                }
            };

            Assert.IsTrue(parameter.HasMany<String>(false));
        }
        public void TestAllIntegerConversionFailure() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "1",
                        "2",
                        "Invalid"
                    }
                }
            };

            var items = parameter.All(typeof (int)) as List<Object>;

            Assert.IsNull(items);
        }
Exemple #14
0
        public void TestAllEnumConversionSuccess() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "Six",
                        "Seven"
                    }
                }
            };

            var items = (List<Object>)parameter.All(typeof (ExecutableEnum));

            Assert.AreEqual(ExecutableEnum.Six, items[0]);
            Assert.AreEqual(ExecutableEnum.Seven, items[1]);
        }
        public void TestAllDateTimeConversionFailure() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "2014-04-14 13:50:59",
                        "2014-04-11 03:23:13",
                        "Invalid"
                    }
                }
            };

            var items = parameter.All(typeof(DateTime)) as List<Object>;

            Assert.IsNull(items);
        }
Exemple #16
0
		protected void ExecuteCommand(CommandParameter<object> parameter)
		{
			if (Command == null)
				return;

			var routedCommand = Command as RoutedCommand;
			if (routedCommand != null)
			{
				routedCommand.Execute(parameter, CommandTarget);
			}
			else
			{
				Command.Execute(parameter);
			}
		}
Exemple #17
0
        public void TestAllGuidConversionFailure() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "9D2B0228-4D0D-4C23-8B49-01A698857709",
                        "f380eb1e-1438-48c0-8c3d-ad55f2d40538",
                        "Invalid"
                    }
                }
            };

            var items = parameter.All(typeof(Guid)) as List<Object>;

            Assert.IsNull(items);
        }
Exemple #18
0
 public static string Run(CommandParameter commandParam)
 {
     string result = "";
     try
     {
         Command command = FindCommand(commandParam.Method);
         if (command != null)
         {
             command.Run(commandParam, ref result);
         }
     }
     catch
     {
     }
     return result;
 }
Exemple #19
0
        public void TestAllGuidConversionSuccess() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "9D2B0228-4D0D-4C23-8B49-01A698857709",
                        "f380eb1e-1438-48c0-8c3d-ad55f2d40538",
                        "76268850-2029-4b5f-b421-5b5ee4f17b6b"
                    }
                }
            };
            
            var list = (List<Object>)parameter.All(typeof(Guid));

            Assert.AreEqual(new Guid("9D2B0228-4D0D-4C23-8B49-01A698857709"), list[0]);
            Assert.AreEqual(new Guid("f380eb1e-1438-48c0-8c3d-ad55f2d40538"), list[1]);
            Assert.AreEqual(new Guid("76268850-2029-4b5f-b421-5b5ee4f17b6b"), list[2]);
        }
        public void TestAllKnownTypeSuccess() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "1",
                        "Anything",
                        "Nothing"
                    }
                }
            };

            List<String> items = ((List<Object>) parameter.All(typeof (String), false)).Cast<String>().ToList();

            Assert.AreEqual("1", items[0]);
            Assert.AreEqual("Anything", items[1]);
            Assert.AreEqual("Nothing", items[2]);
        }
        public void TestAllDateTimeConversionSuccess() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "2014-04-14 13:50:59",
                        "2014-04-11 03:23:13",
                        "2014-04-10 03:23:13"
                    }
                }
            };
            
            var list = (List<Object>)parameter.All(typeof(DateTime));

            Assert.AreEqual(DateTime.Parse("2014-04-14 13:50:59"), list[0]);
            Assert.AreEqual(DateTime.Parse("2014-04-11 03:23:13"), list[1]);
            Assert.AreEqual(DateTime.Parse("2014-04-10 03:23:13"), list[2]);
        }
        public void TestAllIntegerConversionSuccess() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "1",
                        "2",
                        "3"
                    }
                }
            };

            var list = (List<Object>)parameter.All(typeof (int));

            Assert.AreEqual(1, list[0]);
            Assert.AreEqual(2, list[1]);
            Assert.AreEqual(3, list[2]);
        }
Exemple #23
0
        public override bool Run(CommandParameter commandParam, ref string result)
        {
            if (commandParam.AppInfo.ApplicationType == (int)ApplicationType.WEB)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PERMISSION_DENIED, commandParam.ParamList);
                return false;
            }
            TokenInfo token = new TokenInfo();

            if (System.Web.HttpContext.Current.Request.Cookies["dnt"] == null || System.Web.HttpContext.Current.Request.Cookies["dnt"]["expires"] == null)
            {
                token.Token = "";
                result = commandParam.Format == FormatType.JSON ? string.Empty : SerializationHelper.Serialize(token);
                return true;
            }

            OnlineUserInfo oluserinfo = OnlineUsers.UpdateInfo(commandParam.GeneralConfig.Passwordkey, commandParam.GeneralConfig.Onlinetimeout);
            int olid = oluserinfo.Olid;

            string expires = string.Empty;
            DateTime expireUTCTime;

            expires = System.Web.HttpContext.Current.Request.Cookies["dnt"]["expires"].ToString();
            ShortUserInfo userinfo = Discuz.Forum.Users.GetShortUserInfo(oluserinfo.Userid);
            expireUTCTime = DateTime.Parse(userinfo.Lastvisit).ToUniversalTime().AddSeconds(Convert.ToDouble(expires));
            expires = Utils.ConvertToUnixTimestamp(expireUTCTime).ToString();

            string time = string.Empty;
            if (oluserinfo == null)
                time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            else
                time = DateTime.Parse(oluserinfo.Lastupdatetime).ToString("yyyy-MM-dd HH:mm:ss");

            string authToken = Common.DES.Encode(string.Format("{0},{1},{2}", olid.ToString(), time, expires), commandParam.AppInfo.Secret.Substring(0, 10)).Replace("+", "[");
            token.Token = authToken;
            result = commandParam.Format == FormatType.JSON ? authToken : SerializationHelper.Serialize(token);
            return true;
        }
 public ApplicationDeleteRequest()
 {
     ShortName = CommandParameter.Output(SqlDbType.VarChar, 20);
 }
        public override ICommandResult Execute(ExecutionInformation info, IEnumerable <ICommand> arguments, IEnumerable <CommandResultType> returnTypes)
        {
            // Make arguments lazy, we only want to execute them once
            arguments = arguments.Select(c => new LazyCommand(c));
            int availableArguments;

            object[] parameters = FitArguments(info, arguments, returnTypes, out availableArguments);

            // Check if we were able to set enough arguments
            if (availableArguments < Math.Min(parameters.Length, RequiredParameters))
            {
                if (returnTypes.Contains(CommandResultType.Command))
                {
                    if (!arguments.Any())
                    {
                        return(new CommandCommandResult(this));
                    }
                    return(new CommandCommandResult(new AppliedCommand(this, arguments)));
                }
                throw new CommandException("Not enough arguments for function " + internCommand.Name);
            }

            if (CommandReturn == typeof(ICommandResult))
            {
                return((ICommandResult)ExecuteFunction(parameters));
            }

            bool   executed = false;
            object result   = null;

            // Take first fitting command result
            foreach (var returnType in returnTypes)
            {
                switch (returnType)
                {
                case CommandResultType.Command:
                    // Return a command if we can take more arguments
                    if (CommandParameter.Any(p => p == typeof(string[])) || availableArguments < NormalParameters)
                    {
                        return(new CommandCommandResult(new AppliedCommand(this, arguments)));
                    }
                    break;

                case CommandResultType.Empty:
                    if (!executed)
                    {
                        ExecuteFunction(parameters);
                    }
                    return(new EmptyCommandResult());

                case CommandResultType.String:
                    if (!executed)
                    {
                        result   = ExecuteFunction(parameters);
                        executed = true;
                    }
                    if (result != null && !string.IsNullOrEmpty(result.ToString()))
                    {
                        return(new StringCommandResult(result.ToString()));
                    }
                    break;
                }
            }
            // Try to return an empty string
            if (returnTypes.Contains(CommandResultType.String) && executed)
            {
                return(new StringCommandResult(""));
            }
            throw new CommandException("Couldn't find a proper command result for function " + internCommand.Name);
        }
Exemple #26
0
 public void SetUp()
 {
     _parameter = new CommandParameter("ColumnName", 1);
 }
Exemple #27
0
        public override bool Run(CommandParameter commandParam, ref string result)
        {
            if (commandParam.GetDNTParam("auth_token") == null)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return(false);
            }

            string authToken = commandParam.GetDNTParam("auth_token").ToString().Replace("[", "+");
            string a         = Discuz.Common.DES.Decode(authToken, commandParam.AppInfo.Secret.Substring(0, 10));

            string[] userstr = a.Split(',');
            if (userstr.Length != 3)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return(false);
            }

            int            olid   = Utils.StrToInt(userstr[0], -1);
            OnlineUserInfo oluser = OnlineUsers.GetOnlineUser(olid);

            if (oluser == null)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_SESSIONKEY, commandParam.ParamList);
                return(false);
            }
            string time = DateTime.Parse(oluser.Lastupdatetime).ToString("yyyy-MM-dd HH:mm:ss");

            if (time != userstr[1])
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return(false);
            }
            byte[] md5_result = System.Security.Cryptography.MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(olid.ToString() + commandParam.AppInfo.Secret));

            StringBuilder sessionkey_builder = new StringBuilder();

            foreach (byte b in md5_result)
            {
                sessionkey_builder.Append(b.ToString("x2"));
            }

            string      sessionkey = string.Format("{0}-{1}", sessionkey_builder.ToString(), oluser.Userid.ToString());
            SessionInfo session    = new SessionInfo();

            session.SessionKey = sessionkey;
            session.UId        = oluser.Userid;
            session.UserName   = oluser.Username;
            session.Expires    = Utils.StrToInt(userstr[2], 0);

            if (commandParam.Format == FormatType.JSON)
            {
                result = string.Format(@"{{""session_key"":""{0}"",""uid"":{1},""user_name"":""{2}"",""expires"":{3}}}", sessionkey, commandParam.LocalUid, session.UserName, session.Expires);
            }
            else
            {
                result = SerializationHelper.Serialize(session);
            }

            OnlineUsers.UpdateAction(olid, UserAction.Login.ActionID, 0, GeneralConfigs.GetConfig().Onlinetimeout);
            return(true);
        }
Exemple #28
0
        /*
         * Method:	    RunScript
         * Purpose:	    Creates two shared datasources on report server in home folder, by invoking powershell runspace
         * Parameters:	sctipt string, int mode 1 - create ERP datasource 2 - create LYNQ datasource, reporting server URL as a string, server name as a string, database name as a string,
         *              user name as a string, password as a string
         * Return:		void
         */
        public static ErrorInfo RunScript(string scriptText, int mode, string txtReportingServerURL, string txtServer, string txtDatabase, string txtUserName, string txtPassword, string txtSSRSUserName, string txtSSRSPassword)
        {
            ErrorInfo result = new ErrorInfo();
            // create Powershell runspace
            Runspace runspace = RunspaceFactory.CreateRunspace();

            // open it
            runspace.Open();

            // create a pipeline and feed it the script text
            Pipeline pipeline = runspace.CreatePipeline();

            pipeline.Commands.AddScript(scriptText);


            pipeline.Invoke();
            pipeline.Commands.Clear();


            Command myCommand = new Command("New-SSRSDataSource");

            if (mode == 1)
            {
                CommandParameter dsName = new CommandParameter("DataSourceName", _const.C_ERPSharedDSName);
                myCommand.Parameters.Add(dsName);

                CommandParameter dsPath = new CommandParameter("path", _const.C_SharedDSPath);
                myCommand.Parameters.Add(dsPath);
                CommandParameter dsReportWebService = new CommandParameter("reportWebService", txtReportingServerURL);
                myCommand.Parameters.Add(dsReportWebService);
                CommandParameter dsConnectionString = new CommandParameter("connectString", "Data Source = " + txtServer + "; Initial Catalog = " + txtDatabase);
                myCommand.Parameters.Add(dsConnectionString);
            }
            else
            {
                CommandParameter dsName = new CommandParameter("DataSourceName", _const.C_LYNQSharedDSName);
                myCommand.Parameters.Add(dsName);
                CommandParameter dsPath = new CommandParameter("path", _const.C_SharedDSPath);
                myCommand.Parameters.Add(dsPath);
                CommandParameter dsReportWebService = new CommandParameter("reportWebService", txtReportingServerURL);
                myCommand.Parameters.Add(dsReportWebService);
                CommandParameter dsConnectionString = new CommandParameter("connectString", "Data Source = " + txtServer + "; Initial Catalog = " + txtDatabase);
                myCommand.Parameters.Add(dsConnectionString);
            }
            CommandParameter dsUserName = new CommandParameter("username", txtUserName);

            myCommand.Parameters.Add(dsUserName);
            CommandParameter dsPassword = new CommandParameter("password", txtPassword);

            myCommand.Parameters.Add(dsPassword);
            CommandParameter dsExtension = new CommandParameter("Extension", "SQL");

            myCommand.Parameters.Add(dsExtension);
            string passwordString = txtSSRSPassword;

            // create credential variable for connection to ssrs server
            System.Security.SecureString password = new System.Security.SecureString();
            for (int i = 0; i < passwordString.Length; i++)
            {
                password.AppendChar(passwordString[i]);
            }
            password.MakeReadOnly();
            PSCredential     Credential    = new PSCredential(txtSSRSUserName, password);
            CommandParameter dsCredentials = new CommandParameter("credentials", Credential);

            myCommand.Parameters.Add(dsCredentials);

            Pipeline pipeline1 = runspace.CreatePipeline();

            pipeline1.Commands.Add(myCommand);
            try
            {
                pipeline1.Invoke();
                result.IsOk = true;
                return(result);
            }
            catch (System.Management.Automation.CmdletInvocationException ex)
            {
                result.IsOk       = false;
                result.ErrCode    = ex.Message;
                result.ErrMessage = "Invalid URL address or SSRS credentials";

                return(result);
            }
            catch (Exception ex)
            {
                result.IsOk       = false;
                result.ErrMessage = ex.Message;
                return(result);
            }
            // close the runspace
            finally
            {
                runspace.Close();
            }
        }
Exemple #29
0
 public ByIdFilter(T value, NpgsqlDbType dbType)
 {
     _parameter = new CommandParameter(value, dbType);
 }
Exemple #30
0
        public override bool Run(CommandParameter commandParam, ref string result)
        {
            if (commandParam.AppInfo.ApplicationType == (int)ApplicationType.DESKTOP)
            {
                if (commandParam.LocalUid < 1)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_SESSIONKEY, commandParam.ParamList);
                    return(false);
                }

                ShortUserInfo userInfo = Users.GetShortUserInfo(commandParam.LocalUid);
                if (userInfo == null || userInfo.Adminid != 1)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_PERMISSION_DENIED, commandParam.ParamList);
                    return(false);
                }
            }

            if (!commandParam.CheckRequiredParams("forum_info"))
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return(false);
            }

            Forum forum;

            try
            {
                forum = JavaScriptConvert.DeserializeObject <Forum>(commandParam.GetDNTParam("forum_info").ToString());
            }
            catch
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return(false);
            }

            if (forum == null || string.IsNullOrEmpty(forum.Name))
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return(false);
            }

            if (!Utils.StrIsNullOrEmpty(forum.RewriteName) && Discuz.Forum.Forums.CheckRewriteNameInvalid(forum.RewriteName))
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_REWRITENAME, commandParam.ParamList);
                return(false);
            }

            int fid;

            if (forum.ParentId > 0)
            {
                #region 添加与当前论坛同级的论坛

                //添加与当前论坛同级的论坛
                ForumInfo forumInfo = Discuz.Forum.Forums.GetForumInfo(forum.ParentId);

                //找出当前要插入的记录所用的FID
                string parentidlist = null;
                parentidlist = forumInfo.Parentidlist == "0" ? forumInfo.Fid.ToString() : forumInfo.Parentidlist + "," + forumInfo.Fid;

                DataTable dt = AdminForums.GetMaxDisplayOrder(forum.ParentId);
                int       maxdisplayorder = (dt.Rows.Count > 0) && (dt.Rows[0][0].ToString() != "") ? Convert.ToInt32(dt.Rows[0][0]) : forumInfo.Displayorder;

                AdminForums.UpdateForumsDisplayOrder(maxdisplayorder);
                fid = ForumsCommandUtils.InsertForum(forum, forumInfo.Layer + 1, parentidlist, 0, maxdisplayorder + 1);

                AdminForums.SetSubForumCount(forumInfo.Fid);
                #endregion
            }
            else
            {
                #region  根论坛插入

                int maxdisplayorder = AdminForums.GetMaxDisplayOrder();
                fid = ForumsCommandUtils.InsertForum(forum, 0, "0", 0, maxdisplayorder);

                #endregion
            }
            ForumCreateResponse fcr = new ForumCreateResponse();
            fcr.Fid = fid;
            fcr.Url = Utils.GetRootUrl(BaseConfigs.GetForumPath) + Urls.ShowForumAspxRewrite(fid, 1, forum.RewriteName);
            result  = commandParam.Format == FormatType.JSON ? JavaScriptConvert.SerializeObject(fcr) : SerializationHelper.Serialize(fcr);
            return(true);
        }
        private async void sendDeviceMetaData()
        {
            DeviceProperties device     = new DeviceProperties();
            Thermostat       thermostat = new Thermostat();

            thermostat.ObjectType        = "DeviceInfo";
            thermostat.IsSimulatedDevice = false;
            thermostat.Version           = "1.0";

            device.HubEnabledState = true;
            device.DeviceID        = deviceId;
            device.Manufacturer    = "Microsoft";
            device.ModelNumber     = "Lumia950";
            device.SerialNumber    = "5849735293875";
            device.FirmwareVersion = "10";
            device.Platform        = "Windows 10";
            device.Processor       = "SnapDragon";
            device.InstalledRAM    = "3GB";
            device.DeviceState     = "normal";

            Geolocator  geolocator = new Geolocator();
            Geoposition pos        = await geolocator.GetGeopositionAsync();

            device.Latitude  = (float)pos.Coordinate.Point.Position.Latitude;
            device.Longitude = (float)pos.Coordinate.Point.Position.Longitude;

            thermostat.DeviceProperties = device;

            Command TriggerAlarm = new Command();

            TriggerAlarm.Name = "TriggerAlarm";
            CommandParameter param = new CommandParameter();

            param.Name = "Message";
            param.Type = "String";
            TriggerAlarm.Parameters = new CommandParameter[] { param };

            thermostat.Commands = new Command[] { TriggerAlarm };

            thermostat.Telemetry = new TelemetryType[] { new TelemetryType {
                                                             Name = "Temperature", DisplayName = "Temperature", Type = "double"
                                                         },
                                                         new TelemetryType {
                                                             Name = "Humidity", DisplayName = "Humidity", Type = "double"
                                                         } };

            try
            {
                var msg = new Message(Serialize(thermostat));
                if (deviceClient != null)
                {
                    await deviceClient.SendEventAsync(msg);
                }
            }
            catch (System.Exception e)
            {
                Debug.Write("Exception while sending device meta data :\n" + e.Message.ToString());
            }

            Debug.Write("Sent meta data to IoT Suite\n" + hostName);
        }
Exemple #32
0
        public void TestHasOneIntegerConversionFailure() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "one"
                    }
                }
            };

            Assert.IsFalse(parameter.HasOne<Guid>());
        }
Exemple #33
0
        public void TestHasOneGuidConversionSuccessWithMultipleAndInvalid() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "9D2B0228-4D0D-4C23-8B49-01A698857709",
                        "Invalid"
                    }
                }
            };

            Assert.IsTrue(parameter.HasOne<Guid>());
        }
 public ApiSettingAddRequest()
 {
     Id = CommandParameter.Output(SqlDbType.Int);
 }
 /// <summary>
 /// Handles the OnMouseButtonUp event of the MainGrid control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="MouseButtonEventArgs"/> instance containing the event data.</param>
 private void MainGrid_OnMouseButtonUp(object sender, MouseButtonEventArgs e)
 {
     this.MainGrid.ReleaseMouseCapture();
     IsPressed = false;
     this.Command.Execute("-" + CommandParameter.ToString());
 }
Exemple #36
0
        public void Bind_NamedAndFlagParameters_BindsProperty(CommandParameter parameter1, CommandParameter parameter2, CommandParameter parameter3)
        {
            // arrange
            var sut     = CreateCommandParameterBinder(typeof(AllParametersCommand));
            var command = new AllParametersCommand();
            var input   = CreateCommandInput("☕", parameter1, parameter2, parameter3
                                             );

            // act
            var result = sut.Bind(command, input);

            // assert
            Assert.True(result.Success);
            Assert.Equal("value1", command.NamedParameter);
            Assert.True(command.FlagParameter);
        }
Exemple #37
0
        /// <summary>
        /// Binds the specified parameters to the native command
        /// </summary>
        ///
        /// <param name="parameters">
        /// The parameters to bind.
        /// </param>
        ///
        /// <param name="outputRedirected">
        /// true if minishell output is redirected.
        /// </param>
        ///
        /// <param name="hostName">
        /// name of the calling host.
        /// </param>
        ///
        /// <remarks>
        /// For any parameters that do not have a name, they are added to the command
        /// line arguments for the command
        /// </remarks>
        ///
        internal Collection <CommandParameterInternal> BindParameters(Collection <CommandParameterInternal> parameters, bool outputRedirected, string hostName)
        {
            MinishellParameters seen = 0;
            string inputFormat       = null;
            string outputFormat      = null;

            for (int i = 0; i < parameters.Count; i++)
            {
                var parameter = parameters[i];

                if (parameter.ParameterNameSpecified)
                {
                    var parameterName = parameter.ParameterName;

                    if (CommandParameter.StartsWith(parameterName, StringComparison.OrdinalIgnoreCase))
                    {
                        HandleSeenParameter(ref seen, MinishellParameters.Command, CommandParameter);

                        // Value must be specified for -Command parameter.
                        if (i + 1 >= parameters.Count)
                        {
                            throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, CommandParameter,
                                                               typeof(ScriptBlock), null,
                                                               NativeCP.NoValueForCommandParameter,
                                                               "NoValueForCommandParameter");
                        }

                        i += 1;

                        // Value of -Command parameter must be scriptblock
                        var scriptBlockArgument = parameters[i];
                        var argumentValue       = PSObject.Base(scriptBlockArgument.ArgumentValue);
                        if (!scriptBlockArgument.ArgumentSpecified || !(argumentValue is ScriptBlock))
                        {
                            throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, CommandParameter,
                                                               typeof(ScriptBlock), argumentValue.GetType(),
                                                               NativeCP.IncorrectValueForCommandParameter,
                                                               "IncorrectValueForCommandParameter");
                        }

                        // Replace the parameters with -EncodedCommand <base64 encoded scriptblock>
                        parameters[i - 1] = CommandParameterInternal.CreateParameter(EncodedCommandParameter, "-" + EncodedCommandParameter, parameter.ParameterAst);
                        string encodedScript = StringToBase64Converter.StringToBase64String(argumentValue.ToString());
                        parameters[i] = CommandParameterInternal.CreateArgument(encodedScript, scriptBlockArgument.ArgumentAst);
                    }
                    else if (InputFormatParameter.StartsWith(parameterName, StringComparison.OrdinalIgnoreCase))
                    {
                        HandleSeenParameter(ref seen, MinishellParameters.InputFormat, InputFormatParameter);

                        // Value for -Inputformat must be specified
                        if (i + 1 >= parameters.Count)
                        {
                            throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, InputFormatParameter,
                                                               typeof(string), null,
                                                               NativeCP.NoValueForInputFormatParameter,
                                                               "NoValueForInputFormatParameter");
                        }

                        // Update the argument (partial arguments are allowed)
                        i += 1;
                        var inputFormatArg = parameters[i];
                        inputFormat       = ProcessFormatParameterValue(InputFormatParameter, inputFormatArg.ArgumentValue);
                        parameters[i - 1] = CommandParameterInternal.CreateParameter(InputFormatParameter, "-" + InputFormatParameter, parameter.ParameterAst);
                        parameters[i]     = CommandParameterInternal.CreateArgument(inputFormat, inputFormatArg.ArgumentAst);
                    }
                    else if (OutputFormatParameter.StartsWith(parameterName, StringComparison.OrdinalIgnoreCase))
                    {
                        HandleSeenParameter(ref seen, MinishellParameters.OutputFormat, OutputFormatParameter);

                        // Value for -Inputformat must be specified
                        if (i + 1 >= parameters.Count)
                        {
                            throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, OutputFormatParameter,
                                                               typeof(string), null,
                                                               NativeCP.NoValueForOutputFormatParameter,
                                                               "NoValueForInputFormatParameter");
                        }

                        // Update the argument (partial arguments are allowed)
                        i += 1;
                        var outputFormatArg = parameters[i];
                        outputFormat      = ProcessFormatParameterValue(OutputFormatParameter, outputFormatArg.ArgumentValue);
                        parameters[i - 1] = CommandParameterInternal.CreateParameter(OutputFormatParameter, "-" + OutputFormatParameter, parameter.ParameterAst);
                        parameters[i]     = CommandParameterInternal.CreateArgument(outputFormat, outputFormatArg.ArgumentAst);
                    }
                    else if (ArgsParameter.StartsWith(parameterName, StringComparison.OrdinalIgnoreCase))
                    {
                        HandleSeenParameter(ref seen, MinishellParameters.Arguments, ArgsParameter);

                        // Value for -Args parameter must be specified
                        if (i + 1 >= parameters.Count)
                        {
                            throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, ArgsParameter,
                                                               typeof(string), null, NativeCP.NoValuesSpecifiedForArgs,
                                                               "NoValuesSpecifiedForArgs");
                        }

                        // Get the encoded value for -args parameter
                        i += 1;
                        var argsArg     = parameters[i];
                        var encodedArgs = ConvertArgsValueToEncodedString(argsArg.ArgumentValue);
                        parameters[i - 1] = CommandParameterInternal.CreateParameter(EncodedArgsParameter, "-" + EncodedArgsParameter, parameter.ParameterAst);
                        parameters[i]     = CommandParameterInternal.CreateArgument(encodedArgs, argsArg.ArgumentAst);
                    }
                }
                else
                {
                    // -Command is positional parameter. Bind first scriptblock to it, others are errors.
                    var scriptBlockArgument = parameters[i];
                    var argumentValue       = PSObject.Base(scriptBlockArgument.ArgumentValue);
                    if (argumentValue is ScriptBlock)
                    {
                        HandleSeenParameter(ref seen, MinishellParameters.Command, CommandParameter);

                        // Replace the argument with -EncodedCommand <base64 encoded scriptblock>
                        string encodedScript = StringToBase64Converter.StringToBase64String(argumentValue.ToString());
                        parameters[i] = CommandParameterInternal.CreateParameterWithArgument(
                            parameter.ArgumentAst, EncodedCommandParameter, "-" + EncodedCommandParameter,
                            parameter.ArgumentAst, encodedScript,
                            spaceAfterParameter: true);
                    }
                }
            }

            // Add InputFormat and OutputFormat parameter if not specified
            if (inputFormat == null)
            {
                // For minishell default input format is xml
                parameters.Add(CommandParameterInternal.CreateParameter(InputFormatParameter, "-" + InputFormatParameter));
                parameters.Add(CommandParameterInternal.CreateArgument(XmlFormatValue));
                inputFormat = XmlFormatValue;
            }

            if (outputFormat == null)
            {
                // If output is redirected, output format should be xml
                outputFormat = outputRedirected ? XmlFormatValue : TextFormatValue;
                parameters.Add(CommandParameterInternal.CreateParameter(OutputFormatParameter, "-" + OutputFormatParameter));
                parameters.Add(CommandParameterInternal.CreateArgument(outputFormat));
            }

            // Set the output and input format class variable
            InputFormat = XmlFormatValue.StartsWith(inputFormat, StringComparison.OrdinalIgnoreCase)
                ? NativeCommandIOFormat.Xml
                : NativeCommandIOFormat.Text;
            OutputFormat = XmlFormatValue.StartsWith(outputFormat, StringComparison.OrdinalIgnoreCase)
                ? NativeCommandIOFormat.Xml
                : NativeCommandIOFormat.Text;

            // Note if a minishell is invoked from a non-console host, we need to
            // pass -nonInteractive flag. Our console host's name is "ConsoleHost".
            // Correct check would be see if current host has access to console and
            // pass noninteractive flag if doesn't.
            if (string.IsNullOrEmpty(hostName) || !hostName.Equals("ConsoleHost", StringComparison.OrdinalIgnoreCase))
            {
                NonInteractive = true;
                parameters.Insert(0, CommandParameterInternal.CreateParameter(NonInteractiveParameter, "-" + NonInteractiveParameter));
            }

            ((NativeCommandParameterBinder)DefaultParameterBinder).BindParameters(parameters);

            Diagnostics.Assert(s_emptyReturnCollection.Count == 0, "This list shouldn't be used for anything as it's shared.");

            return(s_emptyReturnCollection);
        } // BindParameters
Exemple #38
0
        /// <summary>
        /// 再生処理を行う。
        /// </summary>
        /// <param name="parameter">コマンドパラメータ。</param>
        /// <returns>コマンドの戻り値。</returns>
        private async Task <CommandResult> ExecutePlay(CommandParameter parameter)
        {
            var process = parameter.Process;

            // 本体側のテキストを使わない場合のみテキスト設定を行う
            if (!parameter.UseTargetText)
            {
                // テキスト取得
                var text = parameter.TalkText;
                if (text == null)
                {
                    return
                        (MakeResult(
                             parameter,
                             AppStatusType.Fail,
                             @"再生処理を開始できませんでした。"));
                }

                // テキスト置換
                text = parameter.VoiceReplaceItems?.Replace(text) ?? text;

                // テキスト設定
                bool setOk = await process.SetTalkText(text);

                if (!setOk && process.Id.IsVoiceroid2LikeSoftware())
                {
                    // VOICEROID2ライクの場合、本体の入力欄が読み取り専用になることがある。
                    // 一旦 再生→停止 の操作を行うことで解除を試みる

                    if (!(await process.Play()))
                    {
                        ThreadTrace.WriteLine(@"VOICEROID2文章入力欄の復旧(再生)に失敗");

                        return
                            (MakeResult(
                                 parameter,
                                 AppStatusType.Fail,
                                 @"再生処理に失敗しました。"));
                    }

                    setOk = (await process.Stop()) && (await process.SetTalkText(text));
                    if (!setOk)
                    {
                        ThreadTrace.WriteLine(@"VOICEROID2文章入力欄の復旧に失敗");
                    }
                }
                if (!setOk)
                {
                    return
                        (MakeResult(
                             parameter,
                             AppStatusType.Fail,
                             @"文章の設定に失敗しました。"));
                }
            }

            // 再生
            var success = await process.Play();

            return
                (MakeResult(
                     parameter,
                     success ? AppStatusType.Success : AppStatusType.Fail,
                     success ? @"再生処理に成功しました。" : @"再生処理に失敗しました。"));
        }
Exemple #39
0
        public override bool Run(CommandParameter commandParam, ref string result)
        {
            if (!commandParam.CheckRequiredParams("user_name,password,email"))
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return(false);
            }

            if (commandParam.AppInfo.ApplicationType == (int)ApplicationType.DESKTOP)//如果是桌面程序则不允许此方法
            {
                if (commandParam.LocalUid < 1)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_PERMISSION_DENIED, commandParam.ParamList);
                    return(false);
                }
                ShortUserInfo shortUserInfo = Users.GetShortUserInfo(commandParam.LocalUid);
                if (shortUserInfo == null || shortUserInfo.Adminid != 1)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_PERMISSION_DENIED, commandParam.ParamList);
                    return(false);
                }
            }
            else if (commandParam.LocalUid > 0)//已经登录的用户不能再注册
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_USER_ONLINE, commandParam.ParamList);
                return(false);
            }

            string username = commandParam.GetDNTParam("user_name").ToString();
            string password = commandParam.GetDNTParam("password").ToString();
            string email    = commandParam.GetDNTParam("email").ToString();

            bool isMD5Passwd = commandParam.GetDNTParam("password_format") != null && commandParam.GetDNTParam("password_format").ToString() == "md5" ? true : false;

            //用户名不符合规范
            if (!AuthCommandUtils.CheckUsername(username))
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_USERNAME_ILLEGAL, commandParam.ParamList);
                return(false);
            }

            if (Discuz.Forum.Users.GetUserId(username) != 0)//如果用户名符合注册规则, 则判断是否已存在
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_USER_ALREADY_EXIST, commandParam.ParamList);
                return(false);
            }

            if (!isMD5Passwd && password.Length < 6)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return(false);
            }

            if (!AuthCommandUtils.CheckEmail(email, commandParam.GeneralConfig))
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_EMAIL, commandParam.ParamList);
                return(false);
            }

            #region Create New UserInfo

            UserInfo userInfo = new UserInfo();
            userInfo.Username      = username;
            userInfo.Nickname      = string.Empty;
            userInfo.Password      = isMD5Passwd ? password : Utils.MD5(password);
            userInfo.Secques       = string.Empty;
            userInfo.Gender        = 0;
            userInfo.Adminid       = 0;
            userInfo.Groupexpiry   = 0;
            userInfo.Extgroupids   = "";
            userInfo.Regip         = DNTRequest.GetIP();
            userInfo.Joindate      = Utils.GetDateTime();
            userInfo.Lastip        = DNTRequest.GetIP();
            userInfo.Lastvisit     = Utils.GetDateTime();
            userInfo.Lastactivity  = Utils.GetDateTime();
            userInfo.Lastpost      = Utils.GetDateTime();
            userInfo.Lastpostid    = 0;
            userInfo.Lastposttitle = "";
            userInfo.Posts         = 0;
            userInfo.Digestposts   = 0;
            userInfo.Oltime        = 0;
            userInfo.Pageviews     = 0;
            userInfo.Credits       = 0;
            userInfo.Extcredits1   = Scoresets.GetScoreSet(1).Init;
            userInfo.Extcredits2   = Scoresets.GetScoreSet(2).Init;
            userInfo.Extcredits3   = Scoresets.GetScoreSet(3).Init;
            userInfo.Extcredits4   = Scoresets.GetScoreSet(4).Init;
            userInfo.Extcredits5   = Scoresets.GetScoreSet(5).Init;
            userInfo.Extcredits6   = Scoresets.GetScoreSet(6).Init;
            userInfo.Extcredits7   = Scoresets.GetScoreSet(7).Init;
            userInfo.Extcredits8   = Scoresets.GetScoreSet(8).Init;
            userInfo.Email         = email;
            userInfo.Bday          = string.Empty;
            userInfo.Sigstatus     = 0;

            userInfo.Tpp        = 0;
            userInfo.Ppp        = 0;
            userInfo.Templateid = 0;
            userInfo.Pmsound    = 0;
            userInfo.Showemail  = 0;
            userInfo.Salt       = "0";
            int receivepmsetting = commandParam.GeneralConfig.Regadvance == 0 ? 7 : 1;
            userInfo.Newsletter   = (ReceivePMSettingType)receivepmsetting;
            userInfo.Invisible    = 0;
            userInfo.Newpm        = commandParam.GeneralConfig.Welcomemsg == 1 ? 1 : 0;
            userInfo.Medals       = "";
            userInfo.Accessmasks  = 0;
            userInfo.Website      = string.Empty;
            userInfo.Icq          = string.Empty;
            userInfo.Qq           = string.Empty;
            userInfo.Yahoo        = string.Empty;
            userInfo.Msn          = string.Empty;
            userInfo.Skype        = string.Empty;
            userInfo.Location     = string.Empty;
            userInfo.Customstatus = string.Empty;
            userInfo.Bio          = string.Empty;
            userInfo.Signature    = string.Empty;
            userInfo.Sightml      = string.Empty;
            userInfo.Authtime     = Utils.GetDateTime();

            //邮箱激活链接验证
            if (commandParam.GeneralConfig.Regverify == 1)
            {
                userInfo.Authstr  = ForumUtils.CreateAuthStr(20);
                userInfo.Authflag = 1;
                userInfo.Groupid  = 8;
                Emails.DiscuzSmtpMail(username, email, string.Empty, userInfo.Authstr);
            }
            //系统管理员进行后台验证
            else if (commandParam.GeneralConfig.Regverify == 2)
            {
                userInfo.Authstr  = string.Empty;
                userInfo.Groupid  = 8;
                userInfo.Authflag = 1;
            }
            else
            {
                userInfo.Authstr  = "";
                userInfo.Authflag = 0;
                userInfo.Groupid  = CreditsFacade.GetCreditsUserGroupId(0).Groupid;
            }
            userInfo.Realname = string.Empty;
            userInfo.Idcard   = string.Empty;
            userInfo.Mobile   = string.Empty;
            userInfo.Phone    = string.Empty;

            if (commandParam.GeneralConfig.Passwordmode > 1 && PasswordModeProvider.GetInstance() != null)
            {
                userInfo.Uid = PasswordModeProvider.GetInstance().CreateUserInfo(userInfo);
            }
            else
            {
                userInfo.Uid = Discuz.Forum.Users.CreateUser(userInfo);
            }

            #endregion

            if (commandParam.GeneralConfig.Welcomemsg == 1)
            {
                PrivateMessageInfo privatemessageinfo = new PrivateMessageInfo();
                // 收件箱
                privatemessageinfo.Message      = commandParam.GeneralConfig.Welcomemsgtxt;
                privatemessageinfo.Subject      = "欢迎您的加入! (请勿回复本信息)";
                privatemessageinfo.Msgto        = userInfo.Username;
                privatemessageinfo.Msgtoid      = userInfo.Uid;
                privatemessageinfo.Msgfrom      = PrivateMessages.SystemUserName;
                privatemessageinfo.Msgfromid    = 0;
                privatemessageinfo.New          = 1;
                privatemessageinfo.Postdatetime = Utils.GetDateTime();
                privatemessageinfo.Folder       = 0;
                PrivateMessages.CreatePrivateMessage(privatemessageinfo, 0);
            }
            Statistics.ReSetStatisticsCache();

            //信息同步通知不会发向当前请求接口的应用程序,所以此处应保留,以支持论坛向其他关联应用程序发送通知
            Sync.UserRegister(userInfo.Uid, userInfo.Username, userInfo.Password, commandParam.AppInfo.APIKey);

            CreditsFacade.UpdateUserCredits(userInfo.Uid);

            if (commandParam.Format == FormatType.JSON)
            {
                result = string.Format("\"{0}\"", userInfo.Uid);
            }
            else
            {
                RegisterResponse rr = new RegisterResponse();
                rr.Uid = userInfo.Uid;
                result = SerializationHelper.Serialize(rr);
            }
            return(true);
        }
Exemple #40
0
        public override bool Run(CommandParameter commandParam, ref string result)
        {
            //如果是桌面程序则需要验证用户身份
            //if (commandParam.AppInfo.ApplicationType == (int)ApplicationType.DESKTOP)
            //{
            //    if (commandParam.LocalUid < 1)
            //    {
            //        result = Util.CreateErrorMessage(ErrorType.API_EC_SESSIONKEY, commandParam.ParamList);
            //        return false;
            //    }
            //}

            if (!commandParam.CheckRequiredParams("fid"))
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return(false);
            }

            int fid = Utils.StrToInt(commandParam.GetDNTParam("fid"), 0);

            if (fid < 1)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return(false);
            }

            ForumInfo forumInfo = Discuz.Forum.Forums.GetForumInfo(fid);

            if (forumInfo == null)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_FORUM_NOT_EXIST, commandParam.ParamList);
                return(false);
            }

            ForumGetResponse fgr = new ForumGetResponse();

            fgr.Fid           = fid;
            fgr.Url           = Utils.GetRootUrl(BaseConfigs.GetForumPath) + Urls.ShowForumAspxRewrite(fid, 1, forumInfo.Rewritename);
            fgr.CurTopics     = forumInfo.CurrentTopics;
            fgr.Description   = forumInfo.Description;
            fgr.Icon          = forumInfo.Icon;
            fgr.LastPost      = forumInfo.Lastpost;
            fgr.LastPoster    = forumInfo.Lastposter.Trim();
            fgr.LastPosterId  = forumInfo.Lastposterid;
            fgr.LastTid       = forumInfo.Lasttid;
            fgr.LastTitle     = forumInfo.Lasttitle.Trim();
            fgr.Moderators    = forumInfo.Moderators;
            fgr.Name          = forumInfo.Name;
            fgr.ParentId      = forumInfo.Parentid;
            fgr.ParentIdList  = forumInfo.Parentidlist.Trim();
            fgr.PathList      = forumInfo.Pathlist.Trim();
            fgr.Posts         = forumInfo.Posts;
            fgr.Rules         = forumInfo.Rules;
            fgr.Status        = forumInfo.Status;
            fgr.SubForumCount = forumInfo.Subforumcount;
            fgr.TodayPosts    = forumInfo.Todayposts;
            fgr.Topics        = forumInfo.Topics;

            result = commandParam.Format == FormatType.JSON ? JavaScriptConvert.SerializeObject(fgr) : SerializationHelper.Serialize(fgr);
            return(true);
        }
        /// <summary>
        /// Get the API command parameter summary.
        /// </summary>
        /// <param name="ctx">
        /// The <see cref="RegistryContext"/> holding information about the generated class.
        /// </param>
        /// <param name="command">
        /// The relative <see cref="Command"/>.
        /// </param>
        /// <param name="commandParameter">
        /// The relative <see cref="CommandParameter"/>
        /// </param>
        /// <returns>
        /// It returns the summary relative to the command <paramref name="commandParameter"/>.
        /// </returns>
        public override string QueryCommandParamSummary(RegistryContext ctx, Command command, CommandParameter commandParameter)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException(nameof(ctx));
            }
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }
            if (commandParameter == null)
            {
                throw new ArgumentNullException(nameof(commandParameter));
            }

            return($"A <see cref=\"T:{commandParameter.GetImplementationType(ctx, command)}\"/>.");
        }
        public void TestHasManyDateTimeConversionFailed() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "2014-04-14 13:50:59",
                        "2014-04-11 03:23:13",
                        "Invalid"
                    }
                }
            };

            Assert.IsFalse(parameter.HasMany<DateTime>());
        }
Exemple #43
0
 public ServiceSettingUpdateRequest()
 {
     Service = CommandParameter.Output(SqlDbType.VarChar, 50);
 }
        private async void sendDeviceMetaData()
        {
            DeviceProperties device = new DeviceProperties();
            Thermostat thermostat = new Thermostat();

            thermostat.ObjectType = "DeviceInfo";
            thermostat.IsSimulatedDevice = false;
            thermostat.Version = "1.0";

            device.HubEnabledState = true;
            device.DeviceID = deviceId;
            device.Manufacturer = "Microsoft";
            device.ModelNumber = "Lumia950";
            device.SerialNumber = "5849735293875";
            device.FirmwareVersion = "10";
            device.Platform = "Windows 10";
            device.Processor = "SnapDragon";
            device.InstalledRAM = "3GB";
            device.DeviceState = "normal";

            Geolocator geolocator = new Geolocator();
            Geoposition pos = await geolocator.GetGeopositionAsync();

            device.Latitude = (float)pos.Coordinate.Point.Position.Latitude;
            device.Longitude = (float)pos.Coordinate.Point.Position.Longitude;

            thermostat.DeviceProperties = device;

            Command TriggerAlarm = new Command();
            TriggerAlarm.Name = "TriggerAlarm";
            CommandParameter param = new CommandParameter();
            param.Name = "Message";
            param.Type = "String";
            TriggerAlarm.Parameters = new CommandParameter[] { param };

            thermostat.Commands = new Command[] { TriggerAlarm };

            try
            {
                var msg = new Message(Serialize(thermostat));
                if (deviceClient != null)
                {
                    await deviceClient.SendEventAsync(msg);
                }
            }
            catch (System.Exception e)
            {
                Debug.Write("Exception while sending device meta data :\n" + e.Message.ToString());
            }

            Debug.Write("Sent meta data to IoT Suite\n" + hostName);

        }
Exemple #45
0
        private string ExecuteLocal(string ScriptPath, string ScriptCode, int HasParams, string TableAsString)
        {
            StringWriter sw = new StringWriter();
            DataTable    dt = new DataTable("resultSet");

            dt.Columns.Add("Result", typeof(String));

            try
            {
                if (string.IsNullOrEmpty(ScriptCode) == false)
                {
                    ScriptCode = ScriptCode.Replace("\t", "\r\n");
                }


                if (string.IsNullOrEmpty(ScriptPath) == false)
                {
                    if (File.Exists(ScriptPath))
                    {
                        ScriptCode = File.ReadAllText(ScriptPath);
                    }
                    else
                    {
                        throw new Exception("File not found");
                    }
                }

                InitialSessionState iss = InitialSessionState.CreateDefault();
                PSSnapInException   warning;

                string[] MyArray = ScriptCode.Split(new string[] { "\r\n" }, StringSplitOptions.None);

                foreach (string item in MyArray)
                {
                    if (item.ToLower().Contains("add-pssnapin"))
                    {
                        iss.ImportPSSnapIn(item.Substring(item.ToLower().IndexOf("add-pssnapin") + 12).Trim(), out warning);
                        ScriptCode = ScriptCode.Replace(item, "");
                    }
                }

                Collection <PSObject> results = null;

                using (PowerShellProcessInstance instance = new PowerShellProcessInstance(new Version(4, 0), null, null, false))
                {
                    using (var runspace = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0]), instance))
                    {
                        runspace.Open();

                        using (Pipeline pipeline = runspace.CreatePipeline())
                        {
                            if (HasParams == 1 && string.IsNullOrEmpty(TableAsString) == false)
                            {
                                CommandParameter         param;
                                DataTable                dtParams = new DataTable();
                                System.Text.UTF8Encoding enc      = new System.Text.UTF8Encoding();

                                using (MemoryStream stream = new MemoryStream())
                                {
                                    byte[] allBytes = enc.GetBytes(TableAsString);
                                    stream.Write(allBytes, 0, allBytes.Length);
                                    stream.Position = 0;
                                    dtParams.ReadXml(stream);
                                }

                                Command myCommand = new Command(ScriptCode, true);

                                foreach (DataRow row in dtParams.Rows)
                                {
                                    param = new CommandParameter(row[0].ToString(), row[1]);
                                    myCommand.Parameters.Add(param);
                                }

                                pipeline.Commands.Add(myCommand);
                                pipeline.Commands.Add("Out-String");
                            }
                            else
                            {
                                pipeline.Commands.AddScript(ScriptCode);
                                pipeline.Commands.Add("Out-String");
                            }

                            results = pipeline.Invoke();
                        }
                    }
                }

                StringBuilder stbuilder   = new StringBuilder();
                bool          isStartLine = true;
                string        cmdResult   = string.Empty;

                foreach (PSObject obj in results)
                {
                    if (isStartLine)
                    {
                        cmdResult   = ClearString(obj.ToString());
                        isStartLine = false;
                    }
                    else
                    {
                        cmdResult = obj.ToString();
                    }

                    dt.Rows.Add(cmdResult);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            dt.WriteXml(sw, XmlWriteMode.WriteSchema, false);

            return(sw.ToString());
        }
Exemple #46
0
 public virtual bool Run(CommandParameter commandParam, ref string result)
 {
     return(true);
 }
Exemple #47
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <remarks>
        /// All abount Cmdlet parameters: http://msdn2.microsoft.com/en-us/library/ms714433(VS.85).aspx
        /// </remarks>
        internal override void BindArguments(PSObject obj)
        {
            if ((obj == null) && (Parameters.Count == 0))
            {
                return;
            }

            // TODO: bind the arguments to the parameters
            CommandParameterSetInfo paramSetInfo = _cmdletInfo.GetDefaultParameterSet();

            // TODO: refer to the Command._ParameterSetName for a param set name

            if (obj != null)
            {
                foreach (CommandParameterInfo paramInfo in paramSetInfo.Parameters)
                {
                    if (paramInfo.ValueFromPipeline)
                    {
                        // TODO: extract this into a method
                        PropertyInfo pi = Command.GetType().GetProperty(paramInfo.Name, paramInfo.ParameterType);
                        pi.SetValue(Command, obj, null);
                    }
                }
            }

            if (Parameters.Count > 0)
            {
                // bind by position location
                for (int i = 0; i < Parameters.Count; i++)
                {
                    CommandParameterInfo paramInfo = null;

                    CommandParameter parameter = Parameters[i];

                    if (string.IsNullOrEmpty(parameter.Name))
                    {
                        paramInfo = paramSetInfo.GetParameterByPosition(i);

                        if (paramInfo != null)
                        {
                            // TODO: extract this into a method
                            PropertyInfo pi = Command.GetType().GetProperty(paramInfo.Name, paramInfo.ParameterType);
                            // TODO: make this generic
                            if (pi.PropertyType == typeof(PSObject[]))
                            {
                                PSObject[] arr = new PSObject[] { PSObject.AsPSObject(Parameters[i].Value) };
                                pi.SetValue(Command, arr, null);
                            }
                            else if (pi.PropertyType == typeof(String[]))
                            {
                                String[] arr = new String[] { Parameters[i].Value.ToString() };
                                pi.SetValue(Command, arr, null);
                            }
                            else
                            {
                                pi.SetValue(Command, Parameters[i].Value, null);
                            }
                        }
                    }
                    else
                    {
                        paramInfo = paramSetInfo.GetParameterByName(parameter.Name);

                        if (paramInfo != null)
                        {
                            // TODO: extract this into a method
                            PropertyInfo pi = Command.GetType().GetProperty(paramInfo.Name, paramInfo.ParameterType);
                            pi.SetValue(Command, Parameters[i].Value, null);
                        }
                    }
                }
            }
        }
Exemple #48
0
        public override bool Run(CommandParameter commandParam, ref string result)
        {
            if (commandParam.AppInfo.ApplicationType == (int)ApplicationType.WEB)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PERMISSION_DENIED, commandParam.ParamList);
                return(false);
            }

            if (commandParam.LocalUid > 0)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_USER_ONLINE, commandParam.ParamList);
                return(false);
            }

            if (!commandParam.CheckRequiredParams("user_name,password"))
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return(false);
            }

            if (LoginLogs.UpdateLoginLog(DNTRequest.GetIP(), false) >= 5)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_MORE_LOGIN_FAILED, commandParam.ParamList);
                return(false);
            }

            string loginName      = commandParam.GetDNTParam("user_name").ToString();
            string password       = commandParam.GetDNTParam("password").ToString();
            string passwordFormat = commandParam.CheckRequiredParams("password_format") ? commandParam.GetDNTParam("password_format").ToString() : "";
            int    expires        = commandParam.GetIntParam("expires");

            expires = expires > 0 ? expires : 999;

            int           userId   = -1;
            ShortUserInfo userInfo = new ShortUserInfo();

            if (commandParam.GeneralConfig.Emaillogin == 1 && Utils.IsValidEmail(loginName))
            {
                DataTable dt = Users.GetUserInfoByEmail(loginName);
                if (dt.Rows.Count == 0)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_USER_NOT_EXIST, commandParam.ParamList);
                    return(false);
                }
                if (dt.Rows.Count > 1)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_SAME_USER_EMAIL, commandParam.ParamList);
                    return(false);
                }
                loginName            = dt.Rows[0]["username"].ToString();
                userId               = TypeConverter.ObjectToInt(dt.Rows[0]["uid"]);
                userInfo.Uid         = userId;
                userInfo.Username    = loginName;
                userInfo.Groupid     = TypeConverter.ObjectToInt(dt.Rows[0]["groupid"]);
                userInfo.Groupexpiry = TypeConverter.ObjectToInt(dt.Rows[0]["groupexpiry"]);
                userInfo.Credits     = TypeConverter.ObjectToInt(dt.Rows[0]["credits"]);
                userInfo.Email       = dt.Rows[0]["email"].ToString();
                userInfo.Password    = dt.Rows[0]["password"].ToString();
            }
            else
            {
                userId = Users.GetUserId(loginName);
                if (userId < 1)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_USER_NOT_EXIST, commandParam.ParamList);
                    return(false);
                }
                userInfo = Users.GetShortUserInfo(userId);
            }

            int uid = -1;

            if (passwordFormat == "")
            {
                switch (commandParam.GeneralConfig.Passwordmode)
                {
                case 0:    //默认模式
                {
                    uid = Users.CheckPassword(loginName, password, true);
                    break;
                }

                case 1:    //动网兼容模式
                {
                    uid = Users.CheckDvBbsPassword(loginName, password);
                    break;
                }
                }
            }
            else
            {
                uid = userInfo.Password == password ? userInfo.Uid : -1;
            }

            if (uid != userInfo.Uid)
            {
                LoginLogs.UpdateLoginLog(DNTRequest.GetIP(), true);
                result = Util.CreateErrorMessage(ErrorType.API_EC_WRONG_PASSWORD, commandParam.ParamList);
                return(false);
            }

            #region 当前用户所在用户组为"禁止访问"或"等待激活"时

            if ((userInfo.Groupid == 4 || userInfo.Groupid == 5) && userInfo.Groupexpiry != 0 && userInfo.Groupexpiry <= Utils.StrToInt(DateTime.Now.ToString("yyyyMMdd"), 0))
            {
                //根据当前用户的积分获取对应积分用户组
                UserGroupInfo groupInfo = CreditsFacade.GetCreditsUserGroupId(userInfo.Credits);
                Users.UpdateUserGroup(userInfo.Uid, userInfo.Groupid);
            }

            #endregion

            if (userInfo.Groupid == 5 || userInfo.Groupid == 8)// 5-禁止访问或者需要激活帐号的用户
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_BANNED_USERGROUP, commandParam.ParamList);
                return(false);
            }

            #region 无延迟更新在线信息和相关用户信息
            ForumUtils.WriteUserCookie(userInfo.Uid, expires, commandParam.GeneralConfig.Passwordkey, 0, -1);
            OnlineUserInfo oluserinfo = OnlineUsers.UpdateInfo(commandParam.GeneralConfig.Passwordkey, commandParam.GeneralConfig.Onlinetimeout, userInfo.Uid, "");
            OnlineUsers.UpdateAction(oluserinfo.Olid, UserAction.Login.ActionID, 0);
            LoginLogs.DeleteLoginLog(DNTRequest.GetIP());
            Users.UpdateUserCreditsAndVisit(userInfo.Uid, DNTRequest.GetIP());
            #endregion

            result = "success";
            result = commandParam.Format == FormatType.JSON ? string.Format("\"{0}\"", result) : SerializationHelper.Serialize(result);

            return(true);
        }
Exemple #49
0
 /// <summary>
 /// コマンドパラメータを変換する。
 /// </summary>
 /// <param name="parameter">元のコマンドパラメータ。無視される。</param>
 /// <returns>変換されたコマンドパラメータ。</returns>
 protected override sealed CommandParameter ConvertParameter(
     CommandParameter parameter)
 =>
 this.ParameterMaker();
Exemple #50
0
 public static void CheckParameter(CommandParameter param, string name, Type type, object defaultValue)
 {
     Assert.AreEqual(name, param.Name);
     Assert.AreEqual(type, param.Type);
     Assert.AreEqual(defaultValue, param.DefaultValue);
 }
Exemple #51
0
 public virtual void Execute(CommandParameter _parameter)
 {
 }
 public ApiClientDeleteByPKRequest()
 {
     ClientKey = CommandParameter.Output(SqlDbType.UniqueIdentifier);
 }
Exemple #53
0
        public void TestHasOneGuidConversionSuccessWithMultiple() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "9D2B0228-4D0D-4C23-8B49-01A698857709",
                        "f380eb1e-1438-48c0-8c3d-ad55f2d40538"
                    }
                }
            };

            Assert.IsTrue(parameter.HasOne<Guid>());
        }
Exemple #54
0
        public void TestHasManyGuidConversionFailed() {
            var parameter = new CommandParameter() {
                Data = {
                    Content = new List<String>() {
                        "9D2B0228-4D0D-4C23-8B49-01A698857709",
                        "f380eb1e-1438-48c0-8c3d-ad55f2d40538",
                        "Invalid"
                    }
                }
            };

            Assert.IsFalse(parameter.HasMany<Guid>());
        }
Exemple #55
0
 protected virtual bool canFinishMeasure(CommandParameter <TMode> mode) => true;
        protected void ContextPreExecute <TResponse, UData, VStatus, WRequest, TContext>(TContext context, IDbCommand cmd, IDictionary <string, object> args)
            where TResponse : BaseServiceResponse <UData, VStatus>, new()
            where WRequest : class, IBaseServiceRequest, new()
            where TContext : BabbageContext <TResponse, UData, VStatus, WRequest>, new()
        {
            Type requestType;
            var  babbageRequest = context.Request as BabbageRequest;
            var  baseRequest    = context.Request as BaseServiceRequest;

            if (context.OverrideRequest != null)
            {
                requestType = context.OverrideRequest.GetType();
            }
            else
            {
                requestType = context.Request.GetType();
            }

            args.Add("Result", CommandParameter.Output(SqlDbType.VarChar, 50));
            args.Add("Args", CommandParameter.Output(SqlDbType.NVarChar, 1000));

            var execMode = 0;
            var ctx      = context as BabbageContext <TResponse, UData, VStatus, WRequest>;

            if (ctx != null)
            {
                execMode = ctx.ExecMode;
            }
            else
            if (context.Log.Options.DebugMode)
            {
                execMode = 1;
            }

            args.Add("ExecMode", execMode);

            var           reqProps     = requestType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            var           _args        = new StringBuilder();
            List <string> overrideList = null;

            if (baseRequest != null)
            {
                overrideList = baseRequest.GetOverrideList();
            }
            //var cnt = 0;

            object value = null;
            Type   proptype;

            var babbageContext = context as BabbageContext <TResponse, UData, VStatus, WRequest>;

            if (babbageContext != null)
            {
                foreach (var op in babbageContext.OutputParameters)
                {
                    args.Add(op.Key, op.Value);
                }
            }

            foreach (var prop in reqProps)
            {
                if (prop.CanRead)
                {
                    if (babbageRequest != null && string.Compare(prop.Name, "Hash", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        continue;
                    }

                    if (overrideList != null && overrideList.Count > 0 && overrideList.Exists(x => string.Compare(x, prop.Name, StringComparison.OrdinalIgnoreCase) == 0))
                    {
                        if (baseRequest.GetValue(prop.Name, out value))
                        {
                            args.Add(prop.Name, value);
                        }

                        continue;
                    }

                    proptype = prop.PropertyType;

                    if (proptype.IsNullableOrBasicType() || proptype.IsModelField() || proptype.IsCommandParameterType())
                    {
                        if (context.OverrideRequest != null)
                        {
                            value = prop.GetValue(context.OverrideRequest);
                        }
                        else
                        {
                            value = prop.GetValue(context.Request);
                        }

                        args.Add(prop.Name, value);

                        if (context.Log.Options.DebugMode)
                        {
                            var _value = "";
                            var cmdIO  = value as CommandInputOutputParameter;
                            if (cmdIO != null)
                            {
                                _value = SafeClrConvert.ToString(cmdIO.Value);
                                _args.AppendFormatWithCommaIfNotEmpty("{0}: {1}", prop.Name, _value);
                                //_args.Append((cnt == 0) ? "" : "," + prop.Name + ":" + SafeClrConvert.ToString(cmdIO.Value));
                            }
                            else
                            {
                                var cmdGUId = value as GuidCommandParameter;
                                if (cmdGUId != null)
                                {
                                    _value = SafeClrConvert.ToString(cmdGUId.Value);
                                    _args.AppendFormatWithCommaIfNotEmpty("{0}: {1}", prop.Name, _value);

                                    //_args.Append((cnt == 0)
                                    //    ? ""
                                    //    : "," + prop.Name + ":" + SafeClrConvert.ToString(cmdGUId.Value));
                                }
                                else
                                {
                                    var cmdParam = value as CommandParameter;
                                    if (cmdParam != null)
                                    {
                                        _value = SafeClrConvert.ToString(cmdParam.Value);
                                        _args.AppendFormatWithCommaIfNotEmpty("{0}: {1}", prop.Name, _value);

                                        //_args.Append((cnt == 0)
                                        //    ? ""
                                        //    : "," + prop.Name + ":" + SafeClrConvert.ToString(cmdParam.Value));
                                    }
                                    else
                                    {
                                        _value = SafeClrConvert.ToString(value);
                                        _args.AppendFormatWithCommaIfNotEmpty("{0}: {1}", prop.Name, _value);

                                        //_args.Append((cnt == 0)
                                        //    ? ""
                                        //    : "," + prop.Name + ":" + SafeClrConvert.ToString(value));
                                    }
                                }
                            }
                            //cnt++;
                        }
                    }
                    else
                    {
                        // currently, we don't support non-basic types
                    }
                }
            }

            context.Log.System(context.Strategy.Store.Service.Name, context.Strategy.Name, "sys_db_cmd_exec", () => _args.ToString());
        }
    private void AddParameter(TreeNode parametersNode, CommandParameter parameter, bool detailed, bool includeHidden)
    {
        if (!includeHidden && parameter.IsHidden)
        {
            return;
        }

        if (!detailed)
        {
            parametersNode.AddNode(
                $"{parameter.PropertyName} [purple]{GetShortOptions(parameter)}[/] [grey]{parameter.Property.PropertyType.ToString().EscapeMarkup()}[/]");

            return;
        }

        var parameterNode = parametersNode.AddNode(
            $"{parameter.PropertyName} [grey]{parameter.Property.PropertyType.ToString().EscapeMarkup()}[/]");

        parameterNode.AddNode(ValueMarkup("Description", parameter.Description, "no description"));
        parameterNode.AddNode(ValueMarkup("Parameter Kind", parameter.ParameterKind.ToString()));

        if (parameter is CommandOption commandOptionParameter)
        {
            if (commandOptionParameter.IsShadowed)
            {
                parameterNode.AddNode(ValueMarkup("IsShadowed", commandOptionParameter.IsShadowed.ToString()));
            }

            if (commandOptionParameter.LongNames.Count > 0)
            {
                parameterNode.AddNode(ValueMarkup(
                                          "Long Names",
                                          string.Join("|", commandOptionParameter.LongNames.Select(i => $"--{i}"))));

                parameterNode.AddNode(ValueMarkup(
                                          "Short Names",
                                          string.Join("|", commandOptionParameter.ShortNames.Select(i => $"-{i}"))));
            }
        }
        else if (parameter is CommandArgument commandArgumentParameter)
        {
            parameterNode.AddNode(ValueMarkup("Position", commandArgumentParameter.Position.ToString()));
            parameterNode.AddNode(ValueMarkup("Value", commandArgumentParameter.Value));
        }

        parameterNode.AddNode(ValueMarkup("Required", parameter.Required.ToString()));

        if (parameter.Converter != null)
        {
            parameterNode.AddNode(ValueMarkup(
                                      "Converter", $"\"{parameter.Converter.ConverterTypeName}\""));
        }

        if (parameter.DefaultValue != null)
        {
            parameterNode.AddNode(ValueMarkup(
                                      "Default Value", $"\"{parameter.DefaultValue.Value}\""));
        }

        if (parameter.PairDeconstructor != null)
        {
            parameterNode.AddNode(ValueMarkup("Pair Deconstructor", parameter.PairDeconstructor.Type.ToString()));
        }

        AddStringList(
            parameterNode,
            "Validators",
            parameter.Validators.Select(i => i.GetType().ToString()).ToList());
    }
Exemple #58
0
 /// <summary>
 /// コンストラクタ。
 /// </summary>
 /// <param name="appStatus">アプリ状態値。</param>
 /// <param name="parameter">コマンド実施時に作成されたパラメータ。</param>
 public CommandResult(IAppStatus appStatus, CommandParameter parameter)
 {
     this.AppStatus = appStatus;
     this.Parameter = parameter;
 }
		/// <summary>
		/// Returns a native Command corresponding to the database engine associated
		/// </summary>
		protected virtual MySqlPCL.MySqlParameter Parse(CommandParameter param)
		{
			MySqlPCL.MySqlParameter dbParam = new MySqlPCL.MySqlParameter();

			dbParam.Value = param.Value;
			dbParam.DbType = (System.Data.DbType) param.DbType;
			dbParam.Direction = (System.Data.ParameterDirection) param.Direction;
			dbParam.Size = param.Size;
			dbParam.ParameterName = param.Name;

			return dbParam;
		}
 public override void Execute(CommandParameter commandParameter, IFeedbackFactory feedbackFactory,
                              IClientInfo clientInfo)
 {
     throw new NotImplementedException();
 }