示例#1
0
        public async Task <BaseResponse> AddRoleAsync(RoleAddDto req, string account, string GroupId)
        {
            BaseResponse rm = new BaseResponse();
            //检查该组织下该部门下是否存在相同的角色
            var r = await IsExist(a => a.RoleName == req.Name /*&& a.GroupId == req.gr*/);

            if (r)
            {
                rm.Success = false;
                rm.Message = "该部门下存在相同名称的角色,请确认";
                return(rm);
            }
            try
            {
                var role = _mapper.Map <RoleModel>(req);
                role.Create  = account;
                role.GroupId = GroupId;
                await _role.AddAsync(role);

                rm = new HandleResponse <int> {
                    Key = role.Id, Success = true, Message = "添加角色成功"
                };
                _log.LogInformation($"{account}创建角色{req.Name},角色编号为{role.Id}成功");
            }
            catch (Exception ex)
            {
                rm.Success = false;
                rm.Message = "添加角色失败";
                _log.LogError($"{account}创建角色{req.Name}失败,失败原因:{ex.Message}->{ex.StackTrace}->{ex.InnerException}");
            }
            return(rm);
        }
示例#2
0
        public HandleResponse <UserDepartmentKey> RemoveUserDepartment(int userId, int departmentId)
        {
            HandleResponse <UserDepartmentKey> rm = new HandleResponse <UserDepartmentKey>();

            UserDepartmentModel ud = new UserDepartmentModel()
            {
                UserId = userId, DeparmentId = departmentId
            };

            try
            {
                _UserDepartment.Remove(ud);
                rm.Success = true;
                rm.Message = "删除数据成功";
                rm.Key     = new UserDepartmentKey {
                    UserId = ud.UserId, DepartmentId = ud.DeparmentId
                };
            }
            catch (Exception ex)
            {
                rm.Success = false;
                rm.Message = "删除数据失败" + ex.Message;
            }
            return(rm);
        }
示例#3
0
        public HandleResponse <UserRoleKey> DeleteUserRole(UserRoleDeleteViewModel req)
        {
            HandleResponse <UserRoleKey> rm = new HandleResponse <UserRoleKey>();
            //var b = IsExist(a => a.UserId == req.UserId && a.RoleId == req.RoleId);
            //if (b)
            //{
            //    rm.Success = false;
            //    rm.Message = "用户没有分配该角色,请确认";
            //    return rm;
            //}
            UserRoleModel ur = new UserRoleModel()
            {
                UserId = req.UserId, RoleId = req.RoleId
            };

            try
            {
                _userrole.Remove(ur);
                rm.Success = true;
                rm.Message = "删除数据成功";
                rm.Key     = new UserRoleKey {
                    UserId = req.UserId, RoleId = req.RoleId
                };
            }
            catch (Exception ex)
            {
                rm.Success = false;
                rm.Message = "删除数据失败" + ex.Message;
            }
            return(rm);
        }
示例#4
0
        public HandleResponse <UserDepartmentKey> AddUserDepartment(UserDepartmentAddViewModel req)
        {
            HandleResponse <UserDepartmentKey> rm = new HandleResponse <UserDepartmentKey>();
            //bool b =await IsExist(a => a.UserId == req.UserId && a.DeparmentId == req.DepartmentId);
            //if (b)
            //{
            //    rm.Success = false;
            //    rm.Message = "该用户已分配在该部门,请勿重复操作";
            //    return rm;
            //}
            UserDepartmentModel ud = new UserDepartmentModel()
            {
                UserId = req.UserId, DeparmentId = req.DepartmentId
            };

            try
            {
                _UserDepartment.Add(ud);
                rm.Success = true;
                rm.Message = "添加数据成功";
                rm.Key     = new UserDepartmentKey {
                    UserId = ud.UserId, DepartmentId = ud.DeparmentId
                };
            }
            catch (Exception ex)
            {
                rm.Success = false;
                rm.Message = "添加数据失败" + ex.Message;
            }
            return(rm);
        }
