Exemplo n.º 1
0
        protected void gvDomains_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "DeleteItem")
            {
                // delete domain
                int domainId = Utils.ParseInt(e.CommandArgument.ToString(), 0);

                // domain name
                DomainInfo domain     = ES.Services.Servers.GetDomain(domainId);
                var        DomainName = domain.DomainName;

                try
                {
                    int result = ES.Services.Organizations.DeleteOrganizationDomain(PanelRequest.ItemID, domainId);
                    if (result < 0)
                    {
                        Response.Redirect(EditUrl("ItemID", PanelRequest.ItemID.ToString(), "check_domain",
                                                  "SpaceID=" + PanelSecurity.PackageId, "DomainID=" + domainId));
                        return;
                    }
                    //Delete Domain to Mail Cleaner
                    Knom.Helpers.Net.APIMailCleanerHelper.DomainRemove(DomainName);

                    // rebind domains
                    BindDomainNames();

                    BindStats();
                }
                catch (Exception ex)
                {
                    ShowErrorMessage("EXCHANGE_DELETE_DOMAIN", ex);
                }
            }
            else if (e.CommandName == "Change")
            {
                string[] commandArgument = e.CommandArgument.ToString().Split('|');
                int      domainId        = Utils.ParseInt(commandArgument[0].ToString(), 0);
                ExchangeAcceptedDomainType acceptedDomainType = (ExchangeAcceptedDomainType)Enum.Parse(typeof(ExchangeAcceptedDomainType), commandArgument[1]);


                try
                {
                    ExchangeAcceptedDomainType newDomainType = ExchangeAcceptedDomainType.Authoritative;
                    if (acceptedDomainType == ExchangeAcceptedDomainType.Authoritative)
                    {
                        newDomainType = ExchangeAcceptedDomainType.InternalRelay;
                    }

                    int result = ES.Services.Organizations.ChangeOrganizationDomainType(PanelRequest.ItemID, domainId, newDomainType);
                    if (result < 0)
                    {
                        messageBox.ShowResultMessage(result);
                        return;
                    }

                    // rebind domains
                    BindDomainNames();

                    BindStats();
                }
                catch (Exception ex)
                {
                    ShowErrorMessage("EXCHANGE_CHANGE_DOMAIN", ex);
                }
            }
            if (e.CommandName == "ViewUsage")
            {
                int domainId = Utils.ParseInt(e.CommandArgument.ToString(), 0);
                Response.Redirect(EditUrl("ItemID", PanelRequest.ItemID.ToString(), "check_domain",
                                          "SpaceID=" + PanelSecurity.PackageId, "DomainID=" + domainId));
                return;
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Save document information
        /// </summary>
        /// <param name="Doc"></param>
        /// <param name="filePath"></param>
        /// <param name="isReconstruct"></param>
        private PdwInfo Save(Document Doc, string filePath, bool isReconstruct = false, bool isToFinal = true)
        {
            try
            {
                TemplateInfo tempInfo = Wkl.MainCtrl.CommonCtrl.GetTemplateInfo(Doc.FullName);
                if (tempInfo == null)
                {
                    return(null);
                }

                PdwInfo pdwInfo = null;
                tempInfo.IsSaving = true; // markup the document is saving

                if (!string.IsNullOrEmpty(filePath))
                {
                    // put where clause into internal bookmark
                    foreach (string domainName in tempInfo.DomainNames)
                    {
                        DomainInfo             domainInfo = Wkl.MainCtrl.CommonCtrl.GetDomainInfo(domainName);
                        InternalBookmarkDomain ibmDomain  = tempInfo.InternalBookmark.GetInternalBookmarkDomain(domainName);
                        if (ibmDomain != null)
                        {
                            ibmDomain.WhereClause = domainInfo.DSDomainData.WhereClause.Clause;
                        }
                    }

                    // save pdwinfo (checksum, oslq, xslt)
                    pdwInfo = SavePdwInfo(filePath, Doc, isReconstruct);

                    // save internal bookmark
                    mainManager.MainService.PropertyService.SaveInterBookmark();

                    // save the document
                    if (isToFinal)
                    {
                        TemplateType type = MarkupUtilities.GetTemplateType(filePath);

                        if (type == TemplateType.Pdm)
                        {
                            mainManager.MainService.PdmService.Save();
                        }
                        else
                        {
                            // Doc.SaveAs(filePath);
                            Doc.Save();
                        }
                    }

                    tempInfo = Wkl.MainCtrl.CommonCtrl.GetTemplateInfo(Doc.FullName);
                    if (tempInfo != null)
                    {
                        tempInfo.IsProntoDoc = true; // markup the document is pronto doc

                        // set autosave option
                        if (!isReconstruct && Wkl.MainCtrl.CommonCtrl.CommonProfile.App.Options.SaveInterval != ProntoMarkup.SaveInterval)
                        {
                            Wkl.MainCtrl.CommonCtrl.CommonProfile.App.Options.SaveInterval = ProntoMarkup.SaveInterval;
                        }

                        if (isToFinal)
                        {
                            UpdateStatus(MessageUtils.Expand(Properties.Resources.ipm_SaveSuccessful, filePath)); // update status
                        }
                    }
                }

                if (tempInfo != null)
                {
                    tempInfo.IsSaving = false; // markup the document is saved
                }
                return(pdwInfo);
            }
            catch (BaseException baseExp)
            {
                ManagerException mgrExp = new ManagerException(ErrorCode.ipe_SaveDocumentError);
                mgrExp.Errors.Add(baseExp);

                throw mgrExp;
            }
            catch (Exception ex)
            {
                ManagerException mgrExp = new ManagerException(ErrorCode.ipe_SaveDocumentError,
                                                               MessageUtils.Expand(Properties.Resources.ipe_SaveDocumentError, ex.Message), ex.StackTrace);

                throw mgrExp;
            }
        }
Exemplo n.º 3
0
        private static void LoadConfig()
        {
            lock (SyncObject)
            {
                Printer.PrintMessage("Loading config...");
                var configInfo = new System.IO.FileInfo(ConfigFile);
                if (!configInfo.Exists)
                {
                    Printer.PrintError("#x#Error:##\n  Can't find config file #b#{0}##! Using default.", ConfigFile);
                }
                else
                {
                    using (var fs = configInfo.OpenText())
                    {
                        Config = Newtonsoft.Json.JsonConvert.DeserializeObject<ServerConfig>(fs.ReadToEnd());
                    }
                    if (!string.IsNullOrEmpty(Config.AutoDomains))
                    {
                        string path = System.IO.Path.GetFullPath(Config.AutoDomains);
                        var vaultdir = new System.IO.DirectoryInfo(path);
                        if (!vaultdir.Exists)
                            Printer.PrintError("#x#Error:##\n  Can't find auto-domain location: {0}.", path);
                        else
                        {
                            foreach (var x in vaultdir.GetDirectories())
                            {
                                Config.Domains.Add(x.Name, x.FullName);
                            }
                        }
                    }
                    List<string> deletedDomains = new List<string>();
                    foreach (var z in Domains)
                    {
                        if (z.Key != string.Empty && !Config.Domains.ContainsKey(z.Key))
                            deletedDomains.Add(z.Key);
                    }
                    foreach (var z in deletedDomains)
                        Domains.Remove(z);
                    foreach (var x in Config.Domains)
                    {
                        System.IO.DirectoryInfo domInfo = new System.IO.DirectoryInfo(x.Value);
                        if (domInfo.Exists)
                        {
                            Area dm = null;
                            try
                            {
                                dm = Area.Load(domInfo, true, true);
                            }
                            catch
                            {
                                dm = null;
                            }
                            Printer.PrintMessage("Module: {0} => ./{1} {2}", x.Key, domInfo, dm == null ? "bare" : dm.Domain.ToString());

                            DomainInfo info = new DomainInfo() { Bare = dm == null, Directory = domInfo };
                            Domains[x.Key] = info;
                            if (dm != null)
                                dm.Dispose();
                        }
                        else
                            Printer.PrintError("#x#Error:##\n  Can't find domain location {0}!", x.Value);
                    }
                    if ((Config.IncludeRoot.HasValue && Config.IncludeRoot.Value) || (!Config.IncludeRoot.HasValue && Domains.Count != 0))
                    {
                        using (Area a = Area.Load(BaseDirectory))
                        {
                            Domains[string.Empty] = new DomainInfo() { Bare = a == null, Directory = BaseDirectory };
                            Printer.PrintMessage("Root Module {1} {2}", BaseDirectory, a == null ? "bare" : a.Domain.ToString());
                        }
                    }
                    else if (Config.IncludeRoot.HasValue && Config.IncludeRoot.Value == false)
                        Domains.Remove(string.Empty);

                    if (Config.RequiresAuthentication)
                        Printer.PrintMessage("Configured to use authentication. Unauthenticated read {0}.", (Config.AllowUnauthenticatedRead ? "allowed" : "disabled"));
                }
            }
        }
Exemplo n.º 4
0
 private async void Domain_RowRemoved(object sender, DomainRowEventArgs e)
 {
     this.domainInfo  = this.domain.DomainInfo;
     this.domainState = this.domain.DomainState;
     await this.RefreshAsync();
 }
Exemplo n.º 5
0
 private async void Domain_DomainInfoChanged(object sender, EventArgs e)
 {
     this.domainInfo = this.domain.DomainInfo;
     await this.RefreshAsync();
 }
Exemplo n.º 6
0
 void IDomainServiceCallback.OnDomainInfoChanged(SignatureDate signatureDate, Guid domainID, DomainInfo domainInfo)
 {
     this.InvokeAsync(() =>
     {
         var domain         = this.Domains[domainID];
         var authentication = this.userContext.Authenticate(signatureDate);
         domain.InvokeDomainInfoChanged(authentication, domainInfo);
     }, nameof(IDomainServiceCallback.OnDomainInfoChanged));
 }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            //////////////////////////
            // Fill in your details //
            //////////////////////////
            string username = "******";
            string password = "******";
            string domain   = "google.com";

            /////////////////////////
            // Use a JSON resource //
            /////////////////////////
            string format = "JSON";
            string url    = "http://www.whoisxmlapi.com/whoisserver/WhoisService?cmd=GET_DN_AVAILABILITY" + "&domainName=" + domain + "&username="******"&password="******"&outputFormat=" + format;

            // Create our JSON parser
            JavaScriptSerializer jsc = new JavaScriptSerializer();

            jsc.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });

            // Download and parse the JSON into a dynamic object
            dynamic result = jsc.Deserialize(new System.Net.WebClient().DownloadString(url), typeof(object)) as dynamic;

            // Print a nice informative string
            try
            {
                Console.WriteLine("JSON:\n");
                result.PrintPairs();
            }
            catch (Exception e)
            {
                try
                {
                    Console.WriteLine("JSON:\nErrorMessage:\n\t{0}", result.ErrorMessage.msg);
                }
                catch (Exception e2)
                {
                    Console.WriteLine("An unkown error has occurred!");
                }
            }

            /////////////////////////
            // Use an XML resource //
            /////////////////////////
            format = "XML";
            url    = "http://www.whoisxmlapi.com/whoisserver/WhoisService?cmd=GET_DN_AVAILABILITY" + "&domainName=" + domain + "&username="******"&password="******"&outputFormat=" + format;

            var        settings = new XmlReaderSettings();
            var        reader   = XmlReader.Create(url, settings);
            DomainInfo record   = new DomainInfo();

            try
            {
                var serializer = new System.Xml.Serialization.XmlSerializer(typeof(DomainInfo));
                record = (DomainInfo)serializer.Deserialize(reader);

                reader.Close();

                // Print a nice informative string
                Console.WriteLine("XML:\n");
                record.PrintToConsole();
            }
            catch (Exception e)
            {
                try
                {
                    var          serializer   = new System.Xml.Serialization.XmlSerializer(typeof(ErrorMessage));
                    ErrorMessage errorMessage = (ErrorMessage)serializer.Deserialize(reader);

                    reader.Close();

                    // Print a nice informative string
                    Console.WriteLine("XML:\nErrorMessage:\n\t{0}", errorMessage.msg);
                }
                catch (Exception e2)
                {
                    Console.WriteLine("XML:\nException: {0}", e2.Message);
                }
            }

            // Prevent command window from automatically closing during debugging
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Exemplo n.º 8
0
        private void AnalyzeTestMethods(DomainInfo domainInfo)
        {
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            domainInfo.TestClasses = new Dictionary <Type, TestInfo>();
            foreach (Assembly assembly in assemblies)
            {
                string assemblyName   = assembly.GetName().Name;
                bool   isTestAssembly = false;
                foreach (AssemblyInfo testAssembly in domainInfo.Assemblies)
                {
                    string testAssemblyName = testAssembly.AssemblyName;
                    if (assemblyName.Equals(testAssemblyName))
                    {
                        isTestAssembly = true;
                        break;
                    }
                }

                if (!isTestAssembly)
                {
                    continue;
                }

                Type[] types = assembly.GetTypes();

                foreach (Type type in types)
                {
                    Attribute attribute = type.GetCustomAttribute(typeof(TestClass));
                    if (attribute == null)
                    {
                        continue;
                    }

                    TestInfo testInfo = new TestInfo()
                    {
                        AssemblyName = type.Assembly.FullName,
                        ClassName    = type.Name
                    };

                    List <MethodInfo> testMethods = new List <MethodInfo>();

                    BindingFlags flags = BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.ExactBinding;

                    MethodInfo[] methods = type.GetMethods(flags);
                    foreach (MethodInfo method in methods)
                    {
                        attribute = method.GetCustomAttribute(typeof(InitMethod));
                        if (attribute != null)
                        {
                            testInfo.InitMethod = method;
                            continue;
                        }

                        attribute = method.GetCustomAttribute(typeof(TestMethod));
                        if (attribute != null)
                        {
                            testMethods.Add(method);
                        }
                    }

                    testInfo.TestMethods = testMethods;
                    domainInfo.TestClasses.Add(type, testInfo);
                }
            }
        }
