Exemple #1
0
        internal static string GetCalcLibErrorString(string strErrorCode)
        {
            switch (strErrorCode)
            {
            case "0":
                return(SPResource.GetString("CalcLibErrorDiv0", new object[0]));

            case "1":
                return(SPResource.GetString("CalcLibErrorValue", new object[0]));

            case "3":
                return(SPResource.GetString("CalcLibErrorNull", new object[0]));

            case "4":
                return(SPResource.GetString("CalcLibErrorCirc", new object[0]));

            case "5":
                return(SPResource.GetString("CalcLibErrorNum", new object[0]));

            case "6":
                return(SPResource.GetString("CalcLibErrorRef", new object[0]));

            case "7":
                return(SPResource.GetString("CalcLibErrorNA", new object[0]));
            }
            return(SPResource.GetString("CalcLibErrorName", new object[0]));
        }
        private static SPSite CreateSite(SPWebApplication webApp, string dbname, SPSiteSubscription siteSubscription, string webTemplate, string title, string description, string ownerName, string ownerEmail, string quota, string secondaryContactName, string secondaryContactEmail, bool useHostHeaderAsSiteName, uint nLCID, Uri uri, string ownerLogin, string secondaryContactLogin)
        {
            Logger.Write("PROGRESS: Getting content database...");
            SPContentDatabase database = null;

            if (!string.IsNullOrEmpty(dbname))
            {
                foreach (SPContentDatabase tempDB in webApp.ContentDatabases)
                {
                    if (tempDB.Name.ToLower() == dbname.ToLower())
                    {
                        database = tempDB;
                        break;
                    }
                }
                if (database == null)
                {
                    throw new SPException("Content database not found.");
                }
            }

            SPSite site = CreateSite(webApp, siteSubscription, webTemplate, title, description, ownerName, ownerEmail, quota, secondaryContactName, secondaryContactEmail, useHostHeaderAsSiteName, nLCID, uri, ownerLogin, secondaryContactLogin, database);

            if (useHostHeaderAsSiteName && !webApp.IisSettings[SPUrlZone.Default].DisableKerberos)
            {
                Logger.Write(SPResource.GetString("WarnNoDefaultNTLM", new object[0]));
            }

            return(site);
        }
        /// <summary>
        /// Parses the specified URL zone.
        /// </summary>
        /// <param name="strUrlZone">The URL zone.</param>
        /// <returns></returns>
        public static SPUrlZone Parse(string strUrlZone)
        {
            strUrlZone = strUrlZone.Trim().ToLower(CultureInfo.InvariantCulture);
            string str = strUrlZone;

            if (str != null)
            {
                if (str == "default")
                {
                    return(SPUrlZone.Default);
                }
                if (str == "intranet")
                {
                    return(SPUrlZone.Intranet);
                }
                switch (str)
                {
                case "internet":
                    return(SPUrlZone.Internet);

                case "extranet":
                    return(SPUrlZone.Extranet);

                default:
                    if (str == "custom")
                    {
                        return(SPUrlZone.Custom);
                    }
                    break;
                }
            }
            throw new ArgumentException(SPResource.GetString("ZoneNotFound", new object[] { strUrlZone }));
        }
        public virtual void Validate()
        {
            this.m_fIsValid = true;
            Label label = null;

            if (webControl.ErrorMessageLabelControl.Length > 0)
            {
                label = webControl.FindControl(webControl.ErrorMessageLabelControl) as Label;
            }
            if ((webControl.Enabled && (webControl.MaxLength > 0)) && ((webControl.Text != null) && (webControl.Text.Length > webControl.MaxLength)))
            {
                webControl.ErrorMessage = SPHttpUtility.NoEncode(SPResource.GetString("InputLengthGreaterThanMaxLength", new object[] { webControl.MaxLength }));
                this.m_fIsValid         = false;
            }
            if (label != null)
            {
                if (this.m_fIsValid)
                {
                    label.Text = string.Empty;
                }
                else
                {
                    label.Text = SPHttpUtility.HtmlEncode(webControl.ErrorMessage);
                }
            }
        }
