Exemple #1
0
 public Stream Post(string arguments, Stream body)
 {
     WcfResponse response = new WcfResponse();
     if (!_handler.ProcessRequest(new WcfRequest(body), response))
         NotFound(response);
     return response.ToStream();
 }
Exemple #2
0
 public WcfResponse Create(CriteriaRequest request)
 {
   Csla.Server.DataPortal portal = new Csla.Server.DataPortal();
   Exception error = null;
   DataPortalResult  result = null;
   WcfResponse response = null;
   ISerializationFormatter formatter = SerializationFormatterFactory.GetFormatter();
   try
   {
     request = ConvertRequest(request);
     DataPortalContext context = new DataPortalContext(
         formatter.Deserialize(request.Principal) as IPrincipal,
         true,
         request.ClientCulture,
         request.ClientUICulture,
         formatter.Deserialize(request.ClientContext) as ContextDictionary,
         formatter.Deserialize(request.GlobalContext) as ContextDictionary);
     result = portal.Create(Type.GetType(request.TypeName), formatter.Deserialize(request.CriteriaData), context);
     response = new WcfResponse(
         formatter.Serialize(result.ReturnObject),
         formatter.Serialize(error),
         formatter.Serialize(Csla.ApplicationContext.GlobalContext));
   }
   catch (Exception ex)
   {
     error = ex;
     response = new WcfResponse(
        null,
        formatter.Serialize(error),
        formatter.Serialize(Csla.ApplicationContext.GlobalContext));
   }
   return ConvertResponse(response);
 }
 public WcfResponse ChangePassword(string username, string oldpasswd, string newpassword)
 {
     WcfResponse response = new WcfResponse();
     User user = DataEntities.User.FirstOrDefault(u => u.UserName == username);
     if (user != null)
     {
         if (user.Password == oldpasswd)
         {
             try
             {
                 user.Password = newpassword;
                 DataEntities.SaveChanges();
             }
             catch (Exception ex)
             {
                 response.success = WcfResponseStatus.Failed;
                 response.message = ex.Message;
             }
         }
         else
         {
             response.success = WcfResponseStatus.CurrentPasswordIncorrect;
             response.message = "Current password incorrect";
         }
     }
     else
     {
         response.success = WcfResponseStatus.UserNotFound;
         response.message = "User not found";
     }
     return response;
 }
Exemple #4
0
 protected override WcfResponse ConvertResponse(WcfResponse response)
 {
   WcfResponse returnValue = new WcfResponse();
   returnValue.GlobalContext = CompressionUtility.Compress(response.GlobalContext);
   returnValue.ObjectData = CompressionUtility.Compress(response.ObjectData);
   returnValue.Error = response.Error;
   return returnValue;
 }
 public WcfResponse AddUser(User newUser, Guid adminID, string adminPwd)
 {
     WcfResponse response = new WcfResponse();
     //TODO add check for admin role
     User admin = DataEntities.User.FirstOrDefault(u => u.UserID == adminID && u.Password == adminPwd);
     if (admin != null)
     {
         if (newUser != null)
         {
             User existingUser = DataEntities.User.FirstOrDefault(u => u.UserName == newUser.UserName);
             if (existingUser == null)
             {
                 try
                 {
                     DataEntities.User.Add(newUser);
                     DataEntities.SaveChanges();
                 }
                 catch (Exception ex)
                 {
                     response.success = WcfResponseStatus.Failed;
                     response.message = ex.Message;
                 }
             }
             else
             {
                 response.success = WcfResponseStatus.UserNameAlreadyUsed;
                 response.message = "Username already exists";
             }
         }
         else
         {
             response.success = WcfResponseStatus.Failed;
             response.message = "No user data provided";
         }
     }
     else
     {
         response.success = WcfResponseStatus.Failed;
         response.message = "Incorrect admin data";
     }
     return response;
 }
Exemple #6
0
        /// <summary>
        /// Called by <see cref="DataPortal" /> to load an
        /// existing business object.
        /// </summary>
        /// <param name="objectType">Type of business object to create.</param>
        /// <param name="criteria">Criteria object describing business object.</param>
        /// <param name="context">
        /// <see cref="Server.DataPortalContext" /> object passed to the server.
        /// </param>
        /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
#pragma warning disable 1998
        public async Task <DataPortalResult> Fetch(Type objectType, object criteria, DataPortalContext context, bool isSync)
#pragma warning restore 1998
        {
#if !SILVERLIGHT && !NETFX_CORE
            ChannelFactory <IWcfPortal> cf = GetChannelFactory();
            var         proxy    = GetProxy(cf);
            WcfResponse response = null;
#if NET40
            try
            {
                var request = new FetchRequest(objectType, criteria, context);
                if (isSync)
                {
                    response = proxy.Fetch(request);
                }
                else
                {
                    var worker = new Csla.Threading.BackgroundWorker();
                    var tcs    = new TaskCompletionSource <WcfResponse>();
                    worker.RunWorkerCompleted += (o, e) =>
                    {
                        tcs.SetResult((WcfResponse)e.Result);
                    };
                    worker.DoWork += (o, e) =>
                    {
                        e.Result = proxy.Fetch(request);
                    };
                    worker.RunWorkerAsync();
                    response = await tcs.Task;
                }
                if (cf != null)
                {
                    cf.Close();
                }
                object result = response.Result;
                if (result is Exception)
                {
                    throw (Exception)result;
                }
                return((DataPortalResult)result);
            }
            catch
            {
                cf.Abort();
                throw;
            }
#else
            try
            {
                var request = new FetchRequest(objectType, criteria, context);
                if (isSync)
                {
                    response = proxy.Fetch(request);
                }
                else
                {
                    response = await proxy.FetchAsync(request);
                }
                if (cf != null)
                {
                    cf.Close();
                }
            }
            catch
            {
                cf.Abort();
                throw;
            }
            object result = response.Result;
            if (result is Exception)
            {
                throw (Exception)result;
            }
            return((DataPortalResult)result);
#endif
#else // WinRT and Silverlight
            var request = GetBaseCriteriaRequest();
            request.TypeName = objectType.AssemblyQualifiedName;
            if (!(criteria is IMobileObject))
            {
                criteria = new PrimitiveCriteria(criteria);
            }
            request.CriteriaData = MobileFormatter.Serialize(criteria);

            request = ConvertRequest(request);

            var proxy = GetProxy();
            DataPortalResult result = null;

#if !NETFX_CORE // Silverlight
            var tcs = new TaskCompletionSource <DataPortalResult>();
            proxy.FetchCompleted += (s, e) =>
            {
                try
                {
                    Csla.WcfPortal.WcfResponse response = null;
                    if (e.Error == null)
                    {
                        response = ConvertResponse(e.Result);
                    }
                    ContextDictionary globalContext = null;
                    if (response != null)
                    {
                        globalContext = (ContextDictionary)MobileFormatter.Deserialize(response.GlobalContext);
                    }
                    if (e.Error == null && response != null && response.ErrorData == null)
                    {
                        var obj = MobileFormatter.Deserialize(response.ObjectData);
                        result = new DataPortalResult(obj, null, globalContext);
                    }
                    else if (response != null && response.ErrorData != null)
                    {
                        var ex = new DataPortalException(response.ErrorData);
                        result = new DataPortalResult(null, ex, globalContext);
                    }
                    else
                    {
                        result = new DataPortalResult(null, e.Error, globalContext);
                    }
                }
                catch (Exception ex)
                {
                    result = new DataPortalResult(null, ex, null);
                }
                finally
                {
                    tcs.SetResult(result);
                }
            };
            proxy.FetchAsync(request);
            var finalresult = await tcs.Task;
            if (finalresult.Error != null)
            {
                throw finalresult.Error;
            }
            return(finalresult);
#else // WinRT
            try
            {
                var response = await proxy.FetchAsync(request);

                response = ConvertResponse(response);
                if (response == null)
                {
                    throw new DataPortalException("null response", null);
                }
                var globalContext = (ContextDictionary)MobileFormatter.Deserialize(response.GlobalContext);
                if (response.ErrorData == null)
                {
                    var obj = MobileFormatter.Deserialize(response.ObjectData);
                    result = new DataPortalResult(obj, null, globalContext);
                }
                else
                {
                    var ex = new DataPortalException(response.ErrorData);
                    result = new DataPortalResult(null, ex, globalContext);
                }
            }
            catch (Exception ex)
            {
                result = new DataPortalResult(null, ex, null);
            }
            if (result.Error != null)
            {
                throw result.Error;
            }
            return(result);
#endif
#endif
        }