Exemplo n.º 9
0
        private void AddDomain(SwaggerDocument swaggerDoc, DocumentFilterContext context, DomainInfo domain)
        {
            foreach (var command in domain.Commands)
            {
                this.AddCommand(swaggerDoc, context, domain, command);
            }

            foreach (var query in domain.Queries)
            {
                this.AddQuery(swaggerDoc, context, domain, query);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// check internal bookmark is match with domain data in datasegment or no
        /// = 0: match (that mean same where clause and all field (biz name and unique name))
        /// > 0: number of field in internal not match with datasegment
        /// &lt; 0: where clause is not match
        /// </summary>
        /// <param name="ibmDomain"></param>
        /// <param name="domainName"></param>
        /// <returns>
        /// </returns>
        private DomainMatchItem IsMatchWithDataSegment(InternalBookmarkDomain ibmDomain, string domainName)
        {
            DataSegmentHelper.LoadDomainData(domainName);
            DomainMatchItem matchResult = new DomainMatchItem(domainName);

            matchResult.IsMatchWhereClause = true;
            DomainInfo domainInfo = Wkl.MainCtrl.CommonCtrl.GetDomainInfo(domainName);

            if (domainInfo == null || domainInfo.DSDomainData == null)
            {
                return(null);
            }

            #region 1. Compare fields
            #region 1.2. get internal bookmark item collection from internal bookmark object
            List <InternalBookmarkItem> iItems = GetInternalBookmarkItemCollection(ibmDomain);
            #endregion

            #region 1.3. compare datasegment's field collection with internal bookmark's field collection
            foreach (InternalBookmarkItem item in iItems)
            {
                if (IsMatchWithDataSegment(item, domainInfo.Fields))
                {
                    matchResult.MatchedFields.Add(item.BizName);
                }
                else
                {
                    matchResult.NotMatchFields.Add(item.BizName);
                    if (item.Type == XsltType.Select)
                    {
                        matchResult.SetSingleBiz(item.Key);
                    }
                    else
                    {
                        matchResult.SetDoubleBiz(item.Key);
                    }
                }
            }
            #endregion

            if (!matchResult.IsMatch)
            {
                return(matchResult);
            }
            #endregion

            #region 2. Compare RelationOn
            foreach (RelationOn relationOn in ibmDomain.RelationOns)
            {
                DSOnClause item = domainInfo.DSDomainData.OnClauses.Items.FirstOrDefault(c =>
                                                                                         string.Equals(relationOn.UniqueName, c.UniqueName) &&
                                                                                         string.Equals(relationOn.OnClause, c.ExClause));
                if (item == null)
                {
                    matchResult.IsMatchRelationOn = false;
                    return(matchResult);
                }
            }
            #endregion

            #region 3. compare where clause
            if (ibmDomain.WhereClause != domainInfo.DSDomainData.WhereClause.Clause)
            {
                matchResult.IsMatchWhereClause = false;
            }
            #endregion
            return(matchResult);
        }
Exemplo n.º 11
0
 public List <ClassTestResult> Run(DomainInfo domainInfo)
 {
     AnalyzeTestMethods(domainInfo);
     return(Execute(domainInfo));
 }
Exemplo n.º 12
0
    private void OnGUI()
    {
        if (_gameSettingData == null)
        {
            GetGameSettingData();
        }

        _scrollPos = EditorGUILayout.BeginScrollView(_scrollPos);
        {
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("ProductName : " + PlayerSettings.productName);
            EditorGUILayout.LabelField("Bundle Identifier : " + PlayerSettings.applicationIdentifier);
            EditorGUILayout.LabelField("Bundle Version : " + PlayerSettings.bundleVersion);
            EditorGUILayout.LabelField("Bundle Version Code: " + PlayerSettings.Android.bundleVersionCode);
            EditorGUILayout.LabelField("HttpRoot: " + _gameSettingData.httpRoot);
            EditorGUILayout.LabelField("BuildToFile: " + _buildToFileName);
            EditorGUILayout.LabelField("projmods: " + _buildProjmods);
            EditorGUILayout.Space();

            //GameType选项
            int selectGameTypeIndex = EditorGUILayout.IntPopup("GameType :", _lastSelectGameTypeIndex,
                                                               _gameTypeValues, _gameTypeKeys);

            if (_lastSelectGameTypeIndex != selectGameTypeIndex)
            {
                _lastSelectGameTypeIndex  = selectGameTypeIndex;
                _gameSettingData.gameType = _gameTypeValues[_lastSelectGameTypeIndex];
                GameInfo gameInfo = _gameInfoDic[_gameSettingData.gameType];
                _gameSettingData.gamename     = gameInfo.gamename;
                _gameSettingData.configSuffix = gameInfo.configSuffix;

                LoadSPChannelConfig(_gameSettingData.configSuffix, true);
            }

            if (_gameInfoDic.ContainsKey(_gameSettingData.gameType) == false)
            {
                EditorGUILayout.LabelField(string.Format("GameType {0} no support!!!", _gameSettingData.gameType));
                EditorGUILayout.EndScrollView();
                return;
            }

            //Domain类型选项
            UpdateDomainList(_gameSettingData.gameType, _gameSettingData.domainType);
            _lastSelectDomainIndex = EditorGUILayout.IntPopup("DomainType : ", _lastSelectDomainIndex,
                                                              _domainValues, _domainKeys);

            _gameSettingData.domainType = GetDomianType(_gameSettingData.gameType, _lastSelectDomainIndex);

            DomainInfo domainInfo = GetDomainInfo(_gameSettingData.gameType, _gameSettingData.domainType);
            if (domainInfo == null)
            {
                EditorGUILayout.LabelField(string.Format("DomainType {0} no support!!!", _gameSettingData.domainType));
                EditorGUILayout.EndScrollView();
                return;
            }
            _gameSettingData.httpRoot = domainInfo.url;
            _gameSettingData.resdir   = domainInfo.resdir;

            //Platform类型选项
            _gameSettingData.platformType = (GameSetting.PlatformType)EditorGUILayout.EnumPopup("PlatformType :", _gameSettingData.platformType);

            //Channel类型选项
            UpdateSpSdkList(_gameSettingData.domainType, _gameSettingData.platformType, _gameSettingData.channel);
            if (_channelKeys != null && _channelValues != null)
            {
                _lastSelectChannelIndex = EditorGUILayout.IntPopup("Channel : ", _lastSelectChannelIndex,
                                                                   _channelValues, _channelKeys);
            }
            else
            {
                EditorGUILayout.LabelField("Channel : Load channel Info Failed!!!");
                EditorGUILayout.EndScrollView();
                return;
            }

            if (_channelValues.Length > _lastSelectChannelIndex)
            {
                _gameSettingData.channel = _channelValues[_lastSelectChannelIndex];
            }

            //资源加载配置选项
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("注意:加载模式的更改只对编辑器运行时有效,打包手机包时选择Mobile模式");
            _resLoadMode = (AssetPipeline.AssetManager.LoadMode)EditorGUILayout.EnumPopup("资源加载模式 :", _resLoadMode);

            //调试选项
            EditorGUILayout.Space();
            _gameSettingData.release        = EditorGUILayout.Toggle("Client Release : ", _gameSettingData.release);
            _gameSettingData.testServerMode = EditorGUILayout.Toggle("压测模式 : ", _gameSettingData.testServerMode);
            _gameSettingData.gmMode         = EditorGUILayout.Toggle("GM模式 : ", _gameSettingData.gmMode);
            developmentBuild = EditorGUILayout.Toggle("Development Build : ", developmentBuild);
            EditorGUILayout.Toggle("MinRes Build : ", _minResBuild);
            _enableJSB = EditorGUILayout.Toggle("Enable JSB: ", _enableJSB);
            _useJsz    = EditorGUILayout.Toggle("Use Jsz: ", _useJsz);
            _gameSettingData.logType = (GameSetting.DebugInfoType)EditorGUILayout.EnumPopup("调试信息类型 :", _gameSettingData.logType);

            EditorGUILayout.Space();
            GUI.color = Color.yellow;
            if (GUILayout.Button("保存配置", GUILayout.Height(40)))
            {
                if (!CheckIsCompiling())
                {
                    SaveComeFromConfig();
                }
            }

#if UNITY_ANDROID
            EditorGUILayout.Space();
            if (GUILayout.Button("导出Android Project", GUILayout.Height(40)))
            {
                string outPutPath = EditorUtility.OpenFolderPanel("导出Android工程目录", "", "");
                if (!string.IsNullOrEmpty(outPutPath))
                {
                    EditorHelper.Run(() => ExportAndroidProject(outPutPath), true, false);
                }
            }

            EditorGUILayout.Space();
            if (GUILayout.Button("打包当前渠道", GUILayout.Height(40)))
            {
                if (EditorUtility.DisplayDialog("打包确认", "是否确认打包当前渠道?", "确认打包", "取消"))
                {
                    EditorApplication.delayCall += () => BuildAndroid();
                }
            }

            //			EditorGUILayout.Space ();
            //			if (GUILayout.Button ("打包所有商务渠道", GUILayout.Height (40))) {
            //				if (EditorUtility.DisplayDialog ("打包确认", "是否确认打包所有渠道?", "确认打包", "取消")) {
            //
            //				}
            //			}
#endif

#if UNITY_IPHONE
            EditorGUILayout.Space();
            if (GUILayout.Button("Expor2XCODE", GUILayout.Height(40)))
            {
                if (EditorUtility.DisplayDialog("导出确认", "是否确认导出XCODE?", "确认", "取消"))
                {
                    EditorApplication.delayCall += () =>
                    {
                        string applicationPath = Application.dataPath.Replace("/Assets", "/../..");
                        string target_dir      = EditorUtility.OpenFolderPanel("导出目录", applicationPath, "xcode");
                        BuildIOS(target_dir);
                    };
                }
            }

            EditorGUILayout.Space();
            if (GUILayout.Button("ExportAllIpa", GUILayout.Height(40)))
            {
                EditorApplication.delayCall += () => BuildAllIpa();
            }
#endif

#if UNITY_STANDALONE_WIN && !UNITY_IPHONE
            EditorGUILayout.Space();
            if (GUILayout.Button("一按键打包PC", GUILayout.Height(40)))
            {
                if (EditorUtility.DisplayDialog("打包确认", "是否确认打包PC版?", "确认打包", "取消"))
                {
                    EditorApplication.delayCall += () => BuildPC();
                }
            }
#endif
            EditorGUILayout.Space();
            GUI.color = Color.green;
            if (GUILayout.Button("清除本地数据和PlayerPrefs", GUILayout.Height(40)))
            {
                EditorApplication.delayCall += () =>
                {
                    Debug.Log("清除本地数据和PlayerPrefs");
                    PlayerPrefs.DeleteAll();
                    FileUtil.DeleteFileOrDirectory(Application.persistentDataPath);
                };
            }
            GUI.color = Color.white;

            EditorGUILayout.Space();
            if (GUILayout.Button("上传Dlls", GUILayout.Height(40)))
            {
                GameResVersionManager.UploadDllsPatch();
            }

            EditorGUILayout.Space();
            if (GUILayout.Button("一键打包", GUILayout.Height(40)))
            {
                OneKeyBuildStep1();
            }
        }
        EditorGUILayout.EndScrollView();
    }
Exemplo n.º 13
0
 /// <summary>
 /// Constructor.  Subscribes to parent panel events and
 /// loads target domain file.
 /// </summary>
 /// <param name="parentPanel"></param>
 public FeedbackMechanism(SketchPanel parentPanel, string domainFilePath)
     : base(parentPanel)
 {
     this.mDomain = LoadDomainInfo(domainFilePath);
 }
Exemplo n.º 14
0
        private void BindDomain()
        {
            try
            {
                // load domain
                DomainInfo domain = ES.Services.Servers.GetDomain(PanelRequest.DomainID);
                if (domain == null)
                {
                    RedirectToBrowsePage();
                }


                // load package context
                PackageContext cntx = PackagesHelper.GetCachedPackageContext(domain.PackageId);

                DomainName.Text = domain.DomainName;

                bool webEnabled  = cntx.Groups.ContainsKey(ResourceGroups.Web);
                bool mailEnabled = cntx.Groups.ContainsKey(ResourceGroups.Mail);
                bool dnsEnabled  = cntx.Groups.ContainsKey(ResourceGroups.Dns);

                // web site
                if (webEnabled && domain.WebSiteId > 0)
                {
                    WebSitePanel.Visible      = true;
                    WebSiteAliasPanel.Visible = true;

                    WebSiteName.Text            = domain.WebSiteName;
                    WebSiteParkedPanel.Visible  = (String.Compare(domain.WebSiteName, domain.DomainName, true) == 0);
                    WebSitePointedPanel.Visible = !WebSiteParkedPanel.Visible;

                    BrowseWebSite.NavigateUrl = "http://" + domain.DomainName;
                }

                // mail domain
                if (mailEnabled && domain.MailDomainId > 0)
                {
                    MailDomainPanel.Visible      = true;
                    MailDomainAliasPanel.Visible = true;

                    MailDomainName.Text          = domain.MailDomainName;
                    MailEnabledPanel.Visible     = (String.Compare(domain.MailDomainName, domain.DomainName, true) == 0);
                    PointMailDomainPanel.Visible = !MailEnabledPanel.Visible;
                }

                // DNS
                if (dnsEnabled)
                {
                    DnsPanel.Visible         = true;
                    DnsEnabledPanel.Visible  = (domain.ZoneItemId > 0);
                    DnsDisabledPanel.Visible = !DnsEnabledPanel.Visible;

                    // dns editor
                    EditDnsRecords.Visible = (cntx.Quotas.ContainsKey(Quotas.DNS_EDITOR) &&
                                              cntx.Quotas[Quotas.DNS_EDITOR].QuotaAllocatedValue != 0) ||
                                             PanelSecurity.LoggedUser.Role == UserRole.Administrator;
                }

                // instant alias
                bool instantAliasAllowed = !String.IsNullOrEmpty(domain.InstantAliasName);
                bool instantAliasExists  = (domain.InstantAliasId > 0);
                if (instantAliasAllowed &&
                    !domain.IsDomainPointer && !domain.IsInstantAlias)
                {
                    InstantAliasPanel.Visible    = true;
                    InstantAliasEnabled.Visible  = instantAliasExists;
                    InstantAliasDisabled.Visible = !instantAliasExists;

                    // load instant alias
                    DomainInfo instantAlias = ES.Services.Servers.GetDomain(domain.InstantAliasId);
                    if (instantAlias != null)
                    {
                        WebSiteAliasPanel.Visible    = (instantAlias.WebSiteId > 0);
                        MailDomainAliasPanel.Visible = (instantAlias.MailDomainId > 0);
                    }

                    // instant alias
                    InstantAliasName.Text = domain.InstantAliasName;

                    // web site alias
                    WebSiteAlias.Text = WebSiteAlias.NavigateUrl = "http://" + domain.InstantAliasName;

                    // mail domain alias
                    MailDomainAlias.Text = "@" + domain.InstantAliasName;
                }

                // resellers
                AllowSubDomains.Checked = domain.HostingAllowed;
                if (PanelSecurity.EffectiveUser.Role != UserRole.User &&
                    !(domain.IsDomainPointer || domain.IsSubDomain || domain.IsInstantAlias))
                {
                    ResellersPanel.Visible = true;
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage("DOMAIN_GET_DOMAIN", ex);
                return;
            }
        }
Exemplo n.º 15
0
 public TableContentDomain(DomainInfo domainInfo, CremaDispatcher dispatcher)
     : base(domainInfo, dispatcher)
 {
 }
Exemplo n.º 16
0
 private void AddCommand(SwaggerDocument swaggerDoc, DocumentFilterContext context, DomainInfo domain, CommandInfo command)
 {
     swaggerDoc.Paths.Add($"/{this._teclyn.Configuration.CommandEndpointPrefix}/{this._translater.ExportDomainId(domain)}/{this._translater.ExportCommandId(command)}", new PathItem
     {
         Post = new Operation
         {
             Tags = new List <string> {
                 domain.Name
             },
             Consumes = new List <string>
             {
                 "application/json",
             },
             Parameters = new IParameter[]
             {
                 new BodyParameter
                 {
                     Name   = "command",
                     Schema = context.SchemaRegistry.GetOrRegister(command.CommandType),
                     In     = "body",
                 }
             },
             Responses = new Dictionary <string, Response>
             {
                 { "200", new Response {
                       Description = "Success"
                   } }
             }
         }
     });
 }
Exemplo n.º 17
0
        private int SetArguments(IReadOnlyList <string> args)
        {
            int domainCount   = 0;
            int passwordCount = 0;

            for (int aC = 0; aC < args.Count; aC++)
            {
                switch (args[aC])
                {
                case "-h":
                case "--help":
                    this.PrintUsage();
                    return(-1);

                case "-d":
                case "--domain":
                    if (!Common.CheckArgument(args, aC))
                    {
                        this.PrintUsage();
                        Console.WriteLine("domainid has not been specified");
                        Console.WriteLine();
                        return(2);
                    }

                    if (domainCount < this._DomainInfos.Count)
                    {
                        this._DomainInfos[domainCount].DomainIdRoute = args[aC + 1];
                    }
                    else
                    {
                        this._DomainInfos.Add(new DomainInfo {
                            DomainIdRoute = args[aC + 1]
                        });
                    }

                    domainCount++;
                    aC++;

                    break;

                case "-p":
                case "--password":
                    if (!Common.CheckArgument(args, aC))
                    {
                        this.PrintUsage();
                        Console.WriteLine("password has not been specified");
                        Console.WriteLine();
                        return(2);
                    }

                    if (passwordCount < this._DomainInfos.Count)
                    {
                        this._DomainInfos[passwordCount].Password = args[aC + 1];
                    }
                    else
                    {
                        this._DomainInfos.Add(new DomainInfo {
                            Password = args[aC + 1]
                        });
                    }

                    passwordCount++;
                    aC++;

                    break;

                case "-o":
                case "--output":
                    if (!Common.CheckArgument(args, aC))
                    {
                        this.PrintUsage();
                        Console.WriteLine("output path has not been specified");
                        Console.WriteLine();
                        return(2);
                    }
                    this._OutputLocation = args[aC + 1];
                    aC++;

                    break;

                case "-r":
                case "--recursive":
                    this._Recursive = true;

                    break;

                case "-x":
                case "--external":
                    this._ExternalContent = true;

                    break;

                case "-u":
                case "--publish":
                    this._Publish = true;

                    break;

                case "-y":
                    this._AutoApprove = true;

                    break;

                default:
                    if (aC + 1 < args.Count)
                    {
                        this.PrintUsage();
                        Console.WriteLine("unrecognizable argument");
                        Console.WriteLine();
                        return(2);
                    }

                    this._XeoraProjectPath = Path.GetFullPath(args[aC]);

                    if (!Directory.Exists(this._XeoraProjectPath))
                    {
                        Console.WriteLine("xeora project path is not exists");
                        return(1);
                    }

                    break;
                }
            }

            if (this._Publish && string.IsNullOrEmpty(this._OutputLocation))
            {
                this.PrintUsage();
                Console.WriteLine("output location is required when publish argument is used");
                Console.WriteLine();
                return(2);
            }

            if (this._ExternalContent && string.IsNullOrEmpty(this._OutputLocation))
            {
                this.PrintUsage();
                Console.WriteLine("output location is required when external content argument is used");
                Console.WriteLine();
                return(2);
            }

            if (string.IsNullOrEmpty(this._XeoraProjectPath))
            {
                this.PrintUsage();
                Console.WriteLine("xeora project path is required");
                Console.WriteLine();
                return(2);
            }

            if (domainCount == passwordCount)
            {
                return(0);
            }

            for (int i = 0; i < this._DomainInfos.Count; i++)
            {
                DomainInfo domainInfo =
                    this._DomainInfos[i];

                if (domainInfo.HasDomainIdRoute)
                {
                    continue;
                }

                if (!domainInfo.PasswordEnabled)
                {
                    this.PrintUsage();
                    Console.WriteLine("faulty definition of domainidroutes and passwords");
                    Console.WriteLine();
                    return(2);
                }

                if (!string.IsNullOrEmpty(this._GenericPassword))
                {
                    this.PrintUsage();
                    Console.WriteLine("detected more than one generic password assignment");
                    Console.WriteLine();
                    return(2);
                }

                this._GenericPassword = domainInfo.Password;

                this._DomainInfos.RemoveAt(i);
                i--;
            }

            if (this._DomainInfos.Count == 0)
            {
                return(0);
            }

            Console.WriteLine("DomainIdRoute and Password quantity does not match. Please");
            Console.WriteLine("approve the following list;");
            Console.WriteLine();

            foreach (DomainInfo domainInfo in this._DomainInfos)
            {
                Console.WriteLine($"{domainInfo.DomainIdRoute}: {(domainInfo.PasswordEnabled || !string.IsNullOrEmpty(this._GenericPassword) ? "ENCRYPTED" : "PLAIN")}");
            }

            Console.WriteLine();
            Console.Write("Do you approve the list? (y/N) ");

            if (this._AutoApprove)
            {
                Console.WriteLine("y");
            }
            else
            {
                string answer =
                    Console.ReadLine()?.ToLowerInvariant();
                if (string.IsNullOrEmpty(answer) ||
                    string.CompareOrdinal(answer, "y") != 0 &&
                    string.CompareOrdinal(answer, "yes") != 0)
                {
                    return(2);
                }
            }

            return(0);
        }
Exemplo n.º 18
0
 private void AddQuery(SwaggerDocument swaggerDoc, DocumentFilterContext context, DomainInfo domain, QueryInfo query)
 {
     swaggerDoc.Paths.Add($"/{this._teclyn.Configuration.CommandEndpointPrefix}/{this._translater.ExportDomainId(domain)}/{this._translater.ExportQueryId(query)}", new PathItem
     {
         Get = new Operation
         {
             Tags = new List <string> {
                 domain.Name
             },
             Consumes = new List <string>
             {
                 "application/json",
             },
             Parameters = query.Parameters.Select(p => this.BuildParameter(p.Key, p.Value)).ToList(),
             Responses  = new Dictionary <string, Response>
             {
                 { "200", new Response {
                       Description = "Success", Schema = this.GetSchema(context, query.ResultType)
                   } }
             }
         }
     });
 }
Exemplo n.º 19
0
        public GenericSvcResult ActivateService(ProvisioningContext context)
        {
            GenericSvcResult result = new GenericSvcResult();

            // remeber svc state
            SaveObjectState(SERVICE_INFO, context.ServiceInfo);

            // concretize service to be provisioned
            DomainNameSvc domainSvc = (DomainNameSvc)context.ServiceInfo;
            // concretize parent service
            HostingPackageSvc packageSvc = (HostingPackageSvc)context.ParentSvcInfo;

            try
            {
                // LOG INFO
                TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_ACTIVATE);
                TaskManager.WriteParameter(CONTRACT_PARAM, domainSvc.ContractId);
                TaskManager.WriteParameter(SVC_PARAM, domainSvc.ServiceName);
                TaskManager.WriteParameter(SVC_ID_PARAM, domainSvc.ServiceId);

                // 0. Do security checks
                if (!CheckOperationClientPermissions(result))
                {
                    // LOG ERROR
                    TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
                    TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
                    // EXIT
                    return(result);
                }
                //
                if (!CheckOperationClientStatus(result))
                {
                    // LOG ERROR
                    TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
                    TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
                    // EXIT
                    return(result);
                }

                // error: hosting addon should have parent svc assigned
                if (packageSvc == null || packageSvc.PackageId == 0)
                {
                    result.Succeed = false;
                    //
                    result.Error = PARENT_SVC_NOT_FOUND_MSG;
                    //
                    result.ResultCode = EcommerceErrorCodes.ERROR_PARENT_SVC_NOT_FOUND;

                    // LOG ERROR
                    TaskManager.WriteError(result.Error);
                    TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);

                    // EXIT
                    return(result);
                }

                // first of all - create internal domain in WebsitePanel
                if (domainSvc.Status == ServiceStatus.Ordered)
                {
                    // create domain info object
                    DomainInfo domain = ServerController.GetDomain(domainSvc.Fqdn);
                    //
                    if (domain != null)
                    {
                        domainSvc.DomainId = domain.DomainId;
                    }
                    //
                    if (domain == null)
                    {
                        domain                = new DomainInfo();
                        domain.DomainName     = domainSvc.Fqdn;
                        domain.HostingAllowed = false;
                        domain.PackageId      = packageSvc.PackageId;
                        // add internal domain
                        domainSvc.DomainId = ServerController.AddDomain(domain);
                        // check API result
                        if (domainSvc.DomainId < 1)
                        {
                            // ASSEMBLE ERROR
                            result.Succeed = false;
                            // try to find corresponding error code->error message mapping
                            if (ApiErrorCodesMap.ContainsKey(domainSvc.DomainId))
                            {
                                result.Error = ApiErrorCodesMap[domainSvc.DomainId];
                            }
                            else
                            {
                                result.Error = ERROR_ADD_INTERNAL_DOMAIN;
                            }
                            // copy result code
                            result.ResultCode = domainSvc.DomainId;

                            // LOG ERROR
                            TaskManager.WriteError(result.Error);
                            TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);

                            // EXIT
                            return(result);
                        }
                    }
                }

                // update nameservers only
                if (domainSvc["SPF_ACTION"] == "UPDATE_NS")
                {
                    // remove service here...
                    ServiceController.DeleteCustomerService(domainSvc.ServiceId);
                    //
                    result.Succeed = true;
                    // EXIT
                    return(result);
                }

                // load registrar wrapper
                IDomainRegistrar registrar = (IDomainRegistrar)SystemPluginController.GetSystemPluginInstance(
                    domainSvc.ContractId, domainSvc.PluginId, true);

                #region Commented operations
                // prepare consumer account information

                /*CommandParams cmdParams = PrepeareAccountParams(context.ConsumerInfo);
                 * // copy svc properties
                 * foreach (string keyName in domainSvc.GetAllKeys())
                 *      cmdParams[keyName] = domainSvc[keyName];
                 *
                 * // check registrar requires sub-account to be created
                 * if (registrar.SubAccountRequired)
                 * {
                 *      // 1. Load user's settings
                 *      UserSettings userSettings = LoadUserSettings(context.ConsumerInfo.UserId, registrar.PluginName);
                 *      // 2. Ensure user has account on registrar's side
                 *      if (userSettings.SettingsArray == null || userSettings.SettingsArray.Length == 0)
                 *      {
                 *              // 3. Check account exists
                 *              bool exists = registrar.CheckSubAccountExists(context.ConsumerInfo.Username, context.ConsumerInfo.Email);
                 *              //
                 *              AccountResult accResult = null;
                 *              //
                 *              if (!exists)
                 *              {
                 *                      // 4. Create user account
                 *                      accResult = registrar.CreateSubAccount(cmdParams);
                 *                      // copy keys & values
                 *                      foreach (string keyName in accResult.AllKeys)
                 *                      {
                 *                              userSettings[keyName] = accResult[keyName];
                 *                      }
                 *              }
                 *              else
                 *              {
                 *                      // 4a. Get sub-account info
                 *                      accResult = registrar.GetSubAccount(context.ConsumerInfo.Username,
                 *                              context.ConsumerInfo.Email);
                 *                      //
                 *                      foreach (string keyName in accResult.AllKeys)
                 *                              userSettings[keyName] = accResult[keyName];
                 *              }
                 *              // 5. Update user settings
                 *              int apiResult = UserController.UpdateUserSettings(userSettings);
                 *              // check API result
                 *              if (apiResult < 0)
                 *              {
                 *                      // BUILD ERROR
                 *                      result.Error = ERROR_UPDATE_USR_SETTINGS_MSG;
                 *                      result.Succeed = false;
                 *                      result.ResultCode = apiResult;
                 *                      // LOG ERROR
                 *                      TaskManager.WriteError(result.Error);
                 *                      TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
                 *                      // ROLLBACK
                 *                      RollbackOperation(domainSvc.DomainId);
                 *                      // EXIT
                 *                      return result;
                 *              }
                 *      }
                 *      // copy registrar-specific data
                 *      foreach (string[] pair in userSettings.SettingsArray)
                 *      {
                 *              // copy 2
                 *              cmdParams[pair[0]] = pair[1];
                 *      }
                 * }*/
                #endregion

                // load NS settings
                PackageSettings nsSettings = PackageController.GetPackageSettings(packageSvc.PackageId, PackageSettings.NAME_SERVERS);
                // build name servers array
                string[] nameServers = null;
                if (!String.IsNullOrEmpty(nsSettings[PackageSettings.NAME_SERVERS]))
                {
                    nameServers = nsSettings[PackageSettings.NAME_SERVERS].Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                }

                // register or renew domain
                if (domainSvc.Status == ServiceStatus.Ordered)
                {
                    // try to register domain
                    registrar.RegisterDomain(domainSvc, context.ConsumerInfo, nameServers);
                }
                else
                {
                    // try to renew domain
                    registrar.RenewDomain(domainSvc, context.ConsumerInfo, nameServers);
                }

                // change svc status to active
                domainSvc.Status = ServiceStatus.Active;
                // update service info
                int updResult = UpdateServiceInfo(domainSvc);
                // check update result for errors
                if (updResult < 0)
                {
                    // BUILD ERROR
                    result.ResultCode = updResult;
                    result.Succeed    = false;
                    result.Error      = ERROR_SVC_UPDATE_MSG;
                    // LOG ERROR
                    TaskManager.WriteError(result.Error);
                    TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
                    // ROLLBACK
                    RollbackOperation(domainSvc.DomainId);
                    // EXIT
                    return(result);
                }
                //
                result.Succeed = true;
                //
                SetOutboundParameters(context);
            }
            catch (Exception ex)
            {
                // LOG ERROR
                TaskManager.WriteError(ex);
                result.Succeed = false;
                // ROLLBACK
                RollbackOperation(result.ResultCode);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
            //
            return(result);
        }
Exemplo n.º 20
0
 private void DeleteDomainFiles(DomainInfo domainInfo)
 {
 }
Exemplo n.º 21
0
        public bool RunDetection()
        {
            logWriter.AddLog("===== Start detecting =====", LogLevel.Normal, false);

            DomainInfo domainInfo = new DomainInfo()
            {
                Admin         = ptfcfg.KdcAdminUser,
                AdminPassword = ptfcfg.KdcAdminPwd,
                Name          = ptfcfg.KdcDomainName
            };

            //local dc01
            Server dc01 = new Server()
            {
                ComputerName = ptfcfg.KdcName,
                IPv4         = ptfcfg.KDCIP
            };

            if (!ServerHelper.DetectDC(domainInfo, dc01, logWriter))
            {
                return(false);
            }

            var dc02 = new Server()
            {
                ComputerName = ptfcfg.KdcName,
                IPv4         = ptfcfg.KDCIP
            };

            if (!ServerHelper.DetectDC(domainInfo, dc02, logWriter))
            {
                return(false);
            }

            var ap01 = new Server()
            {
                ComputerName = ptfcfg.ApplicationServerName,
                IPv4         = ptfcfg.ApplicationServerIP,
                FQDN         = ptfcfg.ApplicationServerName
            };

            if (!DetectAP(domainInfo, ap01))
            {
                return(false);
            }

            var ap02 = new Server()
            {
                ComputerName = ptfcfg.CrossForestApplicationServerName,
                IPv4         = ptfcfg.CrossForestApplicationServerIP,
                FQDN         = ptfcfg.CrossForestApplicationServerName
            };

            if (!DetectAP(domainInfo, ap02))
            {
                return(false);
            }

            ComputerInfo client = new ComputerInfo()
            {
                ComputerName = ptfcfg.ClientComputerName,
                IPv4         = ptfcfg.ClientComputerIp,
                Password     = ptfcfg.ClientAdminPwd
            };

            //local client
            if (!ServerHelper.DetectClient(domainInfo, client, logWriter))
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 22
0
        private static int AddOrganizationDomain(int itemId, string domainName)
        {
            Log.WriteStart(string.Format("Importing domain {0}...", domainName));

            // load organization
            Organization org = (Organization)PackageController.GetPackageItem(itemId);

            if (org == null)
            {
                return(-1);
            }

            // check package
            int packageCheck = SecurityContext.CheckPackage(org.PackageId, DemandPackage.IsActive);

            if (packageCheck < 0)
            {
                return(packageCheck);
            }

            DomainInfo domain = null;

            // check if the domain already exists
            int checkResult = ServerController.CheckDomain(domainName);

            if (checkResult == BusinessErrorCodes.ERROR_DOMAIN_ALREADY_EXISTS)
            {
                // domain exists
                // check if it belongs to the same space
                domain = ServerController.GetDomain(domainName);
                if (domain == null)
                {
                    return(checkResult);
                }

                if (domain.PackageId != org.PackageId)
                {
                    return(checkResult);
                }

                if (DataProvider.ExchangeOrganizationDomainExists(domain.DomainId))
                {
                    return(BusinessErrorCodes.ERROR_ORGANIZATION_DOMAIN_IS_IN_USE);
                }
            }
            else if (checkResult == BusinessErrorCodes.ERROR_RESTRICTED_DOMAIN)
            {
                return(checkResult);
            }

            // create domain if required
            if (domain == null)
            {
                domain                = new DomainInfo();
                domain.PackageId      = org.PackageId;
                domain.DomainName     = domainName;
                domain.IsInstantAlias = false;
                domain.IsSubDomain    = false;

                // add domain
                domain.DomainId = ServerController.AddDomain(domain);
            }



            // register domain
            DataProvider.AddExchangeOrganizationDomain(itemId, domain.DomainId, false);

            // register service item
            OrganizationDomain exchDomain = new OrganizationDomain();

            exchDomain.Name      = domainName;
            exchDomain.PackageId = org.PackageId;
            exchDomain.ServiceId = org.ServiceId;
            PackageController.AddPackageItem(exchDomain);
            Log.WriteEnd("Domain imported");
            return(0);
        }
Exemplo n.º 23
0
 private async void Domain_PropertyChanged(object sender, DomainPropertyEventArgs e)
 {
     this.domainInfo  = this.domain.DomainInfo;
     this.domainState = this.domain.DomainState;
     await this.RefreshAsync();
 }
Exemplo n.º 24
0
 /// <summary>
 /// Upon loading this Feedback Mechanism, read domain info from
 /// domain file.  <see cref="Labeler.Form1.loadDomain()"/>
 /// </summary>
 public DomainAwareFeedbackMechanism()
 {
     this.domain = loadDomain();
 }
Exemplo n.º 25
0
        public static LyncUserResult CreateLyncUser(int itemId, int accountId, int lyncUserPlanId)
        {
            LyncUserResult res = TaskManager.StartResultTask <LyncUserResult>("LYNC", "CREATE_LYNC_USER");

            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

            if (accountCheck < 0)
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.NOT_AUTHORIZED);
                return(res);
            }


            LyncUser retLyncUser = new LyncUser();
            bool     isLyncUser;

            isLyncUser = DataProvider.CheckLyncUserExists(accountId);
            if (isLyncUser)
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.USER_IS_ALREADY_LYNC_USER);
                return(res);
            }

            OrganizationUser user;

            user = OrganizationController.GetAccount(itemId, accountId);
            if (user == null)
            {
                TaskManager.CompleteResultTask(res, ErrorCodes.CANNOT_GET_ACCOUNT);
                return(res);
            }

            user = OrganizationController.GetUserGeneralSettings(itemId, accountId);
            if (string.IsNullOrEmpty(user.FirstName))
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.USER_FIRST_NAME_IS_NOT_SPECIFIED);
                return(res);
            }

            if (string.IsNullOrEmpty(user.LastName))
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.USER_LAST_NAME_IS_NOT_SPECIFIED);
                return(res);
            }

            bool quota = CheckQuota(itemId);

            if (!quota)
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.USER_QUOTA_HAS_BEEN_REACHED);
                return(res);
            }


            LyncServer lync;

            try
            {
                bool bReloadConfiguration = false;

                Organization org = (Organization)PackageController.GetPackageItem(itemId);
                if (org == null)
                {
                    throw new ApplicationException(
                              string.Format("Organization is null. ItemId={0}", itemId));
                }

                int lyncServiceId = GetLyncServiceID(org.PackageId);
                lync = GetLyncServer(lyncServiceId, org.ServiceId);

                if (string.IsNullOrEmpty(org.LyncTenantId))
                {
                    PackageContext cntx = PackageController.GetPackageContext(org.PackageId);

                    org.LyncTenantId = lync.CreateOrganization(org.OrganizationId,
                                                               org.DefaultDomain,
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_CONFERENCING].QuotaAllocatedValue),
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_ALLOWVIDEO].QuotaAllocatedValue),
                                                               Convert.ToInt32(cntx.Quotas[Quotas.LYNC_MAXPARTICIPANTS].QuotaAllocatedValue),
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_FEDERATION].QuotaAllocatedValue),
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_ENTERPRISEVOICE].QuotaAllocatedValue));

                    if (string.IsNullOrEmpty(org.LyncTenantId))
                    {
                        TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ENABLE_ORG);
                        return(res);
                    }
                    else
                    {
                        DomainInfo domain = ServerController.GetDomain(org.DefaultDomain);

                        //Add the service records
                        if (domain != null)
                        {
                            if (domain.ZoneItemId != 0)
                            {
                                ServerController.AddServiceDNSRecords(org.PackageId, ResourceGroups.Lync, domain, "");
                            }
                        }

                        PackageController.UpdatePackageItem(org);

                        bReloadConfiguration = true;
                    }
                }

                if (lync.GetOrganizationTenantId(org.OrganizationId) == string.Empty)
                {
                    PackageContext cntx = PackageController.GetPackageContext(org.PackageId);

                    org.LyncTenantId = lync.CreateOrganization(org.OrganizationId,
                                                               org.DefaultDomain,
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_CONFERENCING].QuotaAllocatedValue),
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_ALLOWVIDEO].QuotaAllocatedValue),
                                                               Convert.ToInt32(cntx.Quotas[Quotas.LYNC_MAXPARTICIPANTS].QuotaAllocatedValue),
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_FEDERATION].QuotaAllocatedValue),
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_ENTERPRISEVOICE].QuotaAllocatedValue));

                    if (string.IsNullOrEmpty(org.LyncTenantId))
                    {
                        TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ENABLE_ORG);
                        return(res);
                    }
                    else
                    {
                        PackageController.UpdatePackageItem(org);

                        bReloadConfiguration = true;
                    }
                }


                LyncUserPlan plan = GetLyncUserPlan(itemId, lyncUserPlanId);

                if (!lync.CreateUser(org.OrganizationId, user.UserPrincipalName, plan))
                {
                    TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ADD_LYNC_USER);
                    return(res);
                }

                if (bReloadConfiguration)
                {
                    LyncControllerAsync userWorker = new LyncControllerAsync();
                    userWorker.LyncServiceId         = lyncServiceId;
                    userWorker.OrganizationServiceId = org.ServiceId;
                    userWorker.Enable_CsComputerAsync();
                }
            }
            catch (Exception ex)
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ADD_LYNC_USER, ex);
                return(res);
            }

            try
            {
                DataProvider.AddLyncUser(accountId, lyncUserPlanId, user.UserPrincipalName);
            }
            catch (Exception ex)
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ADD_LYNC_USER_TO_DATABASE, ex);
                return(res);
            }

            res.IsSuccess = true;
            TaskManager.CompleteResultTask();
            return(res);
        }