Exemple #5
0
        public static SPWorkflowAssociation EnsureWorkflowAssociation(SPWorkflowAssociationCollection collection, Guid workflowBaseId, SPWorkflowAssociationCreator createDelegate, out bool associationUpdated)
        {
            CommonHelper.ConfirmNotNull(collection, "collection");
            CommonHelper.ConfirmNotNull(createDelegate, "createDelegate");
            associationUpdated = false;

            SPWeb targetWeb = collection.ParentWeb;
            SPWorkflowAssociation wfAssoc = collection.GetAssociationByBaseIDSafe(workflowBaseId);

            if (wfAssoc == null)
            {
                SPWorkflowTemplate wfTemplate = targetWeb.WorkflowTemplates[workflowBaseId];
                if (wfTemplate == null)
                {
                    throw new ArgumentOutOfRangeException("workflowBaseId", "Workflow template with the specified base ID does not exist in this site");
                }
                SPList taskList    = EnsureList(targetWeb, SPListTemplateType.Tasks, SPResource.GetString("DefaultWorkflowTaskListName", new object[0]));
                SPList historyList = EnsureList(targetWeb, SPListTemplateType.WorkflowHistory, SPResource.GetString("DefaultWorkflowHistoryListName", new object[0]));
                wfAssoc = createDelegate(wfTemplate, wfTemplate.Name, taskList, historyList);
                collection.Add(wfAssoc);
                associationUpdated = true;
            }
            if (!wfAssoc.Enabled)
            {
                wfAssoc.Enabled = true;
                collection.Update(wfAssoc);
                associationUpdated = true;
            }
            return(wfAssoc);
        }