示例#5
0
    void Awake()
    {
        // Get the connection
        connection = ServerConfig.Connection.getInstance();
        connection.startListening();
        HandleResponse handler = new HandleResponse();

        Debug.Log("Connection Loaded!");
    }
示例#6
0
 public static void RequestGet(string url, HandleResponse callback, CookieContainer cookies, params string[] post_data_pair)
 {
     if (post_data_pair != null && post_data_pair.Length%2!=0)
     {
         Debug.LogError("Post data params shoud be an array of name and value pairs");
         return;
     }
     // create get data
     string post_data = "";
     for (int i = 0; i < post_data_pair.Length; i+=2)
         post_data += post_data_pair[i]+"="+post_data_pair[i+1]+((i==post_data_pair.Length-2)? "":"&");
     if (post_data != "") url += "?"+post_data;
     // create request
     HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
     req.Method = "GET";
     req.ContentType = "application/x-www-form-urlencoded";
     req.AllowWriteStreamBuffering = true;
     req.KeepAlive = true;
     req.Timeout = 4000;
     // append cookies
     if (cookies == null)
         req.CookieContainer = new CookieContainer();
     else
     {
         req.CookieContainer = cookies;
     }
     // get response
     HttpWebResponse response = (HttpWebResponse)req.GetResponse();
     Stream streamResponse = response.GetResponseStream();
     StreamReader streamRead = new StreamReader(streamResponse);
     string responseString = streamRead.ReadToEnd();
     if (callback != null) callback(responseString, req.CookieContainer);
     streamResponse.Close();
     streamRead.Close();
     /*
     req.BeginGetResponse(
     delegate(System.IAsyncResult asynchronousResult)
     {
         HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
         HttpWebResponse response = (HttpWebResponse)request.GetResponse();
         Stream streamResponse = response.GetResponseStream();
         StreamReader streamRead = new StreamReader(streamResponse);
         string responseString = streamRead.ReadToEnd();
         if (callback != null) callback(responseString, request.CookieContainer);
         streamResponse.Close();
         streamRead.Close();
         response.Close();
     }, req);*/
 }
示例#7
0
        /// <summary>
        /// Gets a level from the server.
        /// </summary>
        /// <param name="OnGet">The process to run on the level JSON.</param>
        public void GetLevel(HandleResponse OnGet)
        {
            Settings settings = Settings.instance;

            settings.LoadSettings();
            PlayerMover player = PlayerMover.instance;

            WWWForm settingsForm = new WWWForm();

            settingsForm.AddField(Settings.PATH_KEY, settings.pathSetting.ToString());
            settingsForm.AddField(Settings.MOVEMENT_KEY, settings.movementSetting.ToString());
            settingsForm.AddField(Settings.DIFFICULTY_KEY, settings.difficultySetting.ToString());
            settingsForm.AddField(PlayerMover.POSITION_KEY, InputUtil.ConvertVectorToPOST(player.transform.position));
            settingsForm.AddField("numDeaths", GameManager.numDeaths);

            ProcessStringFromURL(levelURL, OnGet, settingsForm);
        }