Exemplo n.º 26
0
        public void CRUDTest()
        {
            var domainName = "sdk-dotnet-crud-" + DateTime.Now.Ticks;
            var regRequest = new RegisterDomainRequest()
            {
                Name        = domainName,
                Description = "A Description",
                WorkflowExecutionRetentionPeriodInDays = "3"
            };

            var regResponse = Client.RegisterDomainAsync(regRequest).Result;

            try
            {
                Sleep(); // Sleep for the eventual consistency
                Assert.IsNotNull(regResponse.ResponseMetadata.RequestId);
                var descRequest = new DescribeDomainRequest()
                {
                    Name = domainName
                };
                var descResponse = Client.DescribeDomainAsync(descRequest).Result;

                Assert.AreEqual(domainName, descResponse.DomainDetail.DomainInfo.Name);
                Assert.AreEqual("A Description", descResponse.DomainDetail.DomainInfo.Description);
                Assert.AreEqual("3", descResponse.DomainDetail.Configuration.WorkflowExecutionRetentionPeriodInDays);
                Assert.IsNotNull(descResponse.DomainDetail.DomainInfo.Status);


                DomainInfo info = null;
                for (int i = 0; i < MaxRetries; i++)
                {
                    Sleep(); // Sleep for the eventual consistency
                    var listDomainResponse = Client.ListDomainsAsync(
                        new ListDomainsRequest()
                    {
                        RegistrationStatus = descResponse.DomainDetail.DomainInfo.Status
                    }).Result;

                    Assert.IsTrue(listDomainResponse.DomainInfos.Infos.Count > 0);
                    info = listDomainResponse.DomainInfos.Infos.FirstOrDefault(x => string.Equals(x.Name, domainName));
                    if (info != null)
                    {
                        break;
                    }
                }
                Assert.IsNotNull(info);
                Assert.IsNotNull(info.Status);


                var activityDescription = "My Description Activity" + DateTime.Now.Ticks;
                var regActivityRequest  = new RegisterActivityTypeRequest()
                {
                    Name            = "My Activity",
                    Domain          = domainName,
                    Description     = activityDescription,
                    Version         = "1.0",
                    DefaultTaskList = new TaskList()
                    {
                        Name = "ImportantTasks"
                    },
                    DefaultTaskHeartbeatTimeout       = ONE_HOUR_DURATION,
                    DefaultTaskScheduleToCloseTimeout = TWO_HOUR_DURATION,
                    DefaultTaskScheduleToStartTimeout = THREE_HOUR_DURATION,
                    DefaultTaskStartToCloseTimeout    = FOUR_HOUR_DURATION
                };

                var regActivityResponse = Client.RegisterActivityTypeAsync(regActivityRequest).Result;
                Assert.IsNotNull(regActivityResponse.ResponseMetadata.RequestId);
                try
                {
                    Sleep(); // Sleep for the eventual consistency
                    var descActivityTypeRequest = new DescribeActivityTypeRequest()
                    {
                        Domain       = domainName,
                        ActivityType = new ActivityType()
                        {
                            Name    = "My Activity",
                            Version = "1.0"
                        }
                    };

                    var descActivityTypeResponse = Client.DescribeActivityTypeAsync(descActivityTypeRequest).Result;

                    Assert.AreEqual(ONE_HOUR_DURATION, descActivityTypeResponse.ActivityTypeDetail.Configuration.DefaultTaskHeartbeatTimeout);
                    Assert.AreEqual(TWO_HOUR_DURATION, descActivityTypeResponse.ActivityTypeDetail.Configuration.DefaultTaskScheduleToCloseTimeout);
                    Assert.AreEqual(THREE_HOUR_DURATION, descActivityTypeResponse.ActivityTypeDetail.Configuration.DefaultTaskScheduleToStartTimeout);
                    Assert.AreEqual(FOUR_HOUR_DURATION, descActivityTypeResponse.ActivityTypeDetail.Configuration.DefaultTaskStartToCloseTimeout);

                    ListActivityTypesResponse listActivityResponse = null;
                    for (int i = 0; i < MaxRetries; i++)
                    {
                        Sleep(); // Sleep for the eventual consistency
                        listActivityResponse = Client.ListActivityTypesAsync(
                            new ListActivityTypesRequest()
                        {
                            Domain             = domainName,
                            RegistrationStatus = descActivityTypeResponse.ActivityTypeDetail.TypeInfo.Status
                        }).Result;
                        if (listActivityResponse.ActivityTypeInfos.TypeInfos.Count > 0)
                        {
                            break;
                        }
                    }
                    Assert.IsNotNull(listActivityResponse);
                    Assert.IsTrue(listActivityResponse.ActivityTypeInfos.TypeInfos.Count > 0);
                    var acInfo = listActivityResponse.ActivityTypeInfos.TypeInfos.FirstOrDefault(x => x.Description == activityDescription);
                    Assert.IsNotNull(acInfo);
                }
                finally
                {
                    var depActivityRequest = new DeprecateActivityTypeRequest()
                    {
                        Domain       = domainName,
                        ActivityType = new ActivityType()
                        {
                            Name    = "My Activity",
                            Version = "1.0"
                        }
                    };

                    var depActivityTypeResponse = Client.DeprecateActivityTypeAsync(depActivityRequest).Result;
                }

                var workflowDescription = "My Workflow Description" + DateTime.Now.Ticks;
                var regWorkflowRequest  = new RegisterWorkflowTypeRequest()
                {
                    Name            = "My Workflow",
                    Domain          = domainName,
                    Description     = workflowDescription,
                    Version         = "1.0",
                    DefaultTaskList = new TaskList()
                    {
                        Name = "ImportantTasks"
                    },
                    DefaultExecutionStartToCloseTimeout = THREE_HOUR_DURATION,
                    DefaultTaskStartToCloseTimeout      = FOUR_HOUR_DURATION
                };

                var regWorkflowResponse = Client.RegisterWorkflowTypeAsync(regWorkflowRequest).Result;
                try
                {
                    Sleep(); // Sleep for the eventual consistency
                    var descWorkFlowRequest = new DescribeWorkflowTypeRequest()
                    {
                        Domain       = domainName,
                        WorkflowType = new WorkflowType()
                        {
                            Name    = "My Workflow",
                            Version = "1.0"
                        }
                    };
                    var descWorkflowResponse = Client.DescribeWorkflowTypeAsync(descWorkFlowRequest).Result;

                    Assert.AreEqual("My Workflow", descWorkflowResponse.WorkflowTypeDetail.TypeInfo.WorkflowType.Name);
                    Assert.AreEqual("1.0", descWorkflowResponse.WorkflowTypeDetail.TypeInfo.WorkflowType.Version);
                    Assert.AreEqual(THREE_HOUR_DURATION, descWorkflowResponse.WorkflowTypeDetail.Configuration.DefaultExecutionStartToCloseTimeout);
                    Assert.AreEqual(FOUR_HOUR_DURATION, descWorkflowResponse.WorkflowTypeDetail.Configuration.DefaultTaskStartToCloseTimeout);
                    Assert.AreEqual("ImportantTasks", descWorkflowResponse.WorkflowTypeDetail.Configuration.DefaultTaskList.Name);

                    ListWorkflowTypesResponse listWorkflowResponse = null;
                    for (int retries = 0; retries < 5; retries++)
                    {
                        UtilityMethods.Sleep(TimeSpan.FromSeconds(retries));
                        listWorkflowResponse = Client.ListWorkflowTypesAsync(
                            new ListWorkflowTypesRequest()
                        {
                            Domain             = domainName,
                            RegistrationStatus = descWorkflowResponse.WorkflowTypeDetail.TypeInfo.Status
                        }).Result;

                        if (listWorkflowResponse.WorkflowTypeInfos.TypeInfos.Count > 0)
                        {
                            break;
                        }
                    }

                    Assert.IsTrue(listWorkflowResponse.WorkflowTypeInfos.TypeInfos.Count > 0);
                    var wfInfo = listWorkflowResponse.WorkflowTypeInfos.TypeInfos.FirstOrDefault(x => x.Description == workflowDescription);
                    Assert.IsNotNull(wfInfo);
                }
                finally
                {
                    var depWorkflowRequest = new DeprecateWorkflowTypeRequest()
                    {
                        Domain       = domainName,
                        WorkflowType = new WorkflowType()
                        {
                            Name    = "My Workflow",
                            Version = "1.0"
                        }
                    };
                    var depWorkflowTypeResponse = Client.DeprecateWorkflowTypeAsync(depWorkflowRequest).Result;
                    Assert.IsNotNull(depWorkflowTypeResponse.ResponseMetadata.RequestId);
                }
            }
            finally
            {
                var depRequest = new DeprecateDomainRequest()
                {
                    Name = domainName
                };
                var depResponse = Client.DeprecateDomainAsync(depRequest).Result;
                Assert.IsNotNull(depResponse.ResponseMetadata.RequestId);
            }
        }