Exemple #7
0
 protected virtual WcfResponse ConvertResponse(WcfResponse response)
 {
     return(response);
 }
Exemple #8
0
        private async Task InstallAsync()
        {
            await RunCommandAsync(() => InstallIsRunning, async() =>
            {
                try
                {
                    {
                        var m = new MessageBoxDialogConfirmViewModel
                        {
                            Title   = "CONFIRM",
                            Message = "Do you really want to run?",
                        };
                        await IoC.UI.ShowMessage(m);
                        if (m.DialogResult == DialogResult.No)
                        {
                            return;
                        }
                    }

                    List <AdGroupItem> SeletedAdGroupItems = new List <AdGroupItem>();
                    foreach (var item in AdGroupItems)
                    {
                        if (item.IsChecked)
                        {
                            SeletedAdGroupItems.Add(item);
                        }
                    }
                    if (SeletedAdGroupItems.Count != 1)
                    {
                        throw new Exception("Select One AD Group");
                    }
                    if (string.IsNullOrEmpty(DomainName))
                    {
                        throw new Exception("Type DomainName");
                    }
                    if (!DomainName.Contains("."))
                    {
                        throw new Exception("Please enter the domain name in FQDN format. '.' This should be included. Ex) ncpdom.local, ncp.local, myad.local");
                    }
                    //if (string.IsNullOrEmpty(NetBiosName))
                    //    throw new Exception("Type NetBiosName");
                    //if (NetBiosName.Length > 15)
                    //    throw new Exception("NetBiosName should be less than 15 characters");
                    if (string.IsNullOrEmpty(SafeModePassword))
                    {
                        throw new Exception("Type SafeMode Password");
                    }
                    if (SafeModePassword.Length <= 7)
                    {
                        throw new Exception("SafeMode Passord : minimum password length is 8");
                    }
                    if (!(SpecialChar.IsContainUpperChar(SafeModePassword) && SpecialChar.IsContainLowerChar(SafeModePassword) && SpecialChar.IsContainNumChar(SafeModePassword)))
                    {
                        throw new Exception("SafeMode Passord : A combination of uppercase and lowercase numbers is required");
                    }
                    if (string.IsNullOrEmpty(MstscPort))
                    {
                        throw new Exception("Type MSTSC Port(RDP)");
                    }
                    if (!int.TryParse(MstscPort, out int portNum))
                    {
                        throw new Exception("MSTSC port number must be numeric.");
                    }
                    if (int.TryParse(MstscPort, out int portNum2))
                    {
                        if (portNum2 > 20000)
                        {
                            throw new Exception("MSTSC port is recommended to be 10000 ~ 20000.");
                        }
                    }

                    if (MstscPort == "3389")
                    {
                        var m = new MessageBoxDialogConfirmViewModel
                        {
                            Title   = "CONFIRM",
                            Message = "The MSTSC port is the default port. Targeted for RDP attacks, would you like to proceed?",
                        };
                        await IoC.UI.ShowMessage(m);
                        if (m.DialogResult == DialogResult.No)
                        {
                            return;
                        }
                    }

                    // step 1
                    StepName      = "Install Started";
                    ProgressValue = 0;
                    AppendVerifyLog(StepName);

                    string response         = string.Empty;
                    WcfResponse wcfResponse = new WcfResponse();

                    var step      = 0;
                    var debugStep = 0;

                    // dir test
                    step++;
                    if (debugStep <= step)
                    {
                        string psCmd = $@"dir c:\";
                        StepName     = $"STEP {step} : communication test";
                        AppendVerifyLog($"{StepName} started");
                        AppendVerifyLog($"{StepName} + {psCmd}");
                        var task = dataManager.Execute
                                       ("ExecuterPs"
                                       , "out-string"
                                       , psCmd
                                       , CsLib.RequestType.POST
                                       , $"https://{SeletedAdGroupItems.FirstOrDefault().MasterServerPublicIp}:9090"
                                       , @"/LazyServer/LazyCommand/PostCmd"
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                                       , 30
                                       );
                        response = await task;
                        AppendVerifyLog($"{StepName} {response}");
                        wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

                        if (!wcfResponse.IsSuccess)
                        {
                            AppendVerifyLog($"{StepName} failed ({wcfResponse.ErrorMessage})");
                            throw new Exception($"{StepName} failed ({wcfResponse.ErrorMessage})");
                        }

                        ProgressValue = 10;
                        AppendVerifyLog(StepName + " completed successfully");
                    }



                    step++;
                    if (debugStep <= step) //added
                    {
                        string psCmd = $"Set-Service RemoteRegistry -StartupType Automatic" + Environment.NewLine
                                       + $"Start-Service RemoteRegistry";

                        StepName = $"STEP {step} : RemoteRegistry Enable";
                        AppendVerifyLog($"{StepName} started");
                        AppendVerifyLog($"{StepName} + {psCmd}");
                        var task = dataManager.Execute
                                       ("ExecuterPs"
                                       , "out-string"
                                       , psCmd
                                       , CsLib.RequestType.POST
                                       , $"https://{SeletedAdGroupItems.FirstOrDefault().MasterServerPublicIp}:9090"
                                       , @"/LazyServer/LazyCommand/PostCmd"
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                                       , 30
                                       );
                        response = await task;
                        AppendVerifyLog(response);
                        wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

                        if (!wcfResponse.IsSuccess)
                        {
                            AppendVerifyLog($"{StepName} failed ({wcfResponse.ErrorMessage})");
                            throw new Exception($"{StepName} failed ({wcfResponse.ErrorMessage})");
                        }
                        ProgressValue = 20;
                        AppendVerifyLog(StepName + " completed successfully");
                    }

                    // hosts add ip
                    step++;
                    if (debugStep <= step)
                    {
                        string psCmd = $"Clear-Content -Path \"C:\\Windows\\System32\\drivers\\etc\\hosts\"" + Environment.NewLine
                                       + $"Add-Content -Path \"C:\\Windows\\System32\\drivers\\etc\\hosts\" -Value \"{SeletedAdGroupItems.FirstOrDefault().MasterServerPublicIp}    {SeletedAdGroupItems.FirstOrDefault().MasterServerName}\"" + Environment.NewLine
                                       + $"Add-Content -Path \"C:\\Windows\\System32\\drivers\\etc\\hosts\" -Value \"{SeletedAdGroupItems.FirstOrDefault().SlaveServerPublicIp}    {SeletedAdGroupItems.FirstOrDefault().SlaveServerName}\"";
                        StepName = $"STEP {step} : hosts add ip";
                        AppendVerifyLog($"{StepName} started");
                        AppendVerifyLog($"{StepName} + {psCmd}");
                        var task = dataManager.Execute
                                       ("ExecuterPs"
                                       , "out-string"
                                       , psCmd
                                       , CsLib.RequestType.POST
                                       , $"https://{SeletedAdGroupItems.FirstOrDefault().MasterServerPublicIp}:9090"
                                       , @"/LazyServer/LazyCommand/PostCmd"
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                                       , 30
                                       );
                        response = await task;
                        AppendVerifyLog(response);
                        wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

                        if (!wcfResponse.IsSuccess)
                        {
                            AppendVerifyLog($"{StepName} failed ({wcfResponse.ErrorMessage})");
                            throw new Exception($"{StepName} failed ({wcfResponse.ErrorMessage})");
                        }
                        ProgressValue = 20;
                        AppendVerifyLog(StepName + " completed successfully");
                    }

                    // hosts add ip confirm
                    step++;
                    if (debugStep <= step)
                    {
                        string psCmd = $"get-content  \"C:\\Windows\\System32\\drivers\\etc\\hosts\"";
                        StepName     = $"STEP {step} : hosts add ip confirm";
                        AppendVerifyLog($"{StepName} started");
                        AppendVerifyLog($"{StepName} + {psCmd}");
                        var task = dataManager.Execute
                                       ("ExecuterPs"
                                       , "out-string"
                                       , psCmd
                                       , CsLib.RequestType.POST
                                       , $"https://{SeletedAdGroupItems.FirstOrDefault().MasterServerPublicIp}:9090"
                                       , @"/LazyServer/LazyCommand/PostCmd"
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                                       , 30
                                       );
                        response = await task;
                        AppendVerifyLog(response);
                        wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

                        if (!wcfResponse.IsSuccess)
                        {
                            AppendVerifyLog($"{StepName} failed ({wcfResponse.ErrorMessage})");
                            throw new Exception($"{StepName} failed ({wcfResponse.ErrorMessage})");
                        }
                        ProgressValue = 30;
                        AppendVerifyLog(StepName + " completed successfully");
                    }

                    step++;
                    if (debugStep <= step) //4
                    {
                        string psCmd = ""

                                       + $"$contents=[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String(\"JABhAGQAYQBwAHQAZQByACAAPQAgAEcAZQB0AC0ATgBlAHQAQQBkAGEAcAB0AGUAcgAgAHwAIAA/ACAAewAkAF8ALgBTAHQAYQB0AHUAcwAgAC0AZQBxACAAIgB1AHAAIgB9AA0ACgAkAEkAUAAgAD0AIAAoACQAYQBkAGEAcAB0AGUAcgAgAHwAIABHAGUAdAAtAE4AZQB0AEkAUABDAG8AbgBmAGkAZwB1AHIAYQB0AGkAbwBuACkALgBJAFAAdgA0AEEAZABkAHIAZQBzAHMALgBJAFAAQQBkAGQAcgBlAHMAcwANAAoAJABHAEEAVABFAFcAQQBZACAAPQAgACgAJABhAGQAYQBwAHQAZQByACAAfAAgAEcAZQB0AC0ATgBlAHQASQBQAEMAbwBuAGYAaQBnAHUAcgBhAHQAaQBvAG4AKQAuAEkAUAB2ADQARABlAGYAYQB1AGwAdABHAGEAdABlAHcAYQB5AC4ATgBlAHgAdABIAG8AcAANAAoAJABCAEkAVABNAEEAUwBLACAAPQAgACgAJABhAGQAYQBwAHQAZQByACAAfAAgAEcAZQB0AC0ATgBlAHQASQBQAEMAbwBuAGYAaQBnAHUAcgBhAHQAaQBvAG4AKQAuAEkAUAB2ADQAQQBkAGQAcgBlAHMAcwAuAFAAcgBlAGYAaQB4AEwAZQBuAGcAdABoAA0ACgAkAEQATgBTACAAPQAgACIAMQAyADcALgAwAC4AMAAuADEAIgANAAoAJABJAFAAVAB5AHAAZQAgAD0AIAAiAEkAUAB2ADQAIgANAAoAIwAgAFIAZQBtAG8AdgBlACAAYQBuAHkAIABlAHgAaQBzAHQAaQBuAGcAIABJAFAALAAgAGcAYQB0AGUAdwBhAHkAIABmAHIAbwBtACAAbwB1AHIAIABpAHAAdgA0ACAAYQBkAGEAcAB0AGUAcgANAAoASQBmACAAKAAoACQAYQBkAGEAcAB0AGUAcgAgAHwAIABHAGUAdAAtAE4AZQB0AEkAUABDAG8AbgBmAGkAZwB1AHIAYQB0AGkAbwBuACkALgBJAFAAdgA0AEEAZABkAHIAZQBzAHMALgBJAFAAQQBkAGQAcgBlAHMAcwApACAAewANAAoAJABhAGQAYQBwAHQAZQByACAAfAAgAFIAZQBtAG8AdgBlAC0ATgBlAHQASQBQAEEAZABkAHIAZQBzAHMAIAAtAEEAZABkAHIAZQBzAHMARgBhAG0AaQBsAHkAIAAkAEkAUABUAHkAcABlACAALQBDAG8AbgBmAGkAcgBtADoAJABmAGEAbABzAGUADQAKAH0ADQAKAEkAZgAgACgAKAAkAGEAZABhAHAAdABlAHIAIAB8ACAARwBlAHQALQBOAGUAdABJAFAAQwBvAG4AZgBpAGcAdQByAGEAdABpAG8AbgApAC4ASQBwAHYANABEAGUAZgBhAHUAbAB0AEcAYQB0AGUAdwBhAHkAKQAgAHsADQAKACQAYQBkAGEAcAB0AGUAcgAgAHwAIABSAGUAbQBvAHYAZQAtAE4AZQB0AFIAbwB1AHQAZQAgAC0AQQBkAGQAcgBlAHMAcwBGAGEAbQBpAGwAeQAgACQASQBQAFQAeQBwAGUAIAAtAEMAbwBuAGYAaQByAG0AOgAkAGYAYQBsAHMAZQANAAoAfQANAAoAJABhAGQAYQBwAHQAZQByACAAfAAgAE4AZQB3AC0ATgBlAHQASQBQAEEAZABkAHIAZQBzAHMAIAAtAEEAZABkAHIAZQBzAHMARgBhAG0AaQBsAHkAIAAkAEkAUABUAHkAcABlACAALQBJAFAAQQBkAGQAcgBlAHMAcwAgACQASQBQACAALQBQAHIAZQBmAGkAeABMAGUAbgBnAHQAaAAgACQAQgBJAFQATQBBAFMASwAgAC0ARABlAGYAYQB1AGwAdABHAGEAdABlAHcAYQB5ACAAJABHAEEAVABFAFcAQQBZAA0ACgAjACAAQwBvAG4AZgBpAGcAdQByAGUAIAB0AGgAZQAgAEQATgBTACAAYwBsAGkAZQBuAHQAIABzAGUAcgB2AGUAcgAgAEkAUAAgAGEAZABkAHIAZQBzAHMAZQBzAA0ACgAkAGEAZABhAHAAdABlAHIAIAB8ACAAUwBlAHQALQBEAG4AcwBDAGwAaQBlAG4AdABTAGUAcgB2AGUAcgBBAGQAZAByAGUAcwBzACAALQBTAGUAcgB2AGUAcgBBAGQAZAByAGUAcwBzAGUAcwAgACQARABOAFMADQAKAA==\"))" + Environment.NewLine
                                       + $"New-Item -Path \"c:\\script\\nicSettingMaster.ps1\"  -ItemType \"file\" -Force" + Environment.NewLine
                                       + $"Add-Content -Path \"c:\\script\\nicSettingMaster.ps1\" -Value $contents" + Environment.NewLine
                                       + $"try" + Environment.NewLine
                                       + $"<<" + Environment.NewLine
                                       + $"    powershell \"c:\\script\\nicSettingMaster.ps1\"  -ErrorAction Stop" + Environment.NewLine
                                       + $"    Write-Output \"completed\" " + Environment.NewLine
                                       + $">>" + Environment.NewLine
                                       + $"catch " + Environment.NewLine
                                       + $"<<" + Environment.NewLine
                                       + $"    Write-Output \"error\" " + Environment.NewLine
                                       + $">>";
                        psCmd = psCmd.Replace("<<", "{");
                        psCmd = psCmd.Replace(">>", "}");


                        StepName = $"STEP {step} : nic setting";
                        AppendVerifyLog($"{StepName} started");
                        AppendVerifyLog($"{StepName} + {psCmd}");
                        try
                        {
                            var task = dataManager.Execute
                                           ("ExecuterPs"
                                           , "out-string"
                                           , psCmd
                                           , CsLib.RequestType.POST
                                           , $"https://{SeletedAdGroupItems.FirstOrDefault().MasterServerPublicIp}:9090"
                                           , @"/LazyServer/LazyCommand/PostCmd"
                                           , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                                           , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                                           , 10
                                           );
                            response = await task;
                            AppendVerifyLog(response);
                            wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);
                        }
                        catch { }
                        AppendVerifyLog($"{StepName} completed");
                    }

                    // hosts add ip confirm
                    step++;
                    if (debugStep <= step) // 5
                    {
                        string psCmd = $"ipconfig /all";
                        StepName     = $"STEP {step} : dns ip confirm";
                        AppendVerifyLog($"{StepName} started");
                        AppendVerifyLog($"{StepName} + {psCmd}");
                        var task = dataManager.Execute
                                       ("ExecuterPs"
                                       , "out-string"
                                       , psCmd
                                       , CsLib.RequestType.POST
                                       , $"https://{SeletedAdGroupItems.FirstOrDefault().MasterServerPublicIp}:9090"
                                       , @"/LazyServer/LazyCommand/PostCmd"
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                                       , 30
                                       );
                        response = await task;
                        AppendVerifyLog(response);
                        wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

                        if (!wcfResponse.IsSuccess)
                        {
                            AppendVerifyLog($"{StepName} failed ({wcfResponse.ErrorMessage})");
                            throw new Exception($"{StepName} failed ({wcfResponse.ErrorMessage})");
                        }
                        ProgressValue = 40;
                        AppendVerifyLog(StepName + " completed successfully");
                    }

                    step++;
                    if (debugStep <= step) // 6
                    {
                        string psCmd = $"Install-windowsfeature AD-domain-services -IncludeManagementTools";
                        StepName     = $"STEP {step} : Install-windowsfeature AD-domain-services -IncludeManagementTools";
                        AppendVerifyLog($"{StepName} started");
                        AppendVerifyLog($"{StepName} + {psCmd}");
                        var task = dataManager.Execute
                                       ("ExecuterPs"
                                       , "out-string"
                                       , psCmd
                                       , CsLib.RequestType.POST
                                       , $"https://{SeletedAdGroupItems.FirstOrDefault().MasterServerPublicIp}:9090"
                                       , @"/LazyServer/LazyCommand/PostCmd"
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                                       , 600
                                       );
                        response = await task;
                        AppendVerifyLog(response);
                        wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

                        if (!wcfResponse.IsSuccess)
                        {
                            AppendVerifyLog($"{StepName} failed ({wcfResponse.ErrorMessage})");
                            throw new Exception($"{StepName} failed ({wcfResponse.ErrorMessage})");
                        }
                        ProgressValue = 70;
                        AppendVerifyLog(StepName + " completed successfully");
                    }

                    step++;
                    if (debugStep <= step) // 7
                    {
                        string psCmd = $"Import-Module ADDSDeployment";
                        StepName     = $"STEP {step} : Import-Module ADDSDeployment";
                        AppendVerifyLog($"{StepName} started");
                        AppendVerifyLog($"{StepName} + {psCmd}");
                        var task = dataManager.Execute
                                       ("ExecuterPs"
                                       , "out-string"
                                       , psCmd
                                       , CsLib.RequestType.POST
                                       , $"https://{SeletedAdGroupItems.FirstOrDefault().MasterServerPublicIp}:9090"
                                       , @"/LazyServer/LazyCommand/PostCmd"
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                                       , 300
                                       );
                        response = await task;
                        AppendVerifyLog(response);
                        wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

                        if (!wcfResponse.IsSuccess)
                        {
                            AppendVerifyLog($"{StepName} failed ({wcfResponse.ErrorMessage})");
                            throw new Exception($"{StepName} failed ({wcfResponse.ErrorMessage})");
                        }
                        ProgressValue = 80;
                        AppendVerifyLog(StepName + " completed successfully");
                    }

                    step++;
                    if (debugStep <= step) // 8
                    {
                        string psCmd = $"Install-ADDSForest -CreateDnsDelegation:$false -DatabasePath \"C:\\Windows\\NTDS\" -DomainMode \"{SelectedDomainModeItem.Display}\" -DomainName \"{DomainName}\" -DomainNetbiosName \"{NetBiosName}\" -ForestMode \"{SelectedDomainModeItem.Display}\" -InstallDns:$true -LogPath \"C:\\Windows\\NTDS\" -NoRebootOnCompletion:$false -SysvolPath \"C:\\Windows\\SYSVOL\" -SafeModeAdministratorPassword (Convertto-SecureString -AsPlainText \"{SafeModePassword}\" -Force) -Force:$true";
                        StepName     = $"STEP {step} : Import-Module ADDSDeployment";
                        AppendVerifyLog($"{StepName} started");
                        AppendVerifyLog($"{StepName} + {psCmd}");
                        var task = dataManager.Execute
                                       ("ExecuterPs"
                                       , "out-string"
                                       , psCmd
                                       , CsLib.RequestType.POST
                                       , $"https://{SeletedAdGroupItems.FirstOrDefault().MasterServerPublicIp}:9090"
                                       , @"/LazyServer/LazyCommand/PostCmd"
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                                       , 600
                                       );
                        response = await task;
                        AppendVerifyLog(response);
                        wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

                        if (!wcfResponse.IsSuccess)
                        {
                            AppendVerifyLog($"{StepName} failed ({wcfResponse.ErrorMessage})");
                            throw new Exception($"{StepName} failed ({wcfResponse.ErrorMessage})");
                        }
                        ProgressValue = 90;
                        AppendVerifyLog(StepName + " completed successfully");
                    }

                    step++;
                    if (debugStep <= step && !MstscPort.Equals("3389")) // 9
                    {
                        string psCmd = $"Set-ItemProperty -Path \"HKLM:\\System\\CurrentControlSet\\Control\\Terminal Server\\WinStations\\RDP-Tcp\\\" -Name PortNumber -Value {MstscPort}";

                        StepName = $"STEP {step} : MSTSC Port Chagne";
                        AppendVerifyLog($"{StepName} started");
                        AppendVerifyLog($"{StepName} + {psCmd}");
                        var task = dataManager.Execute
                                       ("ExecuterPs"
                                       , "out-string"
                                       , psCmd
                                       , CsLib.RequestType.POST
                                       , $"https://{SeletedAdGroupItems.FirstOrDefault().MasterServerPublicIp}:9090"
                                       , @"/LazyServer/LazyCommand/PostCmd"
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                                       , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                                       , 200
                                       );
                        response = await task;
                        AppendVerifyLog(response);
                        wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

                        if (!wcfResponse.IsSuccess)
                        {
                            AppendVerifyLog($"{StepName} failed ({wcfResponse.ErrorMessage})");
                            throw new Exception($"{StepName} failed ({wcfResponse.ErrorMessage})");
                        }
                        ProgressValue = 95;
                        AppendVerifyLog(StepName + " completed successfully");
                        AppendVerifyLog(StepName + " Restart Started");
                    }

                    step++;
                    if (debugStep <= step) // 10
                    {
                        try
                        {
                            StepName = $"STEP {step} : Restart";
                            AppendVerifyLog($"{StepName} started");
                            string endpoint = dataManager.GetValue(DataManager.Category.ApiGateway, DataManager.Key.Endpoint);
                            string action   = @"/server/v2/rebootServerInstances";
                            List <KeyValuePair <string, string> > parameters = new List <KeyValuePair <string, string> >();
                            parameters.Add(new KeyValuePair <string, string>("responseFormatType", "json"));
                            parameters.Add(new KeyValuePair <string, string>("serverInstanceNoList.1", SeletedAdGroupItems.FirstOrDefault().MasterServerInstanceNo));
                            SoaCall soaCall = new SoaCall();
                            var task        = soaCall.WebApiCall(endpoint, RequestType.POST, action, parameters, LogClient.Config.Instance.GetValue(Category.Api, Key.AccessKey), LogClient.Config.Instance.GetValue(Category.Api, Key.SecretKey));
                            response        = await task;

                            JsonSerializerSettings options = new JsonSerializerSettings
                            {
                                NullValueHandling     = NullValueHandling.Ignore,
                                MissingMemberHandling = MissingMemberHandling.Ignore
                            };

                            rebootServerInstances rebootServerInstances = JsonConvert.DeserializeObject <rebootServerInstances>(response, options);
                            if (rebootServerInstances.rebootServerInstancesResponse.returnCode.Equals("0"))
                            {
                                AppendVerifyLog(StepName + response);
                            }
                        }
                        catch (Exception ex)
                        {
                            AppendVerifyLog(StepName + $"Restart Request Failed : {ex.Message}");
                            throw new Exception($"Restart Request Failed : {ex.Message}");
                        }
                        ProgressValue = 99;
                        AppendVerifyLog(StepName + " completed successfully");
                        AppendVerifyLog(StepName + " Target Server Restart Started");
                        AppendVerifyLog(StepName + " After rebooting, you can check whether the domain was successfully created with the following command.");
                        AppendVerifyLog(StepName + " CMD >> systeminfo | findstr /B /C:\"Domain\"");
                    }

                    step++;
                    if (debugStep <= step) // 11
                    {
                        try
                        {
                            StepName = $"STEP {step} : Restart Check";
                            AppendVerifyLog($"{StepName} started");

                            for (int i = 0; i < 30; i++)
                            {
                                await Task.Delay(5000);

                                string endpoint = dataManager.GetValue(DataManager.Category.ApiGateway, DataManager.Key.Endpoint);
                                string action   = @"/server/v2/getServerInstanceList";
                                List <KeyValuePair <string, string> > parameters = new List <KeyValuePair <string, string> >();
                                parameters.Add(new KeyValuePair <string, string>("responseFormatType", "json"));
                                parameters.Add(new KeyValuePair <string, string>("serverInstanceNoList.1", SeletedAdGroupItems.FirstOrDefault().MasterServerInstanceNo));
                                SoaCall soaCall = new SoaCall();
                                var task        = soaCall.WebApiCall(endpoint, RequestType.POST, action, parameters, LogClient.Config.Instance.GetValue(Category.Api, Key.AccessKey), LogClient.Config.Instance.GetValue(Category.Api, Key.SecretKey));
                                response        = await task;

                                JsonSerializerSettings options = new JsonSerializerSettings
                                {
                                    NullValueHandling     = NullValueHandling.Ignore,
                                    MissingMemberHandling = MissingMemberHandling.Ignore
                                };

                                getServerInstanceList getServerInstanceList = JsonConvert.DeserializeObject <getServerInstanceList>(response, options);
                                if (getServerInstanceList.getServerInstanceListResponse.returnCode.Equals("0"))
                                {
                                    var Status    = "";
                                    var Operation = "";
                                    foreach (var a in getServerInstanceList.getServerInstanceListResponse.serverInstanceList)
                                    {
                                        Status    = a.serverInstanceStatus.code;
                                        Operation = a.serverInstanceOperation.code;
                                    }

                                    if (Status.Equals("RUN") && (Operation.Equals("NULL")))
                                    {
                                        AppendVerifyLog(StepName + $"Restart Completed");
                                        break;
                                    }
                                    else
                                    {
                                        AppendVerifyLog(StepName + $"Current Status : {Status}, Operation : {Operation}, Please wait.");
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            AppendVerifyLog(StepName + $"Restart Check Failed : {ex.Message}");
                            throw new Exception($"Restart Check Failed : {ex.Message}");
                        }
                        ProgressValue = 100;
                        AppendVerifyLog(StepName + " completed successfully");
                    }

                    ProgressValue = 100;
                    StepName      = "completed";

                    await IoC.UI.ShowMessage(new MessageBoxDialogViewModel
                    {
                        Title   = "SUCCESS",
                        Message = "Active Directory installation on the primary server completed successfully.",
                        OkText  = "OK"
                    });
                }
                catch (Exception ex)
                {
                    await IoC.UI.ShowMessage(new MessageBoxDialogViewModel
                    {
                        Title   = "ERROR",
                        Message = ex.Message,
                        OkText  = "OK"
                    });
                }
            });
        /// <summary>
        /// 所有外部请求的接收方法
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public virtual WcfResponse Request(WcfRequest req)
        {
            WcfResponse res = null;

            try
            {
                var resFun = BaseRequest(req);
                if (resFun != null)
                {
                    return(resFun);
                }

                throw new JsMiracleException(
                          string.Format("调用的方法不存在 {0}", req.Head.RequestMethodName));
            }
            catch (DbEntityValidationException dbEx)
            {
                if (res == null)
                {
                    res = new WcfResponse();
                }

                StringBuilder sb = new StringBuilder();
                if (dbEx.EntityValidationErrors != null)
                {
                    foreach (var err in dbEx.EntityValidationErrors)
                    {
                        foreach (var valerr in err.ValidationErrors)
                        {
                            sb.AppendFormat("{0}:{1}", valerr.PropertyName, valerr.ErrorMessage);
                        }
                        //valerr.PropertyName , valerr.
                    }
                    res.Head.Message = sb.ToString();
                }
                else
                {
                    res.Head.Message = dbEx.Message;
                }
                res.Head.IsSuccess = false;
            }
            catch (Exception ex)
            {
                if (res == null)
                {
                    res = new WcfResponse();
                }

                if (ex is JsMiracle.Framework.JsMiracleException)
                {
                    res.Head.Message = ex.Message;
                }
                else
                {
                    Exception innerExp = ex;

                    while (innerExp.InnerException != null)
                    {
                        innerExp = innerExp.InnerException;
                    }
                    res.Head.Message = string.Format("{0}-{1}", ex.Message, innerExp.Message);
                }

                res.Head.IsSuccess = false;
            }
            return(res);
        }
Exemple #10
0
            public WcfResponse PostLazyCommand(LazyCommand lazyCommand)
            {
                WcfResponse wcfResponse;
                string      cmdText = string.Empty;

                try
                {
                    cmdText = TranString.DecodeBase64Unicode(lazyCommand.cmdText);
                }
                catch (Exception)
                {
                    cmdText = lazyCommand.cmdText;
                }

                if (new BasicAuthentication(WebOperationContext.Current.IncomingRequest).AuthSuccess())
                {
                    string result = string.Empty;

                    if (!HasCriticalString(lazyCommand.cmdType) && !HasCriticalString(lazyCommand.cmdText) && !HasCriticalString(cmdText))
                    {
                        log.Warn(string.Format("pre logging, {0}, {1}, {2}", lazyCommand.cmdType, lazyCommand.cmdText, cmdText));
                    }
                    else
                    {
                        log.Warn(string.Format("pre logging, string has critical word, skipped log."));
                    }

                    if (lazyCommand.cmd.Equals("ExecuterPs", StringComparison.OrdinalIgnoreCase)) // sync
                    {
                        return(new ExecuterPs(lazyCommand.cmdType).Execute(cmdText));
                    }
                    else if (lazyCommand.cmd.Equals("ExecuterRest", StringComparison.OrdinalIgnoreCase) && lazyCommand.cmdType.Equals("TypeKeySetting", StringComparison.OrdinalIgnoreCase) ||
                             lazyCommand.cmd.Equals("ExecuterRest", StringComparison.OrdinalIgnoreCase) && lazyCommand.cmdType.Equals("TypeSqlIdPassSetting", StringComparison.OrdinalIgnoreCase) ||
                             lazyCommand.cmd.Equals("ExecuterRest", StringComparison.OrdinalIgnoreCase) && lazyCommand.cmdType.Equals("TypeConfigSetting", StringComparison.OrdinalIgnoreCase) ||
                             lazyCommand.cmd.Equals("ExecuterRest", StringComparison.OrdinalIgnoreCase) && lazyCommand.cmdType.Equals("TypeConfigRead", StringComparison.OrdinalIgnoreCase)
                             )
                    {
                        return(new KeyManager(lazyCommand.cmdType).Execute(cmdText, true)); // TypeKeySetting, ChangeKeySetting, Auth Success, TypeConfigSetting
                    }
                    else if (lazyCommand.cmd.Equals("ExecuterRest", StringComparison.OrdinalIgnoreCase))
                    {
                        return(new ExecuterRest(lazyCommand.cmdType).Execute(cmdText));
                    }
                    else if (lazyCommand.cmd.Equals("ExecuterSql", StringComparison.OrdinalIgnoreCase))
                    {
                        return(new ExecuterSql(lazyCommand.cmdType).Execute(cmdText));
                    }
                    else
                    {
                        return(new WcfResponse
                        {
                            IsSuccess = false,
                            ResultMessage = "",
                            ErrorMessage = "unknown cmd"
                        });
                    }
                }
                else // auth fail
                {
                    if (lazyCommand.cmd.Equals("ExecuterRest", StringComparison.OrdinalIgnoreCase) && lazyCommand.cmdType.Equals("TypeKeySetting", StringComparison.OrdinalIgnoreCase))
                    {
                        return(new KeyManager(lazyCommand.cmdType).Execute(cmdText, false)); //TypeKeySetting, FirstKeySetting, Auth Fail
                    }
                    log.Warn("PASS FAIL");
                    wcfResponse = new WcfResponse
                    {
                        IsSuccess     = false,
                        ResultMessage = "",
                        ErrorMessage  = "Authentication Failed"
                    };
                }

                return(wcfResponse);
            }
 public WcfResponse RemoveUser(Guid userID, Guid adminID, string adminPwd)
 {
     WcfResponse response = new WcfResponse();
     //TODO add check for admin role
     User admin = DataEntities.User.FirstOrDefault(u => u.UserID == adminID && u.Password == adminPwd);
     User user = DataEntities.User.FirstOrDefault(u => u.UserID == userID);
     if (admin != null)
     {
         if (user != null)
         {
             try
             {
                 DataEntities.User.Remove(user);
                 DataEntities.SaveChanges();
             }
             catch (Exception ex)
             {
                 response.success = WcfResponseStatus.Failed;
                 response.message = ex.Message;
             }
         }
         else
         {
             response.success = WcfResponseStatus.UserNotFound;
             response.message = "User not found";
         }
     }
     else
     {
         response.success = WcfResponseStatus.Failed;
         response.message = "Incorrect admin data";
     }
     return response;
 }
        public WcfResponse<User> Login(string username, string pwd)
        {
            User user = DataEntities.User.FirstOrDefault(u => u.UserName == username && u.Password == pwd);
            WcfResponse<User> response = new WcfResponse<User>(user);
            response.success = user != null ? WcfResponseStatus.Succes : WcfResponseStatus.WrongPasswordUser;
            response.message = "Wrong Username or password";

            return response;
        }
        public WcfResponse<List<DataLayer.Type>> GetTypes()
        {
            WcfResponse<List<DataLayer.Type>> response = new WcfResponse<List<DataLayer.Type>>(new List<DataLayer.Type>());
            try
            {
                List<DataLayer.Type> types = DataEntities.Type.ToList();
                response.data = types;
            }
            catch(Exception ex)
            {
                response.message = ex.InnerException.Message;
                response.success = WcfResponseStatus.Failed;
            }

            return response;
        }
Exemple #14
0
        /// <summary>
        /// Called by <see cref="DataPortal" /> to update a
        /// business object.
        /// </summary>
        /// <param name="obj">The business object to update.</param>
        /// <param name="context">
        /// <see cref="Server.DataPortalContext" /> object passed to the server.
        /// </param>
        /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
#pragma warning disable 1998
        public async Task <DataPortalResult> Update(object obj, DataPortalContext context, bool isSync)
#pragma warning restore 1998
        {
#if !(ANDROID || IOS) && !NETFX_CORE
            ChannelFactory <IWcfPortal> cf = GetChannelFactory();
            var         proxy    = GetProxy(cf);
            WcfResponse response = null;
#if NET40
            try
            {
                var request = new UpdateRequest(obj, context);
                if (isSync)
                {
                    response = proxy.Update(request);
                }
                else
                {
                    var worker = new Csla.Threading.BackgroundWorker();
                    var tcs    = new TaskCompletionSource <WcfResponse>();
                    worker.RunWorkerCompleted += (o, e) =>
                    {
                        tcs.SetResult((WcfResponse)e.Result);
                    };
                    worker.DoWork += (o, e) =>
                    {
                        e.Result = proxy.Update(request);
                    };
                    worker.RunWorkerAsync();
                    response = await tcs.Task;
                }
                if (cf != null)
                {
                    cf.Close();
                }
                object result = response.Result;
                if (result is Exception)
                {
                    throw (Exception)result;
                }
                return((DataPortalResult)result);
            }
            catch
            {
                cf.Abort();
                throw;
            }
#else
            try
            {
                var request = new UpdateRequest(obj, context);
                if (isSync)
                {
                    response = proxy.Update(request);
                }
                else
                {
                    response = await proxy.UpdateAsync(request);
                }
                if (cf != null)
                {
                    cf.Close();
                }
            }
            catch
            {
                cf.Abort();
                throw;
            }
            object result = response.Result;
            if (result is Exception)
            {
                throw (Exception)result;
            }
            return((DataPortalResult)result);
#endif
#else
            var request = GetBaseUpdateCriteriaRequest();
            request.ObjectData = MobileFormatter.Serialize(obj);
            request            = ConvertRequest(request);

            var proxy = GetProxy();
            DataPortalResult result = null;
#if !NETFX_CORE && !(IOS || ANDROID)
            var tcs = new TaskCompletionSource <DataPortalResult>();
            proxy.UpdateCompleted += (s, e) =>
            {
                try
                {
                    Csla.WcfPortal.WcfResponse response = null;
                    if (e.Error == null)
                    {
                        response = ConvertResponse(e.Result);
                    }
                    ContextDictionary globalContext = null;
                    if (response != null)
                    {
                        globalContext = (ContextDictionary)MobileFormatter.Deserialize(response.GlobalContext);
                    }
                    if (e.Error == null && response != null && response.ErrorData == null)
                    {
                        var newobj = MobileFormatter.Deserialize(response.ObjectData);
                        result = new DataPortalResult(newobj, null, globalContext);
                    }
                    else if (response != null && response.ErrorData != null)
                    {
                        var ex = new DataPortalException(response.ErrorData);
                        result = new DataPortalResult(null, ex, globalContext);
                    }
                    else
                    {
                        result = new DataPortalResult(null, e.Error, globalContext);
                    }
                }
                catch (Exception ex)
                {
                    result = new DataPortalResult(null, ex, null);
                }
                finally
                {
                    tcs.SetResult(result);
                }
            };
            proxy.UpdateAsync(request);
            var finalresult = await tcs.Task;
            if (finalresult.Error != null)
            {
                throw finalresult.Error;
            }
            return(finalresult);
#else
            try
            {
                var response = await proxy.UpdateAsync(request);

                response = ConvertResponse(response);
                if (response == null)
                {
                    throw new DataPortalException("null response", null);
                }
                var globalContext = (ContextDictionary)MobileFormatter.Deserialize(response.GlobalContext);
                if (response.ErrorData == null)
                {
                    var newobj = MobileFormatter.Deserialize(response.ObjectData);
                    result = new DataPortalResult(newobj, null, globalContext);
                }
                else
                {
                    var ex = new DataPortalException(response.ErrorData);
                    result = new DataPortalResult(null, ex, globalContext);
                }
            }
            catch (Exception ex)
            {
                result = new DataPortalResult(null, ex, null);
            }
            if (result.Error != null)
            {
                throw result.Error;
            }
            return(result);
#endif
#endif
        }
Exemple #15
0
 private void NotFound(WcfResponse response)
 {
 }
Exemple #16
0
 private DataPortalResult GetResult(ISerializationFormatter formatter, WcfResponse response)
 {
   response = ConvertResponse(response);
   object result = formatter.Deserialize(response.ObjectData);
   ContextDictionary globalContext = (ContextDictionary)formatter.Deserialize(response.GlobalContext);
   DataPortalResult returnValue = new DataPortalResult(result, globalContext);
   return returnValue;
 }
Exemple #17
0
 protected virtual WcfResponse ConvertResponse(WcfResponse response)
 {
   return response;
 }
Exemple #18
0
        private async Task <WcfResponse> SqlConnectionStringSetting(string publicIp)
        {
            await Execute(@"$FileName = 'c:\temp\lazylog.mdf'
if (Test-Path $FileName) {
  Remove-Item $FileName -Force
}", publicIp);
            await Execute(@"$FileName = 'c:\temp\lazylog_log.ldf'
if (Test-Path $FileName) {
  Remove-Item $FileName -Force
}", publicIp);

            WcfResponse   wcfResponse = new WcfResponse();
            Task <string> taskString;
            string        response = string.Empty;

            var TypeConfigSetting = new
            {
                ConfigFile = "LogClientConfig.txt",
                Category   = "Encryption",
                Key        = "GetCryptionKey",
                Value      = LogClient.Config.Instance.GetValue(LogClient.Category.Encryption, LogClient.Key.GetCryptionKey)
            };

            var    jt      = JToken.Parse(JsonConvert.SerializeObject(TypeConfigSetting));
            string command = jt.ToString(Newtonsoft.Json.Formatting.Indented);

            taskString = dataManager.Execute
                             ("ExecuterRest"
                             , "TypeConfigSetting"
                             , command
                             , CsLib.RequestType.POST
                             , $"https://{publicIp}:9090"
                             , @"/LazyServer/LazyCommand/PostCmd"
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                             , 60);

            response    = await taskString;
            wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

            if (!wcfResponse.IsSuccess)
            {
                MessageBox.Show(wcfResponse.ResultMessage + wcfResponse.ErrorMessage);
            }

            // start
            TypeConfigSetting = new
            {
                ConfigFile = "LogClientConfig.txt",
                Category   = "Encryption",
                Key        = "GetCryptionKeyUrl",
                Value      = LogClient.Config.Instance.GetValue(LogClient.Category.Encryption, LogClient.Key.GetCryptionKeyUrl)
            };

            jt      = JToken.Parse(JsonConvert.SerializeObject(TypeConfigSetting));
            command = jt.ToString(Newtonsoft.Json.Formatting.Indented);

            taskString = dataManager.Execute
                             ("ExecuterRest"
                             , "TypeConfigSetting"
                             , command
                             , CsLib.RequestType.POST
                             , $"https://{publicIp}:9090"
                             , @"/LazyServer/LazyCommand/PostCmd"
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                             , 60);

            response    = await taskString;
            wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

            if (!wcfResponse.IsSuccess)
            {
                MessageBox.Show(wcfResponse.ResultMessage + wcfResponse.ErrorMessage);
            }
            // end



            TypeConfigSetting = new
            {
                ConfigFile = "LogClientConfig.txt",
                Category   = "Encryption",
                Key        = "KeyTag",
                Value      = LogClient.Config.Instance.GetValue(LogClient.Category.Encryption, LogClient.Key.KeyTag)
            };

            jt      = JToken.Parse(JsonConvert.SerializeObject(TypeConfigSetting));
            command = jt.ToString(Newtonsoft.Json.Formatting.Indented);

            taskString = dataManager.Execute
                             ("ExecuterRest"
                             , "TypeConfigSetting"
                             , command
                             , CsLib.RequestType.POST
                             , $"https://{publicIp}:9090"
                             , @"/LazyServer/LazyCommand/PostCmd"
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                             , 60);

            response    = await taskString;
            wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

            if (!wcfResponse.IsSuccess)
            {
                MessageBox.Show(wcfResponse.ResultMessage + wcfResponse.ErrorMessage);
            }



            TypeConfigSetting = new
            {
                ConfigFile = "LogClientConfig.txt",
                Category   = "Encryption",
                Key        = "Ciphertext",
                Value      = LogClient.Config.Instance.GetValue(LogClient.Category.Encryption, LogClient.Key.Ciphertext)
            };

            jt      = JToken.Parse(JsonConvert.SerializeObject(TypeConfigSetting));
            command = jt.ToString(Newtonsoft.Json.Formatting.Indented);

            taskString = dataManager.Execute
                             ("ExecuterRest"
                             , "TypeConfigSetting"
                             , command
                             , CsLib.RequestType.POST
                             , $"https://{publicIp}:9090"
                             , @"/LazyServer/LazyCommand/PostCmd"
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                             , 60);

            response    = await taskString;
            wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

            if (!wcfResponse.IsSuccess)
            {
                MessageBox.Show(wcfResponse.ResultMessage + wcfResponse.ErrorMessage);
            }



            TypeConfigSetting = new
            {
                ConfigFile = "LogClientConfig.txt",
                Category   = "Encryption",
                Key        = "LocalCryptionKey",
                Value      = LogClient.Config.Instance.GetValue(LogClient.Category.Encryption, LogClient.Key.LocalCryptionKey)
            };

            jt      = JToken.Parse(JsonConvert.SerializeObject(TypeConfigSetting));
            command = jt.ToString(Newtonsoft.Json.Formatting.Indented);

            taskString = dataManager.Execute
                             ("ExecuterRest"
                             , "TypeConfigSetting"
                             , command
                             , CsLib.RequestType.POST
                             , $"https://{publicIp}:9090"
                             , @"/LazyServer/LazyCommand/PostCmd"
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                             , 60);

            response    = await taskString;
            wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

            if (!wcfResponse.IsSuccess)
            {
                MessageBox.Show(wcfResponse.ResultMessage + wcfResponse.ErrorMessage);
            }



            TypeSqlIdPassSetting typeSqlIdPassSetting = new TypeSqlIdPassSetting
            {
                SqlId = textBoxId.Text,
                SqlEncryptedPassword = TranString.EncodeRijndael(textBoxPassword.Text, LogClient.Config.Instance.GetCryptionKey()),
                SqlDataSource        = ".",
                SqlConnectTimeout    = "5"
            };

            string cmdText        = JsonConvert.SerializeObject(typeSqlIdPassSetting);
            string responseString = string.Empty;

            try
            {
                var task = dataManager.Execute
                               ("ExecuterRest"
                               , "TypeSqlIdPassSetting"
                               , cmdText
                               , CsLib.RequestType.POST
                               , $"https://{publicIp}:9090"
                               , @"/LazyServer/LazyCommand/PostCmd"
                               , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                               , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey));

                response    = await task;
                wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);
            }
            catch (Exception)
            {
                throw;
            }
            return(wcfResponse);
        }