示例#8
0
        /// <summary>
        /// Processes a string obtained from a URL.
        /// </summary>
        /// <param name="url">The URL to get a string from.</param>
        /// <param name="OnGet">The process to run on the string obtained from the specified URL.</param>
        /// <param name="form">The form to pass to the URL.</param>
        private IEnumerator GetURL(string url, HandleResponse OnGet, WWWForm form = null)
        {
            if (form == null)
            {
                form = new WWWForm();
            }
            WWW www = new WWW(host + baseURL + url, form);

            yield return(www);

            if (www.error == null)
            {
                OnGet(www.text);
            }
            else
            {
                Debug.Log("Error getting URL: " + www.url);
                Debug.Log(www.error);
            }
        }
        public static void Perform(HttpWebRequest request,
                                   ID2LUserContext userContext,
                                   HandleResponse responseHandler,
                                   HandleError errorHandler,
                                   int retryAttempts = 0)
        {
            try {
                using (var response = (HttpWebResponse)request.GetResponse()) {
                    using (var stream = response.GetResponseStream()) {
                        using (var reader = new StreamReader(stream, Encoding.UTF8)) {
                            string responseBody = reader.ReadToEnd();
                            responseHandler(responseBody);
                        }
                    }
                }
            }
            catch (WebException we) {
                var exceptionWrapper = new D2LWebException(we);
                var result           = userContext.InterpretResult(exceptionWrapper);

                switch (result)
                {
                case RequestResult.RESULT_INVALID_TIMESTAMP:
                    if (retryAttempts > 0)
                    {
                        // re-create the request to ensure the new url accounts for calculated skew
                        Uri uri = userContext.CreateAuthenticatedUri(request.RequestUri.AbsoluteUri,
                                                                     request.Method);

                        request = (HttpWebRequest)WebRequest.Create(uri);

                        Perform(request, userContext, responseHandler, errorHandler, retryAttempts - 1);
                    }
                    break;
                }
                errorHandler(result, request.RequestUri);
            }
            catch (ArgumentException) {
                errorHandler(RequestResult.RESULT_UNKNOWN, request.RequestUri);
            }
        }
        public static void Perform( HttpWebRequest request,
            ID2LUserContext userContext,
            HandleResponse responseHandler,
            HandleError errorHandler,
            int retryAttempts = 0)
        {
            try {
                using (var response = (HttpWebResponse) request.GetResponse()) {
                    using (var stream = response.GetResponseStream()) {
                        using (var reader = new StreamReader( stream, Encoding.UTF8 )) {
                            string responseBody = reader.ReadToEnd();
                            responseHandler( responseBody );
                        }
                    }
                }
            }
            catch (WebException we) {
                var exceptionWrapper = new D2LWebException( we );
                var result = userContext.InterpretResult( exceptionWrapper );

                switch (result) {
                    case RequestResult.RESULT_INVALID_TIMESTAMP:
                        if (retryAttempts > 0) {
                            // re-create the request to ensure the new url accounts for calculated skew
                            Uri uri = userContext.CreateAuthenticatedUri( request.RequestUri.AbsoluteUri,
                                                                          request.Method );

                            request = (HttpWebRequest) WebRequest.Create( uri );

                            Perform( request, userContext, responseHandler, errorHandler, retryAttempts - 1 );
                        }
                        break;
                }
                errorHandler( result, request.RequestUri );
            }
            catch (ArgumentException) {
                errorHandler( RequestResult.RESULT_UNKNOWN, request.RequestUri );
            }
        }
示例#11
0
        public HandleResponse <int> UpdateUser(UserUpdateViewModel req)
        {
            HandleResponse <int> rm = new HandleResponse <int>();

            return(rm);
        }
示例#12
0
 /// <summary>
 /// Refreshes the level after being marked as dirty.
 /// </summary>
 /// <param name="OnGet">The process to run on the level refresh JSON.</param>
 public void RefreshLevel(HandleResponse OnGet, WWWForm form)
 {
     //ProcessStringFromURL(refreshURL, OnGet, form);
 }