Exemplo n.º 27
0
        public static DomainInfo GetDomainInfo(string domainController, string port, string userName, string password, string searchBase, RtContextValue _context)
        {
            int ldapPort = ConvertPort(port);

            if (ldapPort == 0)
            {
                ldapPort = 389;
            }
            DomainInfo domainInfo = new DomainInfo();

            if (domains != null && domains.Contains(domainController))
            {
                domainInfo.DomainName      = domainController;
                domainInfo.Users           = (ArrayList)domains[domainController];
                domainInfo.DistiguishNames = (Hashtable)domains[domainController + "1"];
                return(domainInfo);
            }

            if (domains == null)
            {
                domains = new Hashtable();
            }
            ArrayList users = new ArrayList();

            if (_context.Equals(RtContextValue.JVCACHE))
            {
                Hashtable distinguishNames = new Hashtable();

                //Connection Build for Ldap Authentication
                _ldapConnection = GetLdapConnection(domainController, ldapPort, userName, password);

                string filter = "(objectClass=*)";

                String[] attribsToReturn;

                string attribs = "cn";

                // split the single string expression from the string argument into an array of strings
                attribsToReturn = attribs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                SearchRequest searchRequest = new SearchRequest(searchBase, filter, System.DirectoryServices.Protocols.SearchScope.Subtree, attribsToReturn);
                try
                {
                    SearchResponse searchResponse = (SearchResponse)_ldapConnection.SendRequest(searchRequest);

                    if (searchResponse.Entries.Count > 0)
                    {
                        foreach (SearchResultEntry entry in searchResponse.Entries)
                        {
                            // retrieve a specific attribute
                            SearchResultAttributeCollection attributes = entry.Attributes;
                            foreach (DirectoryAttribute attribute in attributes.Values)
                            {
                                users.Add(attribute[0].ToString());
                                distinguishNames.Add(attribute[0].ToString(), entry.DistinguishedName);
                            }
                        }
                    }
                }
                catch (Exception ex) { throw ex; }

                domainInfo.Users           = users;
                domainInfo.DistiguishNames = distinguishNames;

                domains[domainController]       = users;
                domains[domainController + "1"] = distinguishNames;
            }
            else
            {
                #region --- Previous Code ----
                DirectoryEntry    adRoot   = new DirectoryEntry("LDAP://" + domainController, userName, password);
                DirectorySearcher searcher = new DirectorySearcher(adRoot);
                searcher.SearchScope     = System.DirectoryServices.SearchScope.Subtree;
                searcher.ReferralChasing = ReferralChasingOption.All;
                searcher.Filter          = "(&(objectClass=user)(objectCategory=person))";
                searcher.PropertiesToLoad.Add("SAMAccountname");
                searcher.PageSize = 1000;

                try
                {
                    SearchResultCollection result = searcher.FindAll();
                    foreach (SearchResult a in result)
                    {
                        DirectoryEntry entry    = a.GetDirectoryEntry();
                        string         UserName = a.Properties["SAMAccountname"][0].ToString();
                        users.Add(UserName);
                    }
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    adRoot.Dispose();
                    searcher.Dispose();
                }
                domainInfo.Users = users;

                domains[domainController] = users;
                #endregion
            }
            return(domainInfo);
        }