Exemple #6
0
        /// <summary>
        /// Gets the unused instance id.
        /// </summary>
        /// <param name="preferredInstanceId">The preferred instance id.</param>
        /// <returns></returns>
        private static int GetUnusedInstanceId(int preferredInstanceId)
        {
            Random random = new Random();
            int    num    = 0;
            int    num2   = preferredInstanceId;

            if (num2 < 1)
            {
                num2 = random.Next(1, 0x7fffffff);
            }

            while (true)
            {
                if (++num >= 0x19)
                {
                    throw new InvalidOperationException(SPResource.GetString("CannotFindUnusedInstanceId", new object[0]));
                }
                if (DirectoryEntry.Exists("IIS://localhost/w3svc/" + num2))
                {
                    num2 = random.Next(1, 0x7fffffff);
                }
                else
                {
                    break;
                }
            }
            return(num2);
        }
        private void CompleteTasks(SPListItem item, List <string> doubledUsers)
        {
            foreach (SPWorkflowTask task in item.Tasks)
            {
                XElement xml = XElement.Parse(task.Xml);
                if (doubledUsers.Contains(xml.Attribute("ows_AssignedTo").Value) && task["Outcome"] == null)
                {
                    string taskStatus = SPResource.GetString(new CultureInfo((int)task.Web.Language, false), "WorkflowTaskStatusComplete", new object[0]);
                    task[SPBuiltInFieldId.TaskStatus] = taskStatus;
                    task["Outcome"] = "Canceled";
                    task[SPBuiltInFieldId.Completed]          = true;
                    task[SPBuiltInFieldId.PercentComplete]    = 1;
                    task[SPBuiltInFieldId.ExtendedProperties] = "ows_FieldName_DelegateTo='' ows_FieldName_RequestTo='' ows_FieldName_NewDescription='' ows_FieldName_ConsolidatedComments='Approval (2) started by Peter Dimov on 12/17/2014 4:24 PM Comment: aa' ows_TaskStatus='Approved' ows_FieldName_NewDurationUnits='Day' ows_FieldName_NewSerialTaskDuration='' ows_FieldName_Comments='' ";
                    //task[TaskStatus] = "Approved"
                    task.Update();


                    //Hashtable ht = new Hashtable();
                    //ht["Status"] = "Completed";
                    //ht["Outcome"] = "Canceled";
                    //ht["PercentComplete"] = 1.0f;
                    ////ht["TaskStatus"] = "#";     // Mark the entry as approved

                    //SPWorkflowTask.AlterTask((task as SPListItem), ht, true);
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// Validates the user.
        /// </summary>
        /// <param name="site">The site.</param>
        internal static void ValidateUser(SPSite site)
        {
            if (site == null)
            {
                throw new ArgumentNullException("site");
            }

            bool isSiteAdmin = false;

            using (SPWeb rootWeb = site.RootWeb)
            {
                if ((rootWeb != null) && (rootWeb.CurrentUser != null))
                {
                    isSiteAdmin = rootWeb.CurrentUser.IsSiteAdmin;
                }
            }
            if (isSiteAdmin)
            {
                return;
            }
            try
            {
                isSiteAdmin = SPFarm.Local.CurrentUserIsAdministrator();
            }
            catch
            {
                isSiteAdmin = false;
            }
            if (!isSiteAdmin)
            {
                throw new SPException(SPResource.GetString("AccessDenied", new object[0]));
            }
        }
        protected override int IssueQuery(string search, string groupName, int pageIndex, int pageSize)
        {
            Debug.WriteLine("%%%%%% IssueQuery ->" + search);
            int rows;

            if ((search == null) || (search.Trim().Length == 0))
            {
                PickerDialog.ErrorMessage = SPResource.GetString("PeoplePickerNoQueryTextError", new object[0]);
                return(0);
            }

            ActionPickerDialog   pickerDialog         = (ActionPickerDialog)PickerDialog;
            ActionEntityDataBase actionEntityDataBase = new ActionEntityDataBase(pickerDialog.ExtendedData);
            DataTable            dataTable            = actionEntityDataBase.MatchesTable(search);

            PickerDialog.Results = dataTable;
            rows = dataTable.Rows.Count;
            PickerDialog.ResultControl.PageSize = rows;

            if (rows == 0)
            {
                PickerDialog.ErrorMessage = SPResource.GetString("PeoplePickerNoSearchResultError", new object[0]);
            }

            Debug.WriteLine(rows);

            return(rows);
        }
 private void AddDropImage(SPFieldLookup field)
 {
     TextField = new TextBox();
     TextField.Attributes.Add("choices", Choices);
     TextField.Attributes.Add("match", string.Empty);
     TextField.Attributes.Add("onkeydown", "CoreInvoke('HandleKey')");
     TextField.Attributes.Add("onkeypress", "CoreInvoke('HandleChar')");
     TextField.Attributes.Add("onfocusout", "CoreInvoke('HandleLoseFocus')");
     TextField.Attributes.Add("onchange", "CoreInvoke('HandleChange')");
     TextField.Attributes.Add("class", "ms-lookuptypeintextbox");
     TextField.Attributes.Add("title", SPHttpUtility.HtmlEncode(field.Title));
     TextField.TabIndex             = TabIndex;
     TextField.Attributes["optHid"] = HiddenFieldName;
     SpanLiteral = new Literal
     {
         Text = "<span style=\"vertical-align:middle\">"
     };
     SpanClosingLiteral = new Literal
     {
         Text = "</span>"
     };
     Controls.Add(SpanLiteral);
     Controls.Add(TextField);
     TextField.Attributes.Add("opt", "_Select");
     DropImage          = new Image();
     DropImage.ImageUrl = "/_layouts/images/dropdown.gif";
     DropImage.Attributes.Add("alt", SPResource.GetString("LookupWordWheelDropdownAlt", new object[0]));
     DropImage.Attributes.Add("style", "vertical-align:middle;");
     Controls.Add(DropImage);
     Controls.Add(SpanClosingLiteral);
 }
 private bool ValidateDirectory(string path)
 {
     if (string.IsNullOrEmpty(path))
     {
         return(false);
     }
     try
     {
         FileInfo info = new FileInfo(path);
         if (!info.Directory.Exists)
         {
             throw new DirectoryNotFoundException();
         }
         switch (info.Name[info.Name.Length - 1])
         {
         case '\\':
         case '/':
             throw new SPException(SPResource.GetString("StsadmReqFileName", new object[0]));
         }
     }
     catch
     {
         return(false);
     }
     return(true);
 }
        private void AddThrottledControls()
        {
            var    maxItemsPerThrottledOperation = Web.Site.WebApplication.MaxItemsPerThrottledOperation;
            string throttleMessage = base.Field.Required
                ? throttleMessage = SPResource.GetString(
                "RequiredLookupThrottleMessage",
                new object[]
            {
                maxItemsPerThrottledOperation.ToString(CultureInfo.InvariantCulture)
            })
                : throttleMessage = SPResource.GetString(
                "LookupThrottleMessage",
                new object[]
            {
                maxItemsPerThrottledOperation.ToString(CultureInfo.InvariantCulture)
            });

            ThrottleMessageLiteral = new Literal
            {
                Text = SPHttpUtility.HtmlEncode(throttleMessage)
            };
            SpanLiteral = new Literal
            {
                Text = "<span style=\"vertical-align:middle\">"
            };
            SpanClosingLiteral = new Literal
            {
                Text = "</span>"
            };
            Controls.Add(SpanLiteral);
            Controls.Add(ThrottleMessageLiteral);
            Controls.Add(SpanClosingLiteral);
        }
        protected override void OnLoad(EventArgs e)
        {
            if (this.IsCSR && !this.IsRibbon)
            {
                this.Context.Response.ContentType = "application/json";
                HttpContext current = HttpContext.Current;
                if (((current != null) && (current.Request != null)) && !current.Request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
                {
                    throw new UnauthorizedAccessException(SPResource.GetString(CultureInfo.CurrentCulture, "JsonOnGetNotAllowed", new object[0]));
                }
            }

            bool flag = true;

            try
            {
                flag = this.Execute(this.Cmd);
            }
            catch (Exception ex)
            {
                //string str = string.Format(CultureInfo.InvariantCulture, "<div class=\"{0}\">{1}</div>", new string[] { "ms-vb", SPResource.GetString("CallbackDataBadJSONText", new object[0]) }) + "<br/><br/>" + SPHttpUtility.HtmlEncode(SPResource.GetString("ErrorPageRequestGuid", new object[0])) + "<br/>";
                string str = string.Format(CultureInfo.InvariantCulture, "<div class=\"{0}\">{1}</div>", new string[] { "ms-vb", ex.Message }) + "<br/><br/>StackTrace: " + ex.StackTrace + "<br/>";
                base.Response.StatusCode = 0x259;
                base.Response.Write(str);
            }

            if (flag)
            {
                base.Response.Flush();
                base.Response.End();
            }
        }
Exemple #14
0
        public override bool Validate(string str)
        {
            if (base.Validate(str))
            {
                try
                {
                    FileInfo info = new FileInfo(str);
                    if (info.Directory.Exists)
                    {
                        if (info.Name.EndsWith("\\") || info.Name.EndsWith("/"))
                        {
                            ErrorInfo = "Filename not specified";
                            throw new SPException(SPResource.GetString("StsadmReqFileName", new object[0]));
                        }

                        return(true);
                    }
                    else
                    {
                        ErrorInfo = "Directory not found";
                        throw new DirectoryNotFoundException();
                    }
                }
                catch
                {
                    return(false);
                }
            }
            return(false);
        }
Exemple #15
0
        static void Main(string[] args)
        {
            StringDictionary keyValues = null;
            
            if (ParseInput(args, out keyValues) != 0)
            {
                Console.WriteLine(SPResource.GetString("CommandLineError", new object[0]));
                PrintUsage();
                return;
            }

            if (keyValues.ContainsKey("help"))
            {
                PrintUsage();
                return;
            }

            if (keyValues.ContainsKey("o"))
            {
                RunOperation(keyValues);
                return;
            }

            PrintUsage();

        }
Exemple #16
0
        private static void UpdateCurrentComposedLookItem(SPWeb web, ComposedLook composedLook)
        {
            var catalog = web.GetCatalog(SPListTemplateType.DesignCatalog);
            var items   = catalog.GetItems(new SPQuery
            {
                RowLimit       = 1u,
                Query          = "<Where><Eq><FieldRef Name='DisplayOrder'/><Value Type='Number'>0</Value></Eq></Where>",
                ViewFields     = "<FieldRef Name='DisplayOrder'/>",
                ViewFieldsOnly = true
            });

            // Delete current composed look item
            if (items.Count == 1)
            {
                items[0].Delete();
            }

            // Create the new composed look item
            var item = catalog.AddItem();

            item[BuiltInFields.DisplayOrderName]  = 0;
            item[SPBuiltInFieldId.Name]           = SPResource.GetString(web.UICulture, "DesignGalleryCurrentItemName");
            item[SPBuiltInFieldId.Title]          = SPResource.GetString(web.UICulture, "DesignGalleryCurrentItemName");
            item[BuiltInFields.MasterPageUrlName] = HttpUtility.UrlDecode(new Uri(composedLook.MasterPagePath.Url).AbsolutePath);
            item[BuiltInFields.ThemeUrlName]      = HttpUtility.UrlDecode(new Uri(composedLook.ThemePath.Url).AbsolutePath);
            item[BuiltInFields.ImageUrlName]      = composedLook.ImagePath == null ? string.Empty : HttpUtility.UrlDecode(new Uri(composedLook.ImagePath.Url).AbsolutePath);
            item[BuiltInFields.FontSchemeUrlName] = HttpUtility.UrlDecode(new Uri(composedLook.FontSchemePath.Url).AbsolutePath);
            item.Update();
        }
 internal void OutputSucceedMessage()
 {
     if (this.m_bTopLevelOperation)
     {
         Console.WriteLine(SPResource.GetString("OperationSuccess", new object[0]));
         Console.WriteLine();
     }
 }
Exemple #18
0
 private static string GetFormattedErrorValue(string strType, string strData)
 {
     if (strType == "ERROR")
     {
         return(GetCalcLibErrorString(strData));
     }
     return(SPHttpUtility.HtmlEncode(SPResource.GetString("CalcLibErrorName", new object[0])));
 }
Exemple #19
0
        /// <summary>
        /// Used for data serialization logic and for field validation logic that is specific to a custom field type to convert the field value object into a validated, serialized string.
        /// </summary>
        /// <param name="value">An object that represents the value object to convert.</param>
        /// <returns>
        /// A string that serializes the value object.
        /// </returns>
        public override string GetValidatedString(object value)
        {
            if (string.IsNullOrEmpty(value.ToString()) && this.Required)
            {
                throw new SPFieldValidationException(SPResource.GetString("MissingRequiredField", new object[0]));
            }

            return(base.GetValidatedString(value));
        }
 public override void Validate()
 {
     IsValid = true;
     if (Field.Required && SelectedItems.Count == 0)
     {
         IsValid      = false;
         ErrorMessage = SPResource.GetString("MissingRequiredField", new object[0]);
     }
 }
 private void ValidateInputValues()
 {
     if ((!this.Latitude.HasValue || this.Longitude.HasValue) && (this.Latitude.HasValue || !this.Longitude.HasValue) || (!this.IsValid || this.Field.Required))
     {
         return;
     }
     this.IsValid      = false;
     this.ErrorMessage = SPResource.GetString(Thread.CurrentThread.CurrentCulture, "GeolocationAllValues");
 }
Exemple #22
0
        public override string GetValidatedString(object value)
        {
            if (value == null)
            {
                throw new SPFieldValidationException(SPResource.GetString("MissingRequiredField", new object[0]));
            }

            return(base.GetValidatedString(value));
        }
 public override void Validate()
 {
     IsValid = true;
     if (Field.Required && string.IsNullOrEmpty(Convert.ToString(Value)))
     {
         IsValid      = false;
         ErrorMessage = SPResource.GetString("MissingRequiredField", new object[0]);
     }
 }
        /// <summary>
        /// Activates or deactivates the web application scoped feature.
        /// </summary>
        /// <param name="activate">if set to <c>true</c> [activate].</param>
        /// <param name="featureId">The feature id.</param>
        /// <param name="urlScope">The URL scope.</param>
        /// <param name="force">if set to <c>true</c> [force].</param>
        /// <param name="ignoreNonActive">if set to <c>true</c> [ignore non active].</param>
        /// <returns></returns>
        public SPFeature ActivateDeactivateFeatureAtWebApplication(bool activate, Guid featureId, string urlScope, bool force, bool ignoreNonActive)
        {
            SPWebApplication application = SPWebApplication.Lookup(new Uri(urlScope));

            if (application == null)
            {
                throw new FileNotFoundException(SPResource.GetString("WebApplicationLookupFailed", new object[] { urlScope }));
            }
            return(ActivateDeactivateFeatureAtWebApplication(application, featureId, activate, force, ignoreNonActive));
        }
        /// <summary>
        /// Validates the specified key values.
        /// </summary>
        /// <param name="keyValues">The key values.</param>
        public virtual void Validate(StringDictionary keyValues)
        {
            string strMessage = null;

            foreach (string current in keyValues.Keys)
            {
                if (current != "o" && Params[current] == null)
                {
                    strMessage += string.Format("Command line error. Invalid parameter: {0}.\r\n", current);
                }
            }
            if (strMessage != null)
            {
                throw new SPSyntaxException(strMessage);
            }

            foreach (SPParam param in Params)
            {
                if (param.Enabled)
                {
                    if (param.IsRequired && !param.UserTypedIn)
                    {
                        strMessage += SPResource.GetString("MissRequiredArg", new object[] { param.Name }) + "\r\n";
                    }
                }
            }
            if (strMessage != null)
            {
                throw new SPSyntaxException(strMessage);
            }

            foreach (SPParam param in Params)
            {
                if (param.Enabled)
                {
                    if (param.UserTypedIn && !param.Validate())
                    {
                        strMessage += SPResource.GetString("InvalidArg", new object[] { param.Name });
                        if (!string.IsNullOrEmpty(param.ErrorInfo))
                        {
                            strMessage += string.Format(" ({0})", param.ErrorInfo);
                        }

                        if (!string.IsNullOrEmpty(param.HelpMessage))
                        {
                            strMessage += "\r\n\t" + param.HelpMessage + "\r\n";
                        }
                    }
                }
            }
            if (strMessage != null)
            {
                throw new SPSyntaxException(strMessage);
            }
        }
Exemple #26
0
        protected void SetDeploymentSettings(SPDeploymentSettings settings)
        {
            string filePath;

            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            settings.CommandLineVerbose  = this.Verbose;
            settings.HaltOnNonfatalError = (bool)this.HaltOnError;
            settings.HaltOnWarning       = (bool)this.HaltOnWarning;
            //settings.WarnOnUsingLastMajor = true;
            settings.FileCompression = !NoFileCompression.IsPresent;
            string filename = string.Empty;

            if (!NoFileCompression.IsPresent)
            {
                SplitPathFile(this.Path, out filePath, out filename);
                settings.FileLocation = filePath;
                settings.BaseFileName = filename;
            }
            else
            {
                settings.FileLocation = filePath = this.Path;
            }
            if (!NoLogFile.IsPresent)
            {
                string logFileName;
                if (this is SPCmdletExport)
                {
                    logFileName = "export.log";
                }
                else
                {
                    logFileName = "import.log";
                }
                if (NoFileCompression.IsPresent)
                {
                    settings.LogFilePath = System.IO.Path.Combine(settings.FileLocation, filename + logFileName);
                }
                else
                {
                    settings.LogFilePath = System.IO.Path.Combine(settings.FileLocation, filename + "." + logFileName);
                }
                bool fileExists = File.Exists(settings.LogFilePath) && !(this is SPCmdletImportWeb2);
                if ((!this.Force.IsPresent) && fileExists)
                {
                    throw new SPException(SPResource.GetString("DataFileExists", new object[] { settings.LogFilePath }));
                }
                if (fileExists)
                {
                    File.Delete(settings.LogFilePath);
                }
            }
        }
Exemple #27
0
        /// <summary>
        /// Sets up the export objects.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="cabSize">Size of the CAB.</param>
        /// <param name="compressFile">if set to <c>true</c> [compress file].</param>
        /// <param name="filename">The filename.</param>
        /// <param name="haltOnFatalError">if set to <c>true</c> [halt on fatal error].</param>
        /// <param name="haltOnWarning">if set to <c>true</c> [halt on warning].</param>
        /// <param name="includeUserSecurity">if set to <c>true</c> [include user security].</param>
        /// <param name="logFile">if set to <c>true</c> [log file].</param>
        /// <param name="overwrite">if set to <c>true</c> [overwrite].</param>
        /// <param name="quiet">if set to <c>true</c> [quiet].</param>
        /// <param name="versions">The versions.</param>
        internal static void SetupExportObjects(SPExportSettings settings, int cabSize, bool compressFile, string filename, bool haltOnFatalError, bool haltOnWarning, bool includeUserSecurity, bool logFile, bool overwrite, bool quiet, SPIncludeVersions versions)
        {
            if (compressFile)
            {
                new SPDirectoryExistsAndValidFileNameValidator().Validate(filename);
            }
            if (!overwrite && File.Exists(filename))
            {
                throw new SPException(SPResource.GetString("NotOverwriteExportError", new object[] { filename }));
            }

            settings.ExportMethod              = SPExportMethodType.ExportAll;
            settings.HaltOnNonfatalError       = haltOnFatalError;
            settings.HaltOnWarning             = haltOnWarning;
            settings.CommandLineVerbose        = !quiet;
            settings.IncludeVersions           = versions;
            settings.IncludeSecurity           = includeUserSecurity ? SPIncludeSecurity.All : SPIncludeSecurity.None;
            settings.OverwriteExistingDataFile = overwrite;
            settings.FileMaxSize     = cabSize;
            settings.FileCompression = compressFile;

            settings.FileLocation = filename;
            if (!compressFile)
            {
                settings.FileLocation = filename;
            }
            else
            {
                string fileLocation;
                Utilities.SplitPathFile(filename, out fileLocation, out filename);
                settings.FileLocation = fileLocation;
                settings.BaseFileName = filename;
            }

            if (logFile)
            {
                if (!compressFile)
                {
                    settings.LogFilePath = Path.Combine(settings.FileLocation, "export.log");
                }
                else
                {
                    settings.LogFilePath = Path.Combine(settings.FileLocation, filename + ".export.log");
                }
                bool fileExists = File.Exists(settings.LogFilePath);
                if (!overwrite && fileExists)
                {
                    throw new SPException(SPResource.GetString("DataFileExists", new object[] { settings.LogFilePath }));
                }
                if (fileExists)
                {
                    File.Delete(settings.LogFilePath);
                }
            }
        }
        /// <summary>
        /// Runs the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="keyValues">The key values.</param>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public override int Execute(string command, System.Collections.Specialized.StringDictionary keyValues,
                                    out string output)
        {
            output = string.Empty;

            Uri uri = new Uri(Params["url"].Value);

            SPWebApplicationBuilder builder = GetWebAppBuilder(uri);

            SPWebApplication app = builder.Create();

            SPAdministrationWebApplication local = SPAdministrationWebApplication.Local;

            // Set the TimeZone of the Application
            if (Params["timezone"].UserTypedIn)
            {
                app.DefaultTimeZone = ushort.Parse(Params["timezone"].Value);
            }

            app.Update();
            app.ProvisionGlobally();

            // Execute pending timer jobs before moving on.
            Common.TimerJobs.ExecAdmSvcJobs.Execute(false, true);
            // Recreate the web application object to avoid update conflicts.
            app = SPWebApplication.Lookup(uri);

            // Upload the newly created WebApplication to the List 'Web Application List' in Central Administration:
            SPWebService.AdministrationService.WebApplications.Add(app);

            if (!Params["donotcreatesite"].UserTypedIn)
            {
                uint   nLCID       = uint.Parse(Params["lcid"].Value);
                string webTemplate = Params["sitetemplate"].Value;
                string ownerLogin  = Params["ownerlogin"].Value;
                ownerLogin = Utilities.TryGetNT4StyleAccountName(ownerLogin, app);
                string ownerName  = Params["ownername"].Value;
                string ownerEmail = Params["owneremail"].Value;

                app.Sites.Add(uri.AbsolutePath, null, null, nLCID, webTemplate, ownerLogin, ownerName, ownerEmail, null, null, null);
            }


            Console.WriteLine(SPResource.GetString("PendingRestartInExtendWebFarm", new object[0]));
            Console.WriteLine();

            if (!Params["donotcreatesite"].UserTypedIn)
            {
                Console.WriteLine(SPResource.GetString("AccessSiteAt", new object[] { uri.ToString() }));
            }
            Console.WriteLine();

            return((int)ErrorCodes.NoError);
        }
 /// <summary>
 /// Validates the specified param A name.
 /// </summary>
 /// <param name="paramAName">Name of the param A.</param>
 /// <param name="paramAValue">The param A value.</param>
 /// <param name="paramBName">Name of the param B.</param>
 /// <param name="paramBValue">The param B value.</param>
 public static void Validate(string paramAName, string paramAValue, string paramBName, string paramBValue)
 {
     if ((paramAValue == null) && (paramBValue == null))
     {
         throw new ArgumentException(SPResource.GetString("MissingBinaryParameter", new object[] { paramAName, paramBName }));
     }
     if ((paramAValue != null) && (paramBValue != null))
     {
         throw new ArgumentException(SPResource.GetString("IncompatibleParametersSpecified", new object[] { paramAName, paramBName }));
     }
 }
        /// <summary>
        /// Sets up the import object.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="compressFile">if set to <c>true</c> [compress file].</param>
        /// <param name="filename">The filename.</param>
        /// <param name="haltOnFatalError">if set to <c>true</c> [halt on fatal error].</param>
        /// <param name="haltOnWarning">if set to <c>true</c> [halt on warning].</param>
        /// <param name="includeusersecurity">if set to <c>true</c> [includeusersecurity].</param>
        /// <param name="logFile">if set to <c>true</c> [log file].</param>
        /// <param name="quiet">if set to <c>true</c> [quiet].</param>
        /// <param name="updateVersions">The update versions.</param>
        /// <param name="retainObjectIdentity">if set to <c>true</c> [retain object identity].</param>
        /// <param name="suppressAfterEvents">if set to <c>true</c> [suppress after events].</param>
        internal static void SetupImportObject(SPImportSettings settings, bool compressFile, string filename, bool haltOnFatalError, bool haltOnWarning, bool includeusersecurity, bool logFile, bool quiet, SPUpdateVersions updateVersions, bool retainObjectIdentity, bool suppressAfterEvents)
        {
            settings.CommandLineVerbose  = !quiet;
            settings.HaltOnNonfatalError = haltOnFatalError;
            settings.HaltOnWarning       = haltOnWarning;
            settings.FileCompression     = compressFile;
            settings.SuppressAfterEvents = suppressAfterEvents;

            if (!compressFile)
            {
                if (string.IsNullOrEmpty(filename) || !Directory.Exists(filename))
                {
                    throw new SPException(SPResource.GetString("DirectoryNotFoundExceptionMessage", new object[] { filename }));
                }
            }
            else if (string.IsNullOrEmpty(filename) || !File.Exists(filename))
            {
                throw new SPException(SPResource.GetString("FileNotFoundExceptionMessage", new object[] { filename }));
            }

            if (!compressFile)
            {
                settings.FileLocation = filename;
            }
            else
            {
                string path;
                Utilities.SplitPathFile(filename, out path, out filename);
                settings.FileLocation = path;
                settings.BaseFileName = filename;
            }

            if (logFile)
            {
                if (!compressFile)
                {
                    settings.LogFilePath = Path.Combine(settings.FileLocation, "import.log");
                }
                else
                {
                    settings.LogFilePath = Path.Combine(settings.FileLocation, filename + ".import.log");
                }
            }


            if (includeusersecurity)
            {
                settings.IncludeSecurity  = SPIncludeSecurity.All;
                settings.UserInfoDateTime = SPImportUserInfoDateTimeOption.ImportAll;
            }
            settings.UpdateVersions       = updateVersions;
            settings.RetainObjectIdentity = retainObjectIdentity;
        }