示例#13
0
    public static void      RequestGet(string url, HandleResponse callback, CookieContainer cookies, params string[] post_data_pair)
    {
        if (post_data_pair != null && post_data_pair.Length % 2 != 0)
        {
            Debug.LogError("Post data params shoud be an array of name and value pairs");
            return;
        }
        // create get data
        string post_data = "";

        for (int i = 0; i < post_data_pair.Length; i += 2)
        {
            post_data += post_data_pair[i] + "=" + post_data_pair[i + 1] + ((i == post_data_pair.Length - 2)? "":"&");
        }
        if (post_data != "")
        {
            url += "?" + post_data;
        }
        // create request
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);

        req.Method      = "GET";
        req.ContentType = "application/x-www-form-urlencoded";
        req.AllowWriteStreamBuffering = true;
        req.KeepAlive = true;
        req.Timeout   = 4000;
        // append cookies
        if (cookies == null)
        {
            req.CookieContainer = new CookieContainer();
        }
        else
        {
            req.CookieContainer = cookies;
        }
        // get response
        HttpWebResponse response       = (HttpWebResponse)req.GetResponse();
        Stream          streamResponse = response.GetResponseStream();
        StreamReader    streamRead     = new StreamReader(streamResponse);
        string          responseString = streamRead.ReadToEnd();

        if (callback != null)
        {
            callback(responseString, req.CookieContainer);
        }
        streamResponse.Close();
        streamRead.Close();

        /*
         * req.BeginGetResponse(
         * delegate(System.IAsyncResult asynchronousResult)
         * {
         * HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
         *      HttpWebResponse response = (HttpWebResponse)request.GetResponse();
         *      Stream streamResponse = response.GetResponseStream();
         * StreamReader streamRead = new StreamReader(streamResponse);
         * string responseString = streamRead.ReadToEnd();
         *      if (callback != null) callback(responseString, request.CookieContainer);
         * streamResponse.Close();
         * streamRead.Close();
         * response.Close();
         * }, req);*/
    }
示例#14
0
        /// <summary>
        /// Initiates the full course listing.
        /// </summary>
        /// <param name="scopingUser">The username for scoping the report if report uses it</param>
        /// <param name="format">The format</param>
        /// <param name="report">The report name</param>
        /// <param name="reportParams">The report parameters.</param>
        /// <param name="language">The language, or NULL</param>
        /// <param name="duration">The duration to retain report (Use one of the following numeric values: 1 - 1 hour, 2 - 8 hours, 3 - 24 hours.</param>
        /// <param name="client">The client.</param>
        /// <param name="closeclient">if set to <c>true</c> [closeclient].</param>
        /// <returns></returns>
        public static HandleResponse SubmitReport(string scopingUser, reportFormat format, string report, MapItem[] reportParams, string language, int duration, OlsaPortTypeClient client, bool closeclient = false)
        {
            //Set up our response object
            HandleResponse response = null;

            try
            {
                //Create our request
                SubmitReportRequest request = new SubmitReportRequest();

                //Pull the OlsaAuthenticationBehviour so we can extract the customerid
                AuthenticationBehavior olsaCredentials = (AuthenticationBehavior)client.ChannelFactory.Endpoint.Behaviors.Where(p => p.GetType() == typeof(AuthenticationBehavior)).FirstOrDefault();
                request.customerId = olsaCredentials.UserName;

                request.scopingUserId    = scopingUser;
                request.reportFormat     = format;
                request.report           = report;
                request.language         = language;
                request.duration         = duration;
                request.reportParameters = reportParams;


                response = client.UD_SubmitReport(request);
            }
            catch (WebException)
            {
                // This captures any Web Exceptions such as proxy errors etc
                // See http://msdn.microsoft.com/en-us/library/48ww3ee9(VS.80).aspx
                throw;
            }
            catch (TimeoutException)
            {
                //This captures the WCF timeout exception
                throw;
            }
            //WCF fault exception will be thrown for any other issues such as Security
            catch (FaultException fe)
            {
                if (fe.Message.ToLower(CultureInfo.InvariantCulture).Contains("the security token could not be authenticated or authorized"))
                {
                    //The OLSA Credentials specified could not be authenticated
                    throw;
                }
                throw;
            }
            catch (Exception)
            {
                //Any other type of exception, perhaps out of memory
                throw;
            }
            finally
            {
                //Shutdown and dispose of the client
                if (client != null)
                {
                    if (client.State == CommunicationState.Faulted)
                    {
                        client.Abort();
                    }
                    if (closeclient)
                    {
                        //We cannot resue client if we close
                        client.Close();
                    }
                }
            }
            return(response);
        }