Exemplo n.º 28
0
 public virtual void GenOsql(DomainInfo domain, InternalBookmark ibm, int domainIndex)
 {
 }
Exemplo n.º 29
0
        static void HandleConnection(System.IO.DirectoryInfo info, TcpClient client)
        {
            Area ws = null;
            ClientStateInfo clientInfo = new ClientStateInfo();
            using (client)
            using (SharedNetwork.SharedNetworkInfo sharedInfo = new SharedNetwork.SharedNetworkInfo())
            {
                try
                {
                    var stream = client.GetStream();
                    Handshake hs = ProtoBuf.Serializer.DeserializeWithLengthPrefix<Handshake>(stream, ProtoBuf.PrefixStyle.Fixed32);
                    DomainInfo domainInfo = null;
                    lock (SyncObject)
                    {
                        if (hs.RequestedModule == null)
                            hs.RequestedModule = string.Empty;
                        if (!Domains.TryGetValue(hs.RequestedModule, out domainInfo))
                        {
                            domainInfo = Domains.Where(x => x.Key.Equals(hs.RequestedModule, StringComparison.OrdinalIgnoreCase)).Select(x => x.Value).FirstOrDefault();
                        }
                        if (domainInfo == null)
                        {
                            if (!Config.AllowVaultCreation || !Config.RequiresAuthentication || string.IsNullOrEmpty(hs.RequestedModule) || System.IO.Directory.Exists(System.IO.Path.Combine(info.FullName, hs.RequestedModule)))
                            {
                                Network.StartTransaction startSequence = Network.StartTransaction.CreateRejection();
                                Printer.PrintDiagnostics("Rejecting client due to invalid domain: \"{0}\".", hs.RequestedModule);
                                ProtoBuf.Serializer.SerializeWithLengthPrefix<Network.StartTransaction>(stream, startSequence, ProtoBuf.PrefixStyle.Fixed32);
                                return;
                            }
                            domainInfo = new DomainInfo()
                            {
                                Bare = true,
                                Directory = null
                            };
                        }
                    }
                    try
                    {
                        ws = Area.Load(domainInfo.Directory, true, true);
                        if (domainInfo.Bare)
                            throw new Exception("Domain is bare, but workspace could be loaded!");
                    }
                    catch
                    {
                        if (!domainInfo.Bare)
                            throw new Exception("Domain not bare, but couldn't load workspace!");
                    }
                    Printer.PrintDiagnostics("Received handshake - protocol: {0}", hs.VersionrProtocol);
                    SharedNetwork.Protocol? clientProtocol = hs.CheckProtocol();
                    bool valid = true;
                    if (clientProtocol == null)
                        valid = false;
                    else
                    {
                        valid = SharedNetwork.AllowedProtocols.Contains(clientProtocol.Value);
                        if (Config.RequiresAuthentication && !SharedNetwork.SupportsAuthentication(clientProtocol.Value))
                            valid = false;
                    }
                    if (valid)
                    {
                        sharedInfo.CommunicationProtocol = clientProtocol.Value;
                        Network.StartTransaction startSequence = null;
                        clientInfo.Access = Rights.Read | Rights.Write;
                        clientInfo.BareAccessRequired = domainInfo.Bare;
                        if (PrivateKey != null)
                        {
                            startSequence = Network.StartTransaction.Create(domainInfo.Bare ? string.Empty : ws.Domain.ToString(), PublicKey, clientProtocol.Value);
                            Printer.PrintDiagnostics("Sending RSA key...");
                            ProtoBuf.Serializer.SerializeWithLengthPrefix<Network.StartTransaction>(stream, startSequence, ProtoBuf.PrefixStyle.Fixed32);
                            if (!HandleAuthentication(clientInfo, client, sharedInfo))
                                throw new Exception("Authentication failed.");
                            StartClientTransaction clientKey = ProtoBuf.Serializer.DeserializeWithLengthPrefix<StartClientTransaction>(stream, ProtoBuf.PrefixStyle.Fixed32);
                            System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter exch = new System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter(PrivateKey);
                            byte[] aesKey = exch.DecryptKeyExchange(clientKey.Key);
                            byte[] aesIV = exch.DecryptKeyExchange(clientKey.IV);
                            Printer.PrintDiagnostics("Got client key: {0}", System.Convert.ToBase64String(aesKey));

                            var aesCSP = System.Security.Cryptography.AesManaged.Create();

                            sharedInfo.DecryptorFunction = () => { return aesCSP.CreateDecryptor(aesKey, aesIV); };
                            sharedInfo.EncryptorFunction = () => { return aesCSP.CreateEncryptor(aesKey, aesIV); };
                        }
                        else
                        {
                            startSequence = Network.StartTransaction.Create(domainInfo.Bare ? string.Empty : ws.Domain.ToString(), clientProtocol.Value);
                            ProtoBuf.Serializer.SerializeWithLengthPrefix<Network.StartTransaction>(stream, startSequence, ProtoBuf.PrefixStyle.Fixed32);
                            if (!HandleAuthentication(clientInfo, client, sharedInfo))
                                throw new Exception("Authentication failed.");
                            StartClientTransaction clientKey = ProtoBuf.Serializer.DeserializeWithLengthPrefix<StartClientTransaction>(stream, ProtoBuf.PrefixStyle.Fixed32);
                        }
                        sharedInfo.Stream = stream;
                        sharedInfo.Workspace = ws;
                        sharedInfo.ChecksumType = Config.ChecksumType;

                        clientInfo.SharedInfo = sharedInfo;

                        while (true)
                        {
                            NetCommand command = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(stream, ProtoBuf.PrefixStyle.Fixed32);
                            if (command.Type == NetCommandType.Close)
                            {
                                Printer.PrintDiagnostics("Client closing connection.");
                                break;
                            }
                            else if (command.Type == NetCommandType.PushInitialVersion)
                            {
                                bool fresh = false;
                                if (domainInfo.Directory == null)
                                {
                                    if (!clientInfo.Access.HasFlag(Rights.Create))
                                        throw new Exception("Access denied.");
                                    fresh = true;
                                    System.IO.DirectoryInfo newDirectory = new System.IO.DirectoryInfo(System.IO.Path.Combine(info.FullName, hs.RequestedModule));
                                    newDirectory.Create();
                                    domainInfo.Directory = newDirectory;
                                    if (!newDirectory.Exists)
                                        throw new Exception("Access denied.");
                                }
                                if (!clientInfo.Access.HasFlag(Rights.Write))
                                    throw new Exception("Access denied.");
                                lock (SyncObject)
                                {
                                    ws = Area.InitRemote(domainInfo.Directory, Utilities.ReceiveEncrypted<ClonePayload>(clientInfo.SharedInfo));
                                    clientInfo.SharedInfo.Workspace = ws;
                                    domainInfo.Bare = false;
                                    if (fresh)
                                        Domains[hs.RequestedModule] = domainInfo;
                                }
                            }
                            else if (command.Type == NetCommandType.PushBranchJournal)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Write))
                                    throw new Exception("Access denied.");
                                SharedNetwork.ReceiveBranchJournal(sharedInfo);
                            }
                            else if (command.Type == NetCommandType.QueryBranchID)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Read))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Client is requesting a branch info for {0}", string.IsNullOrEmpty(command.AdditionalPayload) ? "<root>" : "\"" + command.AdditionalPayload + "\"");
                                bool multiple = false;
                                Objects.Branch branch = string.IsNullOrEmpty(command.AdditionalPayload) ? ws.RootBranch : ws.GetBranchByPartialName(command.AdditionalPayload, out multiple);
                                if (branch != null)
                                {
                                    ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Acknowledge, AdditionalPayload = branch.ID.ToString() }, ProtoBuf.PrefixStyle.Fixed32);
                                }
                                else if (!multiple)
                                {
                                    ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Error, AdditionalPayload = "branch not recognized" }, ProtoBuf.PrefixStyle.Fixed32);
                                }
                                else
                                {
                                    ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Error, AdditionalPayload = "multiple branches with that name!" }, ProtoBuf.PrefixStyle.Fixed32);
                                }
                            }
                            else if (command.Type == NetCommandType.ListBranches)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Read))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Client is requesting a branch list.");
                                ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Acknowledge }, ProtoBuf.PrefixStyle.Fixed32);
                                if (command.Identifier == 1) // send extra data
                                {
                                    BranchList bl = new BranchList();
                                    bl.Branches = clientInfo.SharedInfo.Workspace.Branches.ToArray();
                                    Dictionary<Guid, Objects.Version> importantVersions = new Dictionary<Guid, Objects.Version>();
                                    List<KeyValuePair<Guid, Guid>> allHeads = new List<KeyValuePair<Guid, Guid>>();
                                    foreach (var x in bl.Branches)
                                    {
                                        if (x.Terminus.HasValue && !importantVersions.ContainsKey(x.Terminus.Value))
                                        {
                                            importantVersions[x.Terminus.Value] = clientInfo.SharedInfo.Workspace.GetVersion(x.Terminus.Value);
                                            continue;
                                        }
                                        var heads = clientInfo.SharedInfo.Workspace.GetBranchHeads(x);
                                        foreach (var head in heads)
                                        {
                                            if (!importantVersions.ContainsKey(head.Version))
                                                importantVersions[head.Version] = clientInfo.SharedInfo.Workspace.GetVersion(head.Version);
                                        }
                                        allHeads.AddRange(heads.Select(y => new KeyValuePair<Guid, Guid>(y.Branch, y.Version)));
                                    }
                                    bl.Heads = allHeads.ToArray();
                                    bl.ImportantVersions = importantVersions.Values.ToArray();
                                    Utilities.SendEncrypted<BranchList>(clientInfo.SharedInfo, bl);
                                }
                                else
                                {
                                    BranchList bl = new BranchList();
                                    bl.Branches = clientInfo.SharedInfo.Workspace.Branches.ToArray();
                                    List<KeyValuePair<Guid, Guid>> allHeads = new List<KeyValuePair<Guid, Guid>>();
                                    foreach (var x in bl.Branches)
                                    {
                                        if (x.Terminus.HasValue)
                                            continue;
                                        var heads = clientInfo.SharedInfo.Workspace.GetBranchHeads(x);
                                        if (heads.Count == 1)
                                            allHeads.Add(new KeyValuePair<Guid, Guid>(x.ID, heads[0].Version));
                                    }
                                    bl.Heads = allHeads.ToArray();
                                    Utilities.SendEncrypted<BranchList>(clientInfo.SharedInfo, bl);
                                }
                            }
                            else if (command.Type == NetCommandType.RequestRecordUnmapped)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Read))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Client is requesting specific record data blobs.");
                                SharedNetwork.SendRecordDataUnmapped(sharedInfo);
                            }
                            else if (command.Type == NetCommandType.Clone)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Read))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Client is requesting to clone the vault.");
                                Objects.Version initialRevision = ws.GetVersion(ws.Domain);
                                Objects.Branch initialBranch = ws.GetBranch(initialRevision.Branch);
                                Utilities.SendEncrypted<ClonePayload>(sharedInfo, new ClonePayload() { InitialBranch = initialBranch, RootVersion = initialRevision });
                            }
                            else if (command.Type == NetCommandType.PullVersions)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Read))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Client asking for remote version information.");
                                Branch branch = ws.GetBranch(new Guid(command.AdditionalPayload));
                                if (branch == null)
                                    ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Error, AdditionalPayload = string.Format("Unknown branch {0}", command.AdditionalPayload) }, ProtoBuf.PrefixStyle.Fixed32);
                                else
                                    ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Acknowledge }, ProtoBuf.PrefixStyle.Fixed32);
                                Stack<Objects.Branch> branchesToSend = new Stack<Branch>();
                                Stack<Objects.Version> versionsToSend = new Stack<Objects.Version>();
                                if (!SharedNetwork.SendBranchJournal(sharedInfo))
                                    throw new Exception();
                                if (!SharedNetwork.GetVersionList(sharedInfo, sharedInfo.Workspace.GetBranchHeadVersion(branch), out branchesToSend, out versionsToSend))
                                    throw new Exception();
                                if (!SharedNetwork.SendBranches(sharedInfo, branchesToSend))
                                    throw new Exception();
                                if (!SharedNetwork.SendVersions(sharedInfo, versionsToSend))
                                    throw new Exception();
                            }
                            else if (command.Type == NetCommandType.PushObjectQuery)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Write))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Client asking about objects on the server...");
                                SharedNetwork.ProcesPushObjectQuery(sharedInfo);
                            }
                            else if (command.Type == NetCommandType.PushBranch)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Write))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Client attempting to send branch data...");
                                SharedNetwork.ReceiveBranches(sharedInfo);
                            }
                            else if (command.Type == NetCommandType.PushVersions)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Write))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Client attempting to send version data...");
                                SharedNetwork.ReceiveVersions(sharedInfo);
                            }
                            else if (command.Type == NetCommandType.PushHead)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Write))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Determining head information.");
                                string errorData;
                                lock (ws)
                                {
                                    clientInfo.SharedInfo.Workspace.RunLocked(() =>
                                    {
                                        try
                                        {
                                            clientInfo.SharedInfo.Workspace.BeginDatabaseTransaction();
                                            if (!SharedNetwork.ImportBranchJournal(clientInfo.SharedInfo, false))
                                            {
                                                clientInfo.SharedInfo.Workspace.RollbackDatabaseTransaction();
                                                return false;
                                            }
                                            if (AcceptHeads(clientInfo, ws, out errorData))
                                            {
                                                ImportVersions(ws, clientInfo);
                                                clientInfo.SharedInfo.Workspace.CommitDatabaseTransaction();
                                                ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.AcceptPush }, ProtoBuf.PrefixStyle.Fixed32);
                                                return true;
                                            }
                                            else
                                                ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.RejectPush, AdditionalPayload = errorData }, ProtoBuf.PrefixStyle.Fixed32);
                                            clientInfo.SharedInfo.Workspace.RollbackDatabaseTransaction();
                                            return false;
                                        }
                                        catch
                                        {
                                            clientInfo.SharedInfo.Workspace.RollbackDatabaseTransaction();
                                            return false;
                                        }
                                    }, false);
                                }
                            }
                            else if (command.Type == NetCommandType.SynchronizeRecords)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Read))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Received {0} versions in version pack, but need {1} records to commit data.", sharedInfo.PushedVersions.Count, sharedInfo.UnknownRecords.Count);
                                Printer.PrintDiagnostics("Beginning record synchronization...");
                                if (sharedInfo.UnknownRecords.Count > 0)
                                {
                                    Printer.PrintDiagnostics("Requesting record metadata...");
                                    SharedNetwork.RequestRecordMetadata(clientInfo.SharedInfo);
                                    Printer.PrintDiagnostics("Requesting record data...");
                                    SharedNetwork.RequestRecordData(sharedInfo);
                                    if (!sharedInfo.Workspace.RunLocked(() =>
                                    {
                                        return SharedNetwork.ImportRecords(sharedInfo);
                                    }, false))
                                    {
                                        throw new Exception("Unable to import records!");
                                    }
                                }
                                ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Synchronized }, ProtoBuf.PrefixStyle.Fixed32);
                            }
                            else if (command.Type == NetCommandType.FullClone)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Read))
                                    throw new Exception("Access denied.");
                                ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Acknowledge, Identifier = (int)ws.DatabaseVersion }, ProtoBuf.PrefixStyle.Fixed32);
                                command = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(stream, ProtoBuf.PrefixStyle.Fixed32);
                                if (command.Type == NetCommandType.Acknowledge)
                                {
                                    bool accept = false;
                                    BackupInfo backupInfo = null;
                                    lock (domainInfo)
                                    {
                                        string backupKey = ws.LastVersion + "-" + ws.LastBranch + "-" + ws.BranchJournalTipID.ToString();
                                        backupInfo = domainInfo.Backup;
                                        if (backupKey != backupInfo.Key)
                                        {
                                            Printer.PrintMessage("Backup key out of date for domain DB[{0}] - {1}", domainInfo.Directory, backupKey);
                                            if (System.Threading.Interlocked.Decrement(ref backupInfo.Refs) == 0)
                                                backupInfo.Backup.Delete();
                                            backupInfo = new BackupInfo();
                                            domainInfo.Backup = backupInfo;
                                            var directory = new System.IO.DirectoryInfo(System.IO.Path.Combine(ws.AdministrationFolder.FullName, "backups"));
                                            directory.Create();
                                            backupInfo.Backup = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, System.IO.Path.GetRandomFileName()));
                                            if (ws.BackupDB(backupInfo.Backup))
                                            {
                                                System.Threading.Interlocked.Increment(ref backupInfo.Refs);
                                                accept = true;
                                                backupInfo.Key = backupKey;
                                            }
                                        }
                                        else
                                        {
                                            accept = true;
                                        }

                                        if (accept)
                                            System.Threading.Interlocked.Increment(ref backupInfo.Refs);
                                    }
                                    if (accept)
                                    {
                                        Printer.PrintDiagnostics("Backup complete. Sending data.");
                                        byte[] blob = new byte[256 * 1024];
                                        long filesize = backupInfo.Backup.Length;
                                        long position = 0;
                                        using (System.IO.FileStream reader = backupInfo.Backup.OpenRead())
                                        {
                                            while (true)
                                            {
                                                long remainder = filesize - position;
                                                int count = blob.Length;
                                                if (count > remainder)
                                                    count = (int)remainder;
                                                reader.Read(blob, 0, count);
                                                position += count;
                                                Printer.PrintDiagnostics("Sent {0}/{1} bytes.", position, filesize);
                                                if (count == remainder)
                                                {
                                                    Utilities.SendEncrypted(sharedInfo, new DataPayload()
                                                    {
                                                        Data = blob.Take(count).ToArray(),
                                                        EndOfStream = true
                                                    });
                                                    break;
                                                }
                                                else
                                                {
                                                    Utilities.SendEncrypted(sharedInfo, new DataPayload()
                                                    {
                                                        Data = blob,
                                                        EndOfStream = false
                                                    });
                                                }
                                            }
                                        }
                                        ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Acknowledge }, ProtoBuf.PrefixStyle.Fixed32);
                                        lock (domainInfo)
                                        {
                                            if (System.Threading.Interlocked.Decrement(ref backupInfo.Refs) == 0)
                                                backupInfo.Backup.Delete();
                                        }
                                    }
                                    else
                                    {
                                        Utilities.SendEncrypted<DataPayload>(sharedInfo, new DataPayload() { Data = new byte[0], EndOfStream = true });
                                        ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Error }, ProtoBuf.PrefixStyle.Fixed32);
                                    }
                                }
                            }
                            else
                            {
                                Printer.PrintDiagnostics("Client sent invalid command: {0}", command.Type);
                                throw new Exception();
                            }
                        }
                    }
                    else
                    {
                        Network.StartTransaction startSequence = Network.StartTransaction.CreateRejection();
                        Printer.PrintDiagnostics("Rejecting client due to protocol mismatch.");
                        ProtoBuf.Serializer.SerializeWithLengthPrefix<Network.StartTransaction>(stream, startSequence, ProtoBuf.PrefixStyle.Fixed32);
                        return;
                    }
                }
                catch (Exception e)
                {
                    Printer.PrintDiagnostics("Client was a terrible person, because: {0}", e);
                }
                finally
                {
                    if (ws != null)
                        ws.Dispose();
                }
            }

            Printer.PrintDiagnostics("Ended client processor task!");
        }
        private static Microsoft.Exchange.Data.Directory.Management.DomainState GetDomainStateFromDomainInfo(DomainInfo domainInfo)
        {
            if (domainInfo != null)
            {
                switch (domainInfo.DomainState)
                {
                case Microsoft.Exchange.Management.ManageDelegation1.DomainState.PendingActivation:
                    return(Microsoft.Exchange.Data.Directory.Management.DomainState.PendingActivation);

                case Microsoft.Exchange.Management.ManageDelegation1.DomainState.Active:
                    return(Microsoft.Exchange.Data.Directory.Management.DomainState.Active);

                case Microsoft.Exchange.Management.ManageDelegation1.DomainState.PendingRelease:
                    return(Microsoft.Exchange.Data.Directory.Management.DomainState.PendingRelease);
                }
            }
            return(Microsoft.Exchange.Data.Directory.Management.DomainState.Unknown);
        }