示例#15
0
 /// <summary>
 /// Processes a string obtained from a URL.
 /// </summary>
 /// <param name="url">The URL to get a string from.</param>
 /// <param name="OnGet">The process to run on the string obtained from the URL.</param>
 /// <param name="form">The form to pass to the URL.</param>
 private void ProcessStringFromURL(string url, HandleResponse OnGet, WWWForm form = null)
 {
     StartCoroutine(GetURL(url, OnGet, form));
 }
示例#16
0
 /// <summary>
 /// Checks if the level needs to be refreshed.
 /// </summary>
 /// <param name="OnGet">The process to run on the dirty response.</param>
 public void CheckDirty(HandleResponse OnGet)
 {
     //ProcessStringFromURL(dirtyURL, OnGet);
 }
示例#17
0
        static void Process(Uri endpoint, string customerId, string sharedSecret)
        {
            //Create the OLSA Web Services Client using code
            OlsaPortTypeClient client = Helpers.Olsa.GetOLSAClient(endpoint, customerId, sharedSecret);

            Console.WriteLine("Issuing the UD_SubmitReport Request");
            Console.WriteLine("------------------------------------");
            HandleResponse handleResponse = new HandleResponse();

            //--------------------------------------------------------------------------------------------
            //Define report settings here to ease changes
            string       scopingUserId  = "admin";
            reportFormat reportFormat   = reportFormat.CSV;
            string       reportFilename = "report." + reportFormat.ToString();

            string reportLanguage     = "en_US"; //en_US only supported value
            int    reportRetainperiod = 3;       //1 - 1 hour, 2 - 8 hours, 3 - 24 hours.

            //For details of report names and parameters see https://documentation.skillsoft.com/en_us/skillport/8_0/ah/35465.htm
            string reportName = "summary_catalog";
            //Define report parameters
            List <MapItem> paramList = new List <MapItem>();

            paramList.Add(new MapItem()
            {
                key = "asset_category", value = "1,2,3,4,5,21"
            });
            paramList.Add(new MapItem()
            {
                key = "display_options", value = "all"
            });


            //--------------------------------------------------------------------------------------------

            //Submit Report request
            try
            {
                handleResponse = Helpers.Olsa.SubmitReport(scopingUserId, reportFormat, reportName, paramList.ToArray(), reportLanguage, reportRetainperiod, client, false);

                //Minutes between polls
                int sleepInterval = 2;
                Console.WriteLine("Handle: {0}", handleResponse.handle);

                UrlResponse url = null;

                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine("{0}: Sleeping {1} minutes", DateTime.UtcNow.ToLongTimeString(), sleepInterval);
                    //ms - so here we sleep for 10 minutes
                    System.Threading.Thread.Sleep(sleepInterval * 60 * 1000);

                    try
                    {
                        url = Helpers.Olsa.PollforReport(handleResponse.handle, client, false);
                        break;
                    }
                    catch (FaultException <Olsa.DataNotReadyYetFault> )
                    {
                        //The report has not completed generation, we are checking for a Specific OLSA Exception
                        Console.WriteLine("{0}: The specified report is not yet ready", DateTime.UtcNow.ToLongTimeString());
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("{0}: Issue while Polling for Report.", DateTime.UtcNow.ToLongTimeString());
                        Console.WriteLine("{0}: Exception: {1}", DateTime.UtcNow.ToLongTimeString(), ex.ToString());
                        throw;
                    }
                }

                if (url != null)
                {
                    WebClient myWebClient = new WebClient();
                    Console.WriteLine("{0}: Downloading Report: {1}", DateTime.UtcNow.ToLongTimeString(), url.olsaURL);
                    myWebClient.DownloadFile(url.olsaURL, reportFilename);
                    Console.WriteLine("{0}: Successfully Downloaded: {1}", DateTime.UtcNow.ToLongTimeString(), reportFilename);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0}: Issue while Submitting Report.", DateTime.UtcNow.ToLongTimeString());
                Console.WriteLine("{0}: Exception: {1}", DateTime.UtcNow.ToLongTimeString(), ex.ToString());
            }
            //Now we can close the client
            if (client != null)
            {
                if (client.State == CommunicationState.Faulted)
                {
                    client.Abort();
                }

                client.Close();
            }
        }
示例#18
0
        public async Task <IActionResult> Delete(DeleteOwner.DeleteOwnerRequest ownerRequest)
        {
            var result = await Mediator.Send(ownerRequest);

            return(HandleResponse.Response(result));
        }
示例#19
0
        public async Task <IActionResult> Createpost(CreatePost.CreatePostRequest create)
        {
            var result = await Mediator.Send(create);

            return(HandleResponse.Response(result));
        }
示例#20
0
        /// <summary>
        /// Initiates the asset meta data.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="metadataFormat">The metadata format.</param>
        /// <param name="initiationMode">The initiation mode.</param>
        /// <param name="onsuccessclose">if set to <c>true</c> [onsuccessclose].</param>
        /// <returns></returns>
        /// <exception cref="AIPOC.Exceptions.OlsaSecurityException"></exception>
        public static string AI_InitiateAssetMetaData(OlsaPortTypeClient client, assetMetadataFormat metadataFormat, assetInitiationMode initiationMode, bool onsuccessclose = false)
        {
            HandleResponse handleResponse = new HandleResponse();

            try
            {
                log.InfoFormat("Sending AI_InitiateAssetMetadata Request. Format: {0} Mode: {1}", metadataFormat, initiationMode);
                InitiateAssetMetaDataRequest request = new InitiateAssetMetaDataRequest();

                //Pull the OlsaAuthenticationBehviour so we can extract the customerid
                AuthenticationBehavior olsaCredentials = (AuthenticationBehavior)client.ChannelFactory.Endpoint.Behaviors.Where(p => p.GetType() == typeof(AuthenticationBehavior)).FirstOrDefault();
                request.customerId     = olsaCredentials.UserName;
                request.initiationMode = initiationMode;
                request.metadataFormat = metadataFormat;

                handleResponse = client.AI_InitiateAssetMetaData(request);
            }
            catch (WebException)
            {
                // This captures any Web Exepctions such as DNS lookup errors, HTTP status errors such as 404, proxy errors etc
                // See http://msdn.microsoft.com/en-us/library/48ww3ee9(VS.80).aspx
                throw;
            }
            catch (TimeoutException)
            {
                //This captures the WCF timeout exception
                throw;
            }
            //Olsa.GeneralFault exception will be thrown for issues like parameters invalid, user does could not be created etc
            catch (FaultException <Olsa.GeneralFault> )
            {
                throw;
            }
            //WCF fault exception will be thrown for any other issues such as Security
            catch (FaultException fe)
            {
                if (fe.Message.ToLower(CultureInfo.InvariantCulture).Contains("the security token could not be authenticated or authorized"))
                {
                    //The OLSA Credentials specified could not be authenticated
                    //Check the values in the web.config are correct for OLSA.CustomerID and OLSA.SharedSecret - these are case sensitive
                    //Check the time on the machine, the SOAP message is valid for 5 minutes. This means that if the time on the calling machine
                    //is to slow OR to fast then the SOAP message will be invalid.
                    throw new Exceptions.OlsaSecurityException();
                }
                throw;
            }
            catch (CommunicationException)
            {
                throw;
            }
            catch (Exception)
            {
                //Any other type of exception, perhaps out of memory
                throw;
            }
            finally
            {
                if (client != null)
                {
                    if (client.State == CommunicationState.Faulted)
                    {
                        client.Abort();
                    }
                    if (onsuccessclose)
                    {
                        client.Close();
                    }
                }
            }
            return(handleResponse.handle);
        }
示例#21
0
        public async Task <IActionResult> GetAll()
        {
            var result = await Mediator.Send(new GettAllProject.GetAllProjectRequest());

            return(HandleResponse.Response(result));
        }