Exemplo n.º 31
0
 public ReturnMethod DeleteHostingDomain(DomainInfo model)
 {
     return(this.Call <ReturnMethod, DomainInfo>(model, "DeleteHostingDomain"));
 }
Exemplo n.º 32
0
 public Domain AddDomain(Authentication authentication, DomainInfo domainInfo)
 {
     return(this.Domains.AddDomain(authentication, domainInfo));
 }
Exemplo n.º 33
0
        private void TestDomainInfo()
        {
            var domainInfo = new DomainInfo("example.ca") { Password = "******", Hosts = "all" };

            domainInfo.ToXml().Save(Console.OpenStandardOutput());

        }
Exemplo n.º 34
0
        private void CiraTecnicalTest()
        {
            var tcpTransport = new TcpTransport("epp.test.cira.ca", 700, new X509Certificate("cert.pfx", "password"), true);

            var service = new Service(tcpTransport);

            //1. SSL connection establishment
            Console.WriteLine("TEST: 1");
            service.Connect();

            //2. EPP <login> command with your ‘a’ account
            Console.WriteLine("TEST: 2");
            var logingCmd = new Login("username", "password");

            var response = service.Execute(logingCmd);

            PrintResponse(response);

            //3. Using the correct EPP call, get the latest CIRA Registrant Agreement
            Console.WriteLine("TEST: 3");
            var agreementCmd = new GetAgreement();

            var getAgreementResponse = service.Execute(agreementCmd);

            var agreementVersion = getAgreementResponse.AgreementVersion;
            var agreementText = getAgreementResponse.Agreement;
            var agreementLanguage = getAgreementResponse.Language;

            PrintResponse(response);
            Console.WriteLine("Agreement Version:{0}", agreementVersion);
            /*
             4. Create a Registrant contact using: 
                -the same ID as your Registrar Number prefixed with the word ‘rant’ (e.g. rant75)
                -CPR category CCT
                -Full postal information, phone number, fax number, and email address
                -Agreed to latest CIRA Registrant Agreement version
             */
            Console.WriteLine("TEST: 4");
            var registrantContact = new Contact("rant" + registrarNumber,
                "Registrant Step Four", "Example Inc.",
                "Toronto", "301 La Fanfan Ave.", "ON", "M5V 3T1", "CA",
                "*****@*****.**",
                new Telephone { Value = "+1.6478913606", Extension = "333" },
                new Telephone { Value = "+1.6478913607" });


            var registrantContactCmd = new CiraContactCreate(registrantContact);

            registrantContactCmd.CprCategory = CiraCprCategories.CCT;
            registrantContactCmd.AgreementVersion = agreementVersion;
            registrantContactCmd.AggreementValue = "Y";
            registrantContactCmd.Language = "en";
            registrantContactCmd.OriginatingIpAddress = "127.0.0.1";
            registrantContactCmd.CreatedByResellerId = registrarNumber;

            var response1 = service.Execute(registrantContactCmd);

            PrintResponse(response1);

            /*
             5. Create an administrative contact
             -the same ID as your Registrar Number prefixed with the word ‘admin’ (e.g. admin75)
             -using all mandatory elements required for a Canadian administrative contact
             -omit CPR category (he have not agreed to the CIRA agreement)
            */
            Console.WriteLine("TEST: 5");
            var adminContact = new Contact("admin" + registrarNumber,
               "Administrative Step Five", "Example Inc.",
               "Toronto", "301 La Fanfan Ave.", "ON", "M5V 3T1", "CA",
               "*****@*****.**",
               new Telephone { Value = "+1.6478913606", Extension = "333" },
               new Telephone { Value = "+1.6478913607" });

            var adminContactCmd = new CiraContactCreate(adminContact);

            adminContactCmd.CprCategory = null;
            adminContactCmd.AgreementVersion = null;
            adminContactCmd.AggreementValue = null;
            adminContactCmd.Language = "en";
            adminContactCmd.OriginatingIpAddress = "127.0.0.1";
            adminContactCmd.CreatedByResellerId = registrarNumber;

            const string adminContactId = "admin" + registrarNumber;

            var loginresponse = service.Execute(adminContactCmd);

            PrintResponse(loginresponse);

            //6. Get information for the contact created in operation #4
            Console.WriteLine("TEST: 6");
            var getContactInfo = new ContactInfo(registrantContact.Id);

            var contactInfoResponse = service.Execute(getContactInfo);

            PrintResponse(contactInfoResponse);

            //7. Do a Registrant transfer for domain <registrar number>-3.ca to the Registrant created in operation #4
            Console.WriteLine("TEST: 7");

            //NOTE: registrant transfers are domain updates

            var registrantTransferCmd = new DomainUpdate(registrarNumber + "-3.ca");
            //var registrantTransferCmd = new DomainUpdate("3406310-4.ca");

            var domainChange = new DomainChange { RegistrantContactId = registrantContact.Id };

            registrantTransferCmd.DomainChange = domainChange;

            var response2 = service.Execute(registrantTransferCmd);

            PrintResponse(response2);

            //8. Update the contact created in operation #4 to no longer have a fax number
            Console.WriteLine("TEST: 8");
            var contactUpdateCmd = new ContactUpdate(registrantContact.Id);

            var contactChange = new ContactChange(registrantContact);

            contactChange.Fax = new Telephone("", "");

            contactUpdateCmd.ContactChange = contactChange;

            //NOTE:the docs say that the cpr category is update for domain contact
            //but they show a sample of a contact update request that does not include the extension
            //NOTE: Organization cannot be entered when CPR Category indicates a non individual - see documentation
            contactUpdateCmd.Extensions.Add(new CiraContactUpdateExtension { CprCategory = CiraCprCategories.CCT });

            var response3 = service.Execute(contactUpdateCmd);

            PrintResponse(response3);

            //8.1 Get contact info and check the fax number dissapeared
            var contactInfoCmd1 = new ContactInfo(registrantContact.Id);

            var contactInfoResponse1 = service.Execute(contactInfoCmd1);

            PrintResponse(contactInfoResponse1);

            //9. Do a domain:check on <registrar number>a.ca
            Console.WriteLine("TEST: 9");
            const string domainStep10 = registrarNumber + "a.ca";

            var domainCheckCmd = new DomainCheck(domainStep10);

            var response4 = service.Execute(domainCheckCmd);

            PrintResponse(response4);

            /*
             10. Create a domain using:
             -a domain name set to <registrar number>a.ca
             -a Registrant who is a Permanent Resident
             -the same administrative contact as the Registrant
             -0 hosts
             -the minimum registration period
            */
            Console.WriteLine("TEST: 10");
            //NOTE: CPR categories CCT and RES where merged into CCR

            //BUG: the registrant needs to be a Permanent Resident
            //TODO: create a new contact that is a permanent resident
            //10.1 
            var registrantContact10 = new Contact("ten" + registrarNumber,
               "Registrant Step Ten", "Example Inc.",
               "Toronto", "301 La Fanfan Ave.", "ON", "M5V 3T1", "CA",
               "*****@*****.**",
               new Telephone { Value = "+1.6478913606", Extension = "333" },
               new Telephone { Value = "+1.6478913607" });


            registrantContactCmd = new CiraContactCreate(registrantContact10);
            registrantContactCmd.CprCategory = CiraCprCategories.RES;
            registrantContactCmd.AgreementVersion = agreementVersion;
            registrantContactCmd.AggreementValue = "Y";
            registrantContactCmd.OriginatingIpAddress = "127.0.0.1";
            registrantContactCmd.Language = "en";
            registrantContactCmd.CreatedByResellerId = registrarNumber;

            //ContactCreate.MakeContact(registrantContact10,  agreementVersion, "Y", "127.0.0.1", "en", registrarNumber);

            var response5 = service.Execute(registrantContactCmd);

            PrintResponse(response5);

            //10.2
            var domainCreateCmd = new DomainCreate(domainStep10, registrantContact10.Id);

            domainCreateCmd.DomainContacts.Add(new DomainContact(registrantContact10.Id, "admin"));

            //NOTE: password is compulsory
            domainCreateCmd.Password = "******";

            var response6 = service.Execute(domainCreateCmd);

            PrintResponse(response6);

            /*11. Do a host:check on hosts <registrar number>.example.com and <registrar number>.example.net*/
            Console.WriteLine("TEST: 11");
            var hostCheckCmd = new HostCheck(new List<string> { registrarNumber + ".example.com", registrarNumber + ".example.net" });

            var response7 = service.Execute(hostCheckCmd);

            PrintResponse(response7);

            /*
             12. Create 2 hosts with the following name formats:
             <registrar number>.example.com
             <registrar number>.example.net
             */
            Console.WriteLine("TEST: 12");
            //CIRA only creates a host at a time

            //12.1
            var hostCreateCmd = new HostCreate(new Host(registrarNumber + ".example.com"));

            var response8 = service.Execute(hostCreateCmd);

            PrintResponse(response8);

            //12.2
            hostCreateCmd = new HostCreate(new Host(registrarNumber + ".example.net"));

            var response9 = service.Execute(hostCreateCmd);

            PrintResponse(response9);

            /*
             13. Create a domain using:
             -a domain name set to <registrar number>b.ca
             -the pre-populated contact id <registrar number> as the administrative contact
             -a Registrant who is a Corporation
             -2 hosts created in operation #12 <- the nameservers
             -a maximum registration period (10 years)
             */
            Console.WriteLine("TEST: 13");
            //13.1 - Create a corporation

            //If it is a corporation you can not provide company name
            var corporation = new Contact("corp" + registrarNumber, "Acme Corp.", null, "Toronto",
                                          "some where 22", "ON", "M6G2L1", "CA", "*****@*****.**",
                                          new Telephone("+1.1234567890", null), new Telephone("+1.1234567890", null));

            //var createCorporationContactCmd = ContactCreate.MakeContact(corporation, CiraCprCategories.CCO, agreementVersion, "Y", "127.0.0.1", "en", registrarNumber);

            var createCorporationContactCmd = new CiraContactCreate(corporation);
            createCorporationContactCmd.CprCategory = CiraCprCategories.CCO;
            createCorporationContactCmd.AgreementVersion = agreementVersion;
            createCorporationContactCmd.AggreementValue = "Y";
            createCorporationContactCmd.OriginatingIpAddress = "127.0.0.1";
            createCorporationContactCmd.Language = "en";
            createCorporationContactCmd.CreatedByResellerId = registrarNumber;

            var response10 = service.Execute(createCorporationContactCmd);

            PrintResponse(response10);

            /* var domainUpdateCmd = new DomainUpdate(registrarNumber + "-10.ca");

             domainUpdateCmd.ToRemove.Status.Add(new Status("", "serverDeleteProhibited"));

             response = service.Execute(domainUpdateCmd);

             PrintResponse(response);*/

            //13.2 - Create the domain

            //var createDomainCmd = new DomainCreate(registrarNumber + "b.ca", corporation.Id);
            var createDomainCmd = new DomainCreate(registrarNumber + "b.ca", "corp" + registrarNumber);

            createDomainCmd.Period = new DomainPeriod(10, "y");

            //NOTE:The administrative or technical contact must be an Individual
            //BUG: admin contact needs be the prepopulated 3406310
            createDomainCmd.DomainContacts.Add(new DomainContact(registrarNumber, "admin"));

            //NOTE:Create the host on the Registry system before you assign it to a domain
            createDomainCmd.NameServers.Add(registrarNumber + ".example.com");
            createDomainCmd.NameServers.Add(registrarNumber + ".example.net");

            createDomainCmd.Password = "******";

            var response11 = service.Execute(createDomainCmd);

            PrintResponse(response11);

            /*
             14. Create a domain using: 
             - a domain name set to <registrar number>c.ca
             - a Registrant who is an Association
             - the administrative contact set to the contact created in operation #5
             - maximum number of technical contacts assigned to it (max is 3)
            - 0 hosts
            - a 2-year term
             */
            Console.WriteLine("TEST: 14");
            var association = new Contact("assoc" + registrarNumber, "Beer Producers Association", null, "Toronto",
                                          "some where 22", "ON", "M6G2L1", "CA", "*****@*****.**",
                                          new Telephone("+1.1234567890", null), new Telephone("+1.1234567890", null));

            //var createAssociationContactCmd = ContactCreate.MakeContact(association, CiraCprCategories.ASS, agreementVersion, "Y", "127.0.0.1", "en", registrarNumber);

            var createAssociationContactCmd = new CiraContactCreate(association);
            createAssociationContactCmd.CprCategory = CiraCprCategories.ASS;
            createAssociationContactCmd.AgreementVersion = agreementVersion;
            createAssociationContactCmd.AggreementValue = "Y";
            createAssociationContactCmd.OriginatingIpAddress = "127.0.0.1";
            createAssociationContactCmd.Language = "en";
            createAssociationContactCmd.CreatedByResellerId = registrarNumber;

            var response12 = service.Execute(createAssociationContactCmd);

            PrintResponse(response12);

            //tech1
            var tech1 = new Contact("tech1" + registrarNumber, "Technician #1", "Beer Producers Association", "Toronto",
                                          "some where 22", "ON", "M6G2L1", "CA", "*****@*****.**",
                                          new Telephone("+1.1234567890", null), new Telephone("+1.1234567890", null));

            //var createTech1ContactCmd = ContactCreate.MakeContact(tech1, CiraCprCategories.CCT, agreementVersion, "Y", "127.0.0.1", "en", registrarNumber);

            var createTech1ContactCmd = new CiraContactCreate(tech1);
            createTech1ContactCmd.CprCategory = CiraCprCategories.CCT;
            createTech1ContactCmd.AgreementVersion = agreementVersion;
            createTech1ContactCmd.AggreementValue = "Y";
            createTech1ContactCmd.OriginatingIpAddress = "127.0.0.1";
            createTech1ContactCmd.Language = "en";
            createTech1ContactCmd.CreatedByResellerId = registrarNumber;

            var response13 = service.Execute(createTech1ContactCmd);

            PrintResponse(response13);

            //tech2
            var tech2 = new Contact("tech2" + registrarNumber, "Technician #2", "Beer Producers Association", "Toronto",
                                          "some where 22", "ON", "M6G2L1", "CA", "*****@*****.**",
                                          new Telephone("+1.1234567890", null), new Telephone("+1.1234567890", null));

            //var createTech2ContactCmd = ContactCreate.MakeContact(tech2, CiraCprCategories.CCT, agreementVersion, "Y", "127.0.0.1", "en", registrarNumber);

            var createTech2ContactCmd = new CiraContactCreate(tech2);
            createTech2ContactCmd.CprCategory = CiraCprCategories.CCT;
            createTech2ContactCmd.AgreementVersion = agreementVersion;
            createTech2ContactCmd.AggreementValue = "Y";
            createTech2ContactCmd.OriginatingIpAddress = "127.0.0.1";
            createTech2ContactCmd.Language = "en";
            createTech2ContactCmd.CreatedByResellerId = registrarNumber;

            var response14 = service.Execute(createTech2ContactCmd);

            PrintResponse(response14);

            //tech1
            var tech3 = new Contact("tech3" + registrarNumber, "Technician #3", "Beer Producers Association", "Toronto",
                                          "some where 22", "ON", "M6G2L1", "CA", "*****@*****.**",
                                          new Telephone("+1.1234567890", null), new Telephone("+1.1234567890", null));

            //var createTech3ContactCmd = ContactCreate.MakeContact(tech3, CiraCprCategories.CCT, agreementVersion, "Y", "127.0.0.1", "en", registrarNumber);

            var createTech3ContactCmd = new CiraContactCreate(tech3);
            createTech3ContactCmd.CprCategory = CiraCprCategories.CCT;
            createTech3ContactCmd.AgreementVersion = agreementVersion;
            createTech3ContactCmd.AggreementValue = "Y";
            createTech3ContactCmd.OriginatingIpAddress = "127.0.0.1";
            createTech3ContactCmd.Language = "en";
            createTech3ContactCmd.CreatedByResellerId = registrarNumber;


            var response15 = service.Execute(createTech3ContactCmd);

            PrintResponse(response15);

            const string step14domain = registrarNumber + "c.ca";

            createDomainCmd = new DomainCreate(step14domain, association.Id);

            createDomainCmd.Period = new DomainPeriod(2, "y");

            createDomainCmd.DomainContacts.Add(new DomainContact(adminContactId, "admin"));

            createDomainCmd.DomainContacts.Add(new DomainContact(tech1.Id, "tech"));
            createDomainCmd.DomainContacts.Add(new DomainContact(tech2.Id, "tech"));
            createDomainCmd.DomainContacts.Add(new DomainContact(tech3.Id, "tech"));

            createDomainCmd.Password = "******";

            var response16 = service.Execute(createDomainCmd);

            PrintResponse(response16);

            /*
             15. Do a host:check for a host which the dot-ca domain name is registered
            */
            Console.WriteLine("TEST: 15");
            hostCheckCmd = new HostCheck("any." + registrarNumber + "b.ca");

            var response17 = service.Execute(hostCheckCmd);

            PrintResponse(response17);

            /*
             16. Create 2 subordinate hosts for the domain created in operation #14:
              - with format ns1.<domain> and ns2.<domain>
              - with IPv4 address information
            */
            Console.WriteLine("TEST: 16");
            var host1 = new Host("ns1." + step14domain);
            host1.Addresses.Add(new HostAddress("127.0.0.1", "v4"));
            var host2 = new Host("ns2." + step14domain);
            host2.Addresses.Add(new HostAddress("127.0.0.2", "v4"));

            var createHostCmd = new HostCreate(host1);

            var response18 = service.Execute(createHostCmd);

            PrintResponse(response18);

            createHostCmd = new HostCreate(host2);

            response18 = service.Execute(createHostCmd);

            PrintResponse(response18);

            /*
             17. Using the correct EPP call, get information on a host
            */
            Console.WriteLine("TEST: 17");
            var hostInfoCmd = new HostInfo(host1.HostName);

            var response19 = service.Execute(hostInfoCmd);

            PrintResponse(response19);

            /*18. Update the domain created in operation #14 such that the hosts created in operation #16 are delegated to the domain explicitly*/
            Console.WriteLine("TEST: 18");
            var domainUpdateCmd = new DomainUpdate(step14domain);

            //NOTE: Nameservers need different IP addresses
            domainUpdateCmd.ToAdd.NameServers = new List<string> { host1.HostName, host2.HostName };

            var response20 = service.Execute(domainUpdateCmd);

            PrintResponse(response20);

            //19. Update host ns1.<domain> created in operation #16 such that an IPv6 address is added
            Console.WriteLine("TEST: 19");
            var hostUpdateCmd = new HostUpdate(host1.HostName);

            var eppHostUpdateAddRemove = new EppHostUpdateAddRemove();

            eppHostUpdateAddRemove.Adresses = new List<HostAddress> { new HostAddress("1080:0:0:0:8:800:2004:17A", "v6") };

            hostUpdateCmd.ToAdd = eppHostUpdateAddRemove;

            var response21 = service.Execute(hostUpdateCmd);
            PrintResponse(response21);

            //20. Update host ns1.<domain> created in operation #16 such that an IPv4 address is removed
            Console.WriteLine("TEST: 20");
            hostUpdateCmd = new HostUpdate(host1.HostName);

            eppHostUpdateAddRemove = new EppHostUpdateAddRemove();

            eppHostUpdateAddRemove.Adresses = new List<HostAddress> { new HostAddress("127.0.0.1", "v4") };

            hostUpdateCmd.ToRemove = eppHostUpdateAddRemove;

            var response22 = service.Execute(hostUpdateCmd);
            PrintResponse(response22);

            //21. Update the status of ns1.<domain> such that it can no longer be updated
            Console.WriteLine("TEST: 21");
            hostUpdateCmd = new HostUpdate(host1.HostName);

            eppHostUpdateAddRemove = new EppHostUpdateAddRemove();

            eppHostUpdateAddRemove.Status = new List<Status> { new Status("", "clientUpdateProhibited") };

            hostUpdateCmd.ToAdd = eppHostUpdateAddRemove;

            response22 = service.Execute(hostUpdateCmd);
            PrintResponse(response22);

            //22. Using the correct EPP call, get information on a domain name without using WHOIS
            Console.WriteLine("TEST: 22");

            //const string domainStep10 = registrarNumber + "a.ca";

            var domainInfoCmd = new DomainInfo(domainStep10);
            var domainInfo = service.Execute(domainInfoCmd);

            PrintResponse(domainInfo);

            //23. Renew the domain created in operation #10 such that the domain’s total length of term becomes 3 years
            Console.WriteLine("TEST: 23");
            var renewCmd = new DomainRenew(domainStep10, domainInfo.Domain.ExDate, new DomainPeriod(2, "y"));

            var response23 = service.Execute(renewCmd);
            PrintResponse(response23);

            /*
             24. Do a Registrar transfer:
             - Domain name <registrar number>X2-1.ca, from your ‘e’ Registrar account 
             - Have the system auto-generate the contacts so that their information is identical to the contacts in the ‘e’ account
             */
            Console.WriteLine("TEST: 24");

            var transferCmd = new CiraDomainTransfer(registrarNumber + "X2-1.ca", null, null, new List<string>());
            //var transferCmd = new DomainTransfer("3406310x2-5.ca", null, null, new List<string>());

            transferCmd.Password = "******";
            var response24 = service.Execute(transferCmd);

            PrintResponse(response24);

            /*25. Do a Registrar transfer:
              - Domain name, <registrar number>X2-2.ca, from your ‘e’ Registrar account
              - Specify the same Registrant, administrative, and technical contacts used for the domain created in operation #14
             */
            Console.WriteLine("TEST: 25");

            //BUG: did not use all the technical contacts.

            transferCmd = new CiraDomainTransfer(registrarNumber + "X2-2.ca", association.Id, adminContactId, new List<string> { tech1.Id, tech2.Id, tech3.Id });
            //transferCmd = new DomainTransfer("3406310x2-10.ca", association.Id, adminContactId, new List<string> { tech1.Id, tech2.Id, tech3.Id });

            //Password is mandatory
            //TODO: find it in the control panel
            transferCmd.Password = "******";
            response24 = service.Execute(transferCmd);

            PrintResponse(response24);

            /*
             26. Do an update to the domain created in operation #14 to change the administrative contact to the pre-populated contact whose id is of format <registrar number>
             */
            Console.WriteLine("TEST: 26");
            domainUpdateCmd = new DomainUpdate(step14domain);

            //remove the previous admin
            domainUpdateCmd.ToRemove.DomainContacts.Add(new DomainContact(adminContactId, "admin"));

            domainUpdateCmd.ToAdd.DomainContacts.Add(new DomainContact(registrarNumber, "admin"));

            var response25 = service.Execute(domainUpdateCmd);

            PrintResponse(response25);

            /*27. Do an update to the status of the domain created in operation #14 such that it cannot be deleted*/
            Console.WriteLine("TEST: 27");
            domainUpdateCmd = new DomainUpdate(step14domain);

            domainUpdateCmd.ToAdd.Status.Add(new Status("", "clientDeleteProhibited"));

            var response26 = service.Execute(domainUpdateCmd);

            PrintResponse(response26);

            /*28. Do an update to the email address of the pre-populated contact whose id is of format <registrar number> to "*****@*****.**" */
            Console.WriteLine("TEST: 28");
            //28.1 get the contact
            //var contactInfoCmd = new ContactInfo("rant" + registrarNumber);
            var contactInfoCmd = new ContactInfo(registrarNumber);

            contactInfoResponse = service.Execute(contactInfoCmd);

            PrintResponse(contactInfoResponse);

            if (contactInfoResponse.Contact != null)
            {

                //28.2 update the email address

                //ASSERT: contactInfoResponse.Contact != null
                contactUpdateCmd = new ContactUpdate(contactInfoResponse.Contact.Id);

                var contactchage = new ContactChange(contactInfoResponse.Contact);

                contactchage.Email = "*****@*****.**";

                contactUpdateCmd.ContactChange = contactchage;

                //the extensions are compulsory
                contactUpdateCmd.Extensions.Add(new CiraContactUpdateExtension { CprCategory = contactInfoResponse.Contact.CprCategory });

                var response27 = service.Execute(contactUpdateCmd);

                PrintResponse(response27);


            }
            else
            {
                Console.WriteLine("Error: contact does not exist?");
            }


            /*
                 29. Do an update to the privacy status for Registrant contact created in operation #4 to now show full detail
            */
            Console.WriteLine("TEST: 29");
            contactUpdateCmd = new ContactUpdate("rant" + registrarNumber);

            //Invalid WHOIS display setting - valid values are PRIVATE or FULL
            contactUpdateCmd.Extensions.Add(new CiraContactUpdateExtension { WhoisDisplaySetting = "FULL" });

            var response28 = service.Execute(contactUpdateCmd);

            PrintResponse(response28);


            /*30. Delete the domain <registrar number>-10.ca*/
            Console.WriteLine("TEST: 30");
            //NOTE:check this domain status

            var deleteDomainCmd = new DomainDelete(registrarNumber + "-10.ca");
            //var deleteDomainCmd = new DomainDelete(registrarNumber + "-9.ca");

            var response29 = service.Execute(deleteDomainCmd);
            PrintResponse(response29);

            /*31. EPP <logout> command*/
            Console.WriteLine("TEST:31");
            var logOutCmd = new Logout();

            service.Execute(logOutCmd);

            /*32. Disconnect SSL connection*/
            Console.WriteLine("TEST: 32");
            service.Disconnect();

            /*33. SSL connection establishment*/
            Console.WriteLine("TEST: 33");
            service.Connect();

            /*34. EPP <login> command with your ‘e’ account*/
            Console.WriteLine("TEST: 34");
            logingCmd = new Login("username", "password");

            response = service.Execute(logingCmd);

            PrintResponse(response);

            /*35. Acknowledge all poll messages*/
            Console.WriteLine("TEST: 35");
            var thereAreMessages = true;

            while (thereAreMessages)
            {
                //request
                var poll = new Poll { Type = PollType.Request };

                var pollResponse = (PollResponse)service.Execute(poll);

                PrintResponse(pollResponse);

                if (!String.IsNullOrEmpty(pollResponse.Id))
                {
                    //acknowledge
                    poll = new Poll { Type = PollType.Acknowledge, MessageId = pollResponse.Id };

                    pollResponse = (PollResponse)service.Execute(poll);

                    PrintResponse(pollResponse);
                }

                Console.WriteLine("Messages left in the queue:" + pollResponse.Count);

                thereAreMessages = pollResponse.Count != 0;
            }

            /*36. EPP <logout> command*/
            Console.WriteLine("TEST: 36");
            logOutCmd = new Logout();

            service.Execute(logOutCmd);


        }