public static void AddXsltViewWebPart(SPWeb web, SPList list, string pageUrl, string webPartName, string zoneID, int zoneIndex, bool isHidden, string viewTitle) { using (SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager( pageUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared)) { bool isExists = false; foreach (System.Web.UI.WebControls.WebParts.WebPart wp in webPartManager.WebParts) { if (wp.Title.Equals(webPartName)) { isExists = true; break; } else { isExists = false; } } if (!isExists) { XsltListViewWebPart webPart = new XsltListViewWebPart(); webPart.ListId = list.ID; webPart.Title = webPartName; webPart.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.TitleAndBorder; SPView view = list.Views[viewTitle]; webPart.ViewGuid = view.ID.ToString(); webPart.XmlDefinition = view.GetViewXml(); webPartManager.AddWebPart(webPart, zoneID, zoneIndex); } } }
protected void btnViewAvailability_Click(object sender, EventArgs e) { SPLimitedWebPartManager webPartManager = null; try { SPList list = null; SPView view = null; // get WebPartManager to identify current List/View SPWeb web = SPContext.Current.Web; webPartManager = SPContext.Current.File.GetLimitedWebPartManager(PersonalizationScope.Shared); foreach (System.Web.UI.WebControls.WebParts.WebPart wp in webPartManager.WebParts) { XsltListViewWebPart xlvwp = wp as XsltListViewWebPart; if (xlvwp != null) { list = web.Lists[xlvwp.ListId]; view = xlvwp.View; break; } } // get list data by Filters FieldFilterOperatorsLayer fol = new FieldFilterOperatorsLayer(this.FilterConditions); CamlFiltersLayer fl = new CamlFiltersLayer(list, this.FilterQuery, fol); string myQuery = fl.GetQueryByFilters(); SPListItemCollection navigator = list.GetItems(new SPQuery() { Query = myQuery, ViewFields = "<FieldRef Name=\"ID\" />", RowLimit = view.RowLimit }); // get filter IDs string filteredIDs = string.Empty; if (navigator != null && navigator.Count > 0) { filteredIDs = String.Join(",", navigator.Cast <SPListItem>().Select(x => x.ID.ToString()).ToArray()); } string redigUrl = string.Format("{0}/{1}?FilteredIDs={2}&OrigSchiftId={3}{4}{5}", web.ServerRelativeUrl.TrimEnd('/'), this.RedirectUrl.TrimStart('/'), filteredIDs, this.Page.Request.QueryString["SchiftId"], string.IsNullOrEmpty(this.CalendarPeriod) ? "" : string.Format("&CalendarPeriod={0}", this.CalendarPeriod), FormatedCalendarDate); SPUtility.Redirect(redigUrl, SPRedirectFlags.Default, this.Context); } catch (Exception ex) { lblError.Text = ex.Message; lblError.Visible = true; } finally { if (webPartManager != null) { webPartManager.Web.Dispose(); } } }
public void AddListToPage(SPFile homePage, SPList list) { XsltListViewWebPart wp = new XsltListViewWebPart(); wp.ListName = list.ID.ToString("B").ToUpper(); ModifyViewClass viewOperations = new ModifyViewClass(); SPView defaultView = viewOperations.GetDefaultView(list); SPView copiedView = viewOperations.CopyView(defaultView, list); viewOperations.SetToolbarType(copiedView, "Standard"); wp.ViewGuid = defaultView.ID.ToString("B").ToUpper(); wp.Title = list.Title; InsertWebPartIntoWikiPage(homePage, wp, "{{1}}"); }
// Uncomment the method below to handle the event raised after a feature has been activated. public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPSite site = properties.Feature.Parent as SPSite; using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists.TryGetList("SPForumsPostList"); list.DisableGridEditing = true; using (SPLimitedWebPartManager wpManager = web.GetLimitedWebPartManager(web.ServerRelativeUrl + "/SitePages/SPForums.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared)) { //add ListViewWebPart to SPForums.aspx XsltListViewWebPart xWP = new XsltListViewWebPart(); xWP.ListName = list.ID.ToString(); xWP.ListId = list.ID; xWP.Title = "SPForumsPostList"; xWP.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None; wpManager.AddWebPart(xWP, "Body", 1); //add LeftMenu to SPForums.aspx SPForumsSourceCode.SPForumsVWPLeftMenu.SPForumsVWPLeftMenu lMenu = new SPForumsVWPLeftMenu.SPForumsVWPLeftMenu(); lMenu.Title = "SPForumsLeftMenu"; lMenu.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None; wpManager.AddWebPart(lMenu, "LeftColumn", 1); } using (SPLimitedWebPartManager wpManager = web.GetLimitedWebPartManager(web.ServerRelativeUrl + "/Lists/SPForumsPostList/DispForm.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared)) { //add ReplyWebPart to DispForm.aspx SPForumsSourceCode.SPForumsVWPReply.SPForumsVWPReply rWebPart = new SPForumsVWPReply.SPForumsVWPReply(); rWebPart.Title = "SPForumsReply"; rWebPart.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None; wpManager.AddWebPart(rWebPart, "Main", 2); } using (SPLimitedWebPartManager wpManager = web.GetLimitedWebPartManager(web.ServerRelativeUrl + "/SitePages/SPForumsMessage.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared)) { SPForumsSourceCode.SPForumsVWPNotice.SPForumsVWPNotice nWebPart = new SPForumsVWPNotice.SPForumsVWPNotice(); nWebPart.Title = "SPForumsNotice"; nWebPart.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None; wpManager.AddWebPart(nWebPart, "Main", 2); } using (SPLimitedWebPartManager wpManager = web.GetLimitedWebPartManager(web.ServerRelativeUrl + "/Lists/SPForumsMessageList/DispForm.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared)) { SPForumsSourceCode.SPForumsWPModifyUnReadState.SPForumsWPModifyUnReadState unWebPart = new SPForumsWPModifyUnReadState.SPForumsWPModifyUnReadState(); unWebPart.Title = "SPForumsModifyUnReadState"; unWebPart.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None; wpManager.AddWebPart(unWebPart, "Main", 2); } } }
private XsltListViewWebPart getFirstListViewWebPart() { WebPartManager currentWebPartManager = WebPartManager.GetCurrentWebPartManager(this.Page); if (currentWebPartManager != null) { foreach (System.Web.UI.WebControls.WebParts.WebPart part in currentWebPartManager.WebParts) { XsltListViewWebPart part2 = part as XsltListViewWebPart; if (part2 != null) { return(part2); } } } return(null); }
private static void CreateWebParts(SPManager mgr) { var configItems = new XsltListViewWebPart { ListId = mgr.ParentWeb.Lists[Constants.SpongeListConfigitems].ID }; var configApps = new XsltListViewWebPart { ListId = mgr.ParentWeb.Lists[Constants.SpongeListConfigapplications].ID }; var logConfig = new XsltListViewWebPart { ListId = mgr.ParentWeb.Lists[Constants.SpongeListLogconfigs].ID }; var logTargets = new XsltListViewWebPart { ListId = mgr.ParentWeb.Lists[Constants.SpongeListLogtargets].ID }; AddWebPart(mgr.ParentWeb, "default.aspx", configApps, "left", 1); AddWebPart(mgr.ParentWeb, "default.aspx", configItems, "left", 2); AddWebPart(mgr.ParentWeb, "default.aspx", logConfig, "right", 1); AddWebPart(mgr.ParentWeb, "default.aspx", logTargets, "right", 2); }
private List <XsltListViewWebPart> GetListViewWebParts() { List <XsltListViewWebPart> xsltListWebPartCollecion = new List <XsltListViewWebPart>(); WebPartManager currentWebPartManager = WebPartManager.GetCurrentWebPartManager(this.Page); if (currentWebPartManager != null) { foreach (System.Web.UI.WebControls.WebParts.WebPart webPpart in currentWebPartManager.WebParts) { XsltListViewWebPart xsltWebPart = webPpart as XsltListViewWebPart; if (xsltWebPart != null) { xsltListWebPartCollecion.Add(xsltWebPart); } } return(xsltListWebPartCollecion); } return(null); }
protected void setUpList(int baseId) { string siteUrl = SPContext.Current.Web.Url; SPSite oSiteCollection = SPContext.Current.Site; oList = SPContext.Current.Web.Lists["Alerts Noticeboard"]; SPWeb web = SPContext.Current.Web; web.AllowUnsafeUpdates = true; string pageUrl = "SitePages/managealerts.aspx"; SPFile page = web.GetFile(pageUrl); SPLimitedWebPartManager wpmgr = page.GetLimitedWebPartManager(PersonalizationScope.Shared); Guid storageKey = Guid.NewGuid(); string wpId = String.Format("g_{0}", storageKey.ToString().Replace('-', '_')); SPLimitedWebPartCollection WebParts = wpmgr.WebParts; XsltListViewWebPart xwp = new XsltListViewWebPart(); //SPViewCollection viewsCol = oList.Views; xwp.ID = wpId; xwp.ListName = oList.ID.ToString("B").ToUpper(); wpmgr.AddWebPart(xwp, "WebPartZone1", 0); if (WebParts.Count > 1) { wpmgr.DeleteWebPart(xwp); } }
public XsltListViewWebPart AddListToPage(SPList list, string title, string zone, SPLimitedWebPartManager webPartManager, int index) { // validation list.RequireNotNull("list"); title.RequireNotNullOrEmpty("title"); zone.RequireNotNullOrEmpty("zone"); webPartManager.RequireNotNull("webPartManager"); index.Require(index >= 0, "index"); XsltListViewWebPart wp = new XsltListViewWebPart(); wp.ListName = list.ID.ToString("B").ToUpper(); wp.Title = title; wp.ZoneID = zone; ModifyViewClass viewOperations = new ModifyViewClass(); SPView defaultView = viewOperations.GetDefaultView(list); SPView modifiedView = viewOperations.CopyView(defaultView, list); viewOperations.SetToolbarType(modifiedView, "Standard"); modifiedView.Update(); wp.ViewGuid = modifiedView.ID.ToString("B").ToUpper(); webPartManager.AddWebPart(wp, zone, index); list.Update(); webPartManager.SaveChanges(wp); return wp; }
private void AddView() { XsltListViewWebPart xlvWebPart = null; //SPSite spSite =// new SPSite("http://xqx2012/personal/xueqingxia"); SPWeb spWeb = SPContext.Current.Web; SPList currList = spWeb.Lists.TryGetList(webObj.ListMediaLib);//"文档" ); //GetList(ref spWeb, ref currList); SPView view = currList.Views[0]; foreach (SPView tmpView in currList.Views) { if (tmpView.Title == "缩略图") { view = tmpView; break; } } xlvWebPart = new XsltListViewWebPart(); xlvWebPart.ID = "xlvPics"; xlvWebPart.Toolbar = "None"; xlvWebPart.WebId = spWeb.ID; xlvWebPart.ListId = currList.ID; xlvWebPart.ChromeType = PartChromeType.TitleOnly; xlvWebPart.ViewGuid = view.ID.ToString(); xlvWebPart.ListName = currList.ID.ToString(); //xlvWebPart.Title = currList.Title; xlvWebPart.ClientRender = true; xlvWebPart.ListUrl = currList.RootFolder.Url; xlvWebPart.CssClass = view.CssStyleSheet; xlvWebPart.CssStyleSheet = view.CssStyleSheet; xlvWebPart.JSLink = view.JSLink; xlvWebPart.AllowClose = false; xlvWebPart.AllowConnect = false; xlvWebPart.AllowEdit = false; xlvWebPart.AllowHide = false; xlvWebPart.AllowMinimize = false; xlvWebPart.AllowZoneChange = false; xlvWebPart.ChromeType = PartChromeType.Default; //xlvWebPart.Title = ""; //xlvWebPart.ViewSelectorFetchAsync = false; //xlvWebPart.InplaceSearchEnabled = false; //xlvWebPart.ServerRender = false; //xlvWebPart.InitialAsyncDataFetch = false; //xlvWebPart.PageSize = -1; xlvWebPart.UseSQLDataSourcePaging = true; xlvWebPart.DataSourceID = ""; xlvWebPart.ShowWithSampleData = false; xlvWebPart.AsyncRefresh = false; xlvWebPart.ManualRefresh = false; xlvWebPart.AutoRefresh = false; xlvWebPart.AutoRefreshInterval = 60; xlvWebPart.SuppressWebPartChrome = false; xlvWebPart.ZoneID = "Main"; xlvWebPart.ChromeState = PartChromeState.Normal; xlvWebPart.AllowClose = true; xlvWebPart.AllowZoneChange = true; xlvWebPart.AllowMinimize = true; xlvWebPart.AllowConnect = true; xlvWebPart.AllowEdit = true; xlvWebPart.AllowHide = true; xlvWebPart.Hidden = false; xlvWebPart.XmlDefinition = view.GetViewXml(); xlvWebPart.ParameterBindings = view.ParameterBindings; StringBuilder txt = new StringBuilder(); txt.AppendLine("<div id = \"MSOZoneCell_WebPartWPQ2\" class=\"ms-webpartzone-cell ms-webpart-cell-vertical ms-fullWidth s4-wpcell\" onkeyup=\"WpKeyUp(event)\" onmouseup=\"WpClick(event)\">"); txt.AppendLine("<div class=\"ms-webpart-chrome ms-webpart-chrome-vertical ms-webpart-chrome-fullWidth \">"); //txt.AppendLine(xlvWebPart.ToString ()); //txt.AppendLine("</div></div>"); try { this.Controls.Add(new LiteralControl(txt.ToString())); this.Controls.Add(xlvWebPart); this.Controls.Add(new LiteralControl("</div></div>")); //divRoll.Controls.Add(xlvWebPart); } catch (Exception ex) { lblMsg.Text = ex.ToString(); } }
/// <summary> /// Adds a List View Web Part to the specified page. /// </summary> /// <param name="pageUrl">The page URL.</param> /// <param name="listUrl">The list URL.</param> /// <param name="title">The title.</param> /// <param name="viewTitle">Title of the view.</param> /// <param name="zoneId">The zone ID.</param> /// <param name="zoneIndex">Index within the zone.</param> /// <param name="linkTitle">if set to <c>true</c> [link title].</param> /// <param name="chromeType">Type of the chrome.</param> /// <param name="publish">if set to <c>true</c> [publish].</param> /// <returns></returns> public static Microsoft.SharePoint.WebPartPages.WebPart Add(string pageUrl, string listUrl, string title, string viewTitle, string zoneId, int zoneIndex, bool linkTitle, string jsLink, PartChromeType chromeType, bool publish) { using (SPSite site = new SPSite(pageUrl)) using (SPWeb web = site.OpenWeb()) // The url contains a filename so AllWebs[] will not work unless we want to try and parse which we don't { SPFile file = web.GetFile(pageUrl); // file.Item will throw "The object specified does not belong to a list." if the url passed // does not correspond to a file in a list. SPList list = Utilities.GetListFromViewUrl(listUrl); if (list == null) { throw new ArgumentException("List not found."); } SPView view = null; if (!string.IsNullOrEmpty(viewTitle)) { view = list.Views.Cast <SPView>().FirstOrDefault(v => v.Title == viewTitle); if (view == null) { throw new ArgumentException("The specified view was not found."); } } bool checkBackIn = false; if (file.InDocumentLibrary) { if (!Utilities.IsCheckedOut(file.Item) || !Utilities.IsCheckedOutByCurrentUser(file.Item)) { checkBackIn = true; file.CheckOut(); } // If it's checked out by another user then this will throw an informative exception so let it do so. } string displayTitle = string.Empty; Microsoft.SharePoint.WebPartPages.WebPart lvw = null; SPLimitedWebPartManager manager = null; try { manager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared); lvw = new XsltListViewWebPart(); if (list.BaseTemplate == SPListTemplateType.Events) { lvw = new ListViewWebPart(); } if (lvw is ListViewWebPart) { ((ListViewWebPart)lvw).ListName = list.ID.ToString("B").ToUpperInvariant(); ((ListViewWebPart)lvw).WebId = list.ParentWeb.ID; if (view != null) { ((ListViewWebPart)lvw).ViewGuid = view.ID.ToString("B").ToUpperInvariant(); } } else { ((XsltListViewWebPart)lvw).ListName = list.ID.ToString("B").ToUpperInvariant(); #if !SP2010 if (!string.IsNullOrEmpty(jsLink)) { ((XsltListViewWebPart)lvw).JSLink = jsLink; } #endif ((XsltListViewWebPart)lvw).WebId = list.ParentWeb.ID; if (view != null) { ((XsltListViewWebPart)lvw).ViewGuid = view.ID.ToString("B").ToUpperInvariant(); } } if (linkTitle) { if (view != null) { lvw.TitleUrl = view.Url; } else { lvw.TitleUrl = list.DefaultViewUrl; } } if (!string.IsNullOrEmpty(title)) { lvw.Title = title; } lvw.ChromeType = chromeType; displayTitle = lvw.DisplayTitle; manager.AddWebPart(lvw, zoneId, zoneIndex); } finally { if (manager != null) { manager.Web.Dispose(); manager.Dispose(); } if (lvw != null) { lvw.Dispose(); } if (file.InDocumentLibrary && Utilities.IsCheckedOut(file.Item) && (checkBackIn || publish)) { file.CheckIn("Checking in changes to page due to new web part being added: " + displayTitle); } if (publish && file.InDocumentLibrary) { file.Publish("Publishing changes to page due to new web part being added: " + displayTitle); if (file.Item.ModerationInformation != null) { file.Approve("Approving changes to page due to new web part being added: " + displayTitle); } } } return(lvw); } }
protected void Page_Load(object sender, EventArgs e) { // 获取当前用户信息 this.CurrentUser = new LoginUser(); this.iCurrentUserID = CurrentUser.iUserID; #region 页面重定向 if (this.CurrentUser.sRoleName == "Executive" || this.CurrentUser.sRoleName == "Branch Manager") { try { this.Response.Redirect("DashBoardHome2.aspx"); } catch { } } #endregion #region Get User Home Profile LPWeb.BLL.UserHomePref UserHomePref1 = new LPWeb.BLL.UserHomePref(); LPWeb.Model.UserHomePref UserHomePref2 = UserHomePref1.GetModel(this.iCurrentUserID); #endregion #region 角色权限-显示控制 #region 设置是否显示Alert if (this.CurrentUser.userRole.OverdueTaskAlerts == true) { this.AlertWebPart1.Visible = true; } else { this.AlertWebPart1.Visible = false; } // User Home Profile if (UserHomePref2 != null) { if (UserHomePref2.OverDueTaskAlert == true) { this.AlertWebPart1.Visible = true; } else { this.AlertWebPart1.Visible = false; } } #endregion #region 设置是否显示Email Inbox if (this.CurrentUser.userRole.ExchangeInbox == true) { this.divEmailInbox.Visible = true; } else { this.divEmailInbox.Visible = false; } // User Home Profile if (UserHomePref2 != null) { if (UserHomePref2.ExchangeInbox == true) { this.divEmailInbox.Visible = true; } else { this.divEmailInbox.Visible = false; } } #endregion #region 设置是否显示Company Announcement //if (this.CurrentUser.userRole.Announcements == true) //{ // this.divCompanyAnn.Visible = true; //} //else //{ // this.divCompanyAnn.Visible = false; //} //// User Home Profile //if (UserHomePref2 != null) //{ // if (UserHomePref2.Announcements == true) // { // this.divCompanyAnn.Visible = true; // } // else // { // this.divCompanyAnn.Visible = false; // } //} #endregion #region 设置是否显示Calendar if (this.CurrentUser.userRole.ExchangeCalendar == true) { this.divCalendar.Visible = true; } else { this.divCalendar.Visible = false; } // User Home Profile if (UserHomePref2 != null) { if (UserHomePref2.ExchangeCalendar == true) { this.divCalendar.Visible = true; } else { this.divCalendar.Visible = false; } } #endregion #region 设置是否显示User Goals if (this.CurrentUser.userRole.GoalsChart == true) { this.divUserGoals.Visible = true; } else { this.divUserGoals.Visible = false; } // User Home Profile if (UserHomePref2 != null) { if (UserHomePref2.GoalsChart == true) { this.divUserGoals.Visible = true; } else { this.divUserGoals.Visible = false; } } #endregion #region 设置是否显示Pipeline Summary if (this.CurrentUser.userRole.PipelineChart == true) { this.divPipelineAnalysis.Visible = true; } else { this.divPipelineAnalysis.Visible = false; } // User Home Profile if (UserHomePref2 != null) { if (UserHomePref2.PipelineChart == true) { this.divPipelineAnalysis.Visible = true; } else { this.divPipelineAnalysis.Visible = false; } } #endregion #region 设置是否显示filter if (this.divPipelineAnalysis.Visible == false && this.divUserGoals.Visible == false) { this.divFilters.Visible = false; } #endregion #region UserHomePref.DashboardLastCompletedStages // StageFilter string sStageFilter = string.Empty; this.ddlStageFilter.Value = "CurrentStages"; sStageFilter = "CurrentStages"; if (UserHomePref2 != null && UserHomePref2.DashboardLastCompletedStages != null && UserHomePref2.DashboardLastCompletedStages == 1) { this.ddlStageFilter.Value = "LastCompletedStages"; sStageFilter = "LastCompletedStages"; } #endregion #region Quick Lead Form if (this.CurrentUser.QuickLeadForm == true) { this.divQuickLead.Visible = true; } else { this.divQuickLead.Visible = false; } #endregion #endregion string sErrorMsg = "Invalid query string, be ignored."; #region 获取页面参数 int iRegionID = 0; int iDivisionID = 0; string sRegionID = string.Empty; string sDivisionID = string.Empty; string sBranchID = string.Empty; string sDateType = string.Empty; string sFromDate = string.Empty; string sToDate = string.Empty; // Template_Stage.WorkflowType = Loan.Status string sWorkflowType = string.Empty; #region RegionID if (this.Request.QueryString["Region"] != null) { #region get region id string sRegionID_Encode = this.Request.QueryString["Region"].ToString(); string sRegionID_Decode = Encrypter.Base64Decode(sRegionID_Encode); if (sRegionID_Decode == sRegionID_Encode) { PageCommon.WriteJsEnd(this, sErrorMsg, "window.location.href = window.location.pathname"); } bool IsValid = Regex.IsMatch(sRegionID_Decode, @"^(-)?\d+$"); if (IsValid == false) { PageCommon.WriteJsEnd(this, sErrorMsg, "window.location.href = window.location.pathname"); } sRegionID = sRegionID_Decode; iRegionID = Convert.ToInt32(sRegionID_Decode); #endregion } #endregion #region DivisionID if (this.Request.QueryString["Division"] != null) { #region get division id string sDivisionID_Encode = this.Request.QueryString["Division"].ToString(); string sDivisionID_Decode = Encrypter.Base64Decode(sDivisionID_Encode); if (sDivisionID_Decode == sDivisionID_Encode) { PageCommon.WriteJsEnd(this, sErrorMsg, "window.location.href = window.location.pathname"); } bool IsValid = Regex.IsMatch(sDivisionID_Decode, @"^(-)?\d+$"); if (IsValid == false) { PageCommon.WriteJsEnd(this, sErrorMsg, "window.location.href = window.location.pathname"); } sDivisionID = sDivisionID_Decode; iDivisionID = Convert.ToInt32(sDivisionID_Decode); #endregion } #endregion #region BranchID if (this.Request.QueryString["Branch"] != null) { string sBranch_Encode = this.Request.QueryString["Branch"].ToString(); sBranchID = Encrypter.Base64Decode(sBranch_Encode); if (sBranch_Encode == sBranchID) { PageCommon.WriteJsEnd(this, sErrorMsg, "window.location.href = window.location.pathname"); } bool IsValid = Regex.IsMatch(sBranchID, @"^(-)?\d+$"); if (IsValid == false) { PageCommon.WriteJsEnd(this, sErrorMsg, "window.location.href = window.location.pathname"); } } #endregion #region Date Type if (this.Request.QueryString["DateType"] != null) { string sDateType_Encode = this.Request.QueryString["DateType"].ToString(); sDateType = Encrypter.Base64Decode(sDateType_Encode); if (sDateType != "CloseDate" && sDateType != "OpenDate") { PageCommon.WriteJsEnd(this, sErrorMsg, "window.location.href = window.location.pathname"); } } else { sDateType = "CloseDate"; } #endregion #region FromDate if (this.Request.QueryString["FromDate"] != null) { string sFromDate_Encode = this.Request.QueryString["FromDate"].ToString(); sFromDate = Encrypter.Base64Decode(sFromDate_Encode); if (sFromDate_Encode == sFromDate) { PageCommon.WriteJsEnd(this, sErrorMsg, "window.location.href = window.location.pathname"); } } #endregion #region ToDate if (this.Request.QueryString["ToDate"] != null) { string sToDate_Encode = this.Request.QueryString["ToDate"].ToString(); sToDate = Encrypter.Base64Decode(sToDate_Encode); if (sToDate_Encode == sToDate) { PageCommon.WriteJsEnd(this, sErrorMsg, "window.location.href = window.location.pathname"); } } #endregion #region Workflow Type if (this.Request.QueryString["WorkflowType"] != null) { string sWorkflowType_Encode = this.Request.QueryString["WorkflowType"].ToString(); sWorkflowType = Encrypter.Base64Decode(sWorkflowType_Encode); if (sWorkflowType != "Processing" && sWorkflowType != "Prospect" && sWorkflowType != "Archived") { PageCommon.WriteJsEnd(this, sErrorMsg, "window.location.href = window.location.pathname"); } } else { sWorkflowType = "Processing"; } #endregion #region StageFilter if (this.Request.QueryString["StageFilter"] != null) { sStageFilter = this.Request.QueryString["StageFilter"].ToString(); if (sStageFilter != "CurrentStages") { sStageFilter = "LastCompletedStages"; } } #endregion #endregion #region load filters DataSet OrganFilters = PageCommon.GetOrganFilter(iRegionID, iDivisionID); // region filter DataTable RegionListData = OrganFilters.Tables["Regions"]; this.ddlRegions.DataSource = RegionListData; this.ddlRegions.DataBind(); // division filter DataTable DivisionListData = OrganFilters.Tables["Divisions"]; this.ddlDivisions.DataSource = DivisionListData; this.ddlDivisions.DataBind(); // branch filter DataTable BranchListData = OrganFilters.Tables["Branches"]; this.ddlBranches.DataSource = BranchListData; this.ddlBranches.DataBind(); #endregion #region Build Search Conditions string sWhere = string.Empty; // Loans.Status if (sWorkflowType == "Archived") { sWhere += " and (b.Status!='Processing') and (b.Status!='Prospect')"; //CR063 : Remove the “Suspended” status in the list of the “Archived Loans” status sWhere += " AND (b.Status != 'Suspended')"; } else { sWhere += " and (b.Status='" + sWorkflowType + "')"; } if (sWorkflowType == "Prospect") { sWhere += " and (b.ProspectLoanStatus='Active')"; } if (sRegionID != string.Empty) { sWhere += " and (a.RegionID = " + sRegionID + ")"; } if (sDivisionID != string.Empty) { sWhere += " and (a.DivisionID = " + sDivisionID + ")"; } if (sBranchID != string.Empty) { sWhere += " and (a.BranchID = " + sBranchID + ")"; } if (sDateType != string.Empty) { #region FromDate and ToDate DateTime?FromDate = null; DateTime?ToDate = null; if (sFromDate != string.Empty) { DateTime FromDate1; bool IsDate1 = DateTime.TryParse(sFromDate, out FromDate1); if (IsDate1 == true) { FromDate = FromDate1; } } if (sToDate != string.Empty) { DateTime ToDate1; bool IsDate2 = DateTime.TryParse(sToDate, out ToDate1); if (IsDate2 == true) { ToDate = ToDate1; } } string sFiledName = string.Empty; if (sDateType == "CloseDate") { sFiledName = "b.LastStageComplDate"; } else { sFiledName = "b.LastStageComplDate"; } sWhere += SqlTextBuilder.BuildDateSearchCondition(sFiledName, FromDate, ToDate); #endregion } #endregion #region Pipeline Summary #region get stage template list // loan manager LPWeb.BLL.Loans LoanManager = new LPWeb.BLL.Loans(); if (sWorkflowType == "Archived") { #region init LoanAnalysisData this.LoanAnalysisData = new DataTable(); this.LoanAnalysisData.Columns.Add("StageName", typeof(string)); this.LoanAnalysisData.Columns.Add("StageAlias", typeof(string)); this.LoanAnalysisData.Columns.Add("Href", typeof(string)); this.LoanAnalysisData.Columns.Add("Amount", typeof(decimal)); this.LoanAnalysisData.Columns.Add("LoanCounts", typeof(int)); //gdc CR40 DataRow ClosedRow = this.LoanAnalysisData.NewRow(); ClosedRow["StageName"] = "Closed"; ClosedRow["StageAlias"] = "Closed"; ClosedRow["Href"] = string.Empty; ClosedRow["Amount"] = decimal.Zero; ClosedRow["LoanCounts"] = decimal.Zero;//gdc CR40 this.LoanAnalysisData.Rows.Add(ClosedRow); DataRow CanceledRow = this.LoanAnalysisData.NewRow(); CanceledRow["StageName"] = "Canceled"; CanceledRow["StageAlias"] = "Canceled"; CanceledRow["Href"] = string.Empty; CanceledRow["Amount"] = decimal.Zero; CanceledRow["LoanCounts"] = decimal.Zero;//gdc CR40 this.LoanAnalysisData.Rows.Add(CanceledRow); DataRow DeniedRow = this.LoanAnalysisData.NewRow(); DeniedRow["StageName"] = "Denied"; DeniedRow["StageAlias"] = "Denied"; DeniedRow["Href"] = string.Empty; DeniedRow["Amount"] = decimal.Zero; DeniedRow["LoanCounts"] = decimal.Zero;//gdc CR40 this.LoanAnalysisData.Rows.Add(DeniedRow); //CR063 : Remove the “Suspended” status in the list of the “Archived Loans” status //DataRow SuspendedRow = this.LoanAnalysisData.NewRow(); //SuspendedRow["StageName"] = "Suspended"; //SuspendedRow["StageAlias"] = "Suspended"; //SuspendedRow["Href"] = string.Empty; //SuspendedRow["Amount"] = decimal.Zero; //SuspendedRow["LoanCounts"] = decimal.Zero;//gdc CR40 //this.LoanAnalysisData.Rows.Add(SuspendedRow); #endregion #region 添加Uncategorized分类 DataRow UncategorizedRow = this.LoanAnalysisData.NewRow(); UncategorizedRow["StageName"] = "Uncategorized"; UncategorizedRow["StageAlias"] = "Uncategorized"; UncategorizedRow["Href"] = string.Empty; UncategorizedRow["Amount"] = decimal.Zero; UncategorizedRow["LoanCounts"] = decimal.Zero;//gdc CR40 this.LoanAnalysisData.Rows.Add(UncategorizedRow); #endregion } else { string sSql2 = "select Name as StageName, Alias as StageAlias, '' as Href, 0.00 as Amount,0 as LoanCounts from Template_Stages " + "where WorkflowType=@WorkflowType and [Enabled]=1 order by SequenceNumber"; SqlCommand SqlCmd2 = new SqlCommand(sSql2); DbHelperSQL.AddSqlParameter(SqlCmd2, "@WorkflowType", sWorkflowType); this.LoanAnalysisData = DbHelperSQL.ExecuteDataTable(SqlCmd2); #region 如果Lead,添加Uncategorized分类 if (sWorkflowType == "Prospect") { DataRow NewStageTempRow = this.LoanAnalysisData.NewRow(); NewStageTempRow["StageName"] = "Uncategorized"; NewStageTempRow["StageAlias"] = "Uncategorized"; NewStageTempRow["Href"] = string.Empty; NewStageTempRow["Amount"] = decimal.Zero; NewStageTempRow["LoanCounts"] = decimal.Zero; //gdc CR40 this.LoanAnalysisData.Rows.Add(NewStageTempRow); } #endregion } #endregion #region get user loan list string sStageField = string.Empty; if (sStageFilter == "CurrentStages") { sStageField = "b.Stage"; } else { sStageField = "b.LastCompletedStage"; } //string sSqlx1 = string.Format("select {0} as Stage, b.Amount as Amount from lpfn_GetUserLoans2({1}, {2}) as a inner join V_ProcessingPipelineInfo as b on a.LoanID = b.FileId ", sStageField, iCurrentUserID, (this.CurrentUser.bAccessOtherLoans)?1:0) // + "where (1=1) " + sWhere; string sSqlx1 = "select " + sStageField + " as Stage, b.Amount as Amount from lpfn_GetUserLoans(" + this.iCurrentUserID + ") as a inner join V_ProcessingPipelineInfo as b on a.LoanID = b.FileId " + "where (1=1) " + sWhere; DataTable UserLoanList = LPWeb.DAL.DbHelperSQL.ExecuteDataTable(sSqlx1); #endregion #region set Amount and Href foreach (DataRow LoanAnaylysisRow in this.LoanAnalysisData.Rows) { string sStageName = LoanAnaylysisRow["StageName"].ToString(); string sStageAlias = LoanAnaylysisRow["StageAlias"] == DBNull.Value ? LoanAnaylysisRow["StageName"].ToString() : LoanAnaylysisRow["StageAlias"].ToString(); if (sStageName == "Uncategorized") { #region Amount string sSqlx10 = string.Empty; if (sWorkflowType == "Prospect") { sSqlx10 = "select isnull(SUM(b.Amount),0.00) as TotalAmount,count(1) as Total from lpfn_GetUserLoans(" + this.iCurrentUserID + ") as a inner join V_ProcessingPipelineInfo as b on a.LoanID=b.FileId " + "where (select COUNT(1) from LoanStages where FileId=a.LoanID)=0 " + sWhere; } else if (sWorkflowType == "Archived") { //string sWhere10 = sWhere.Replace(" and (b.Status!='Processing') and (b.Status!='Prospect')", " and b.Status='Uncategorized Archive'"); //CR063 : Remove the “Suspended” status in the list of the “Archived Loans” status string sWhere10 = sWhere.Replace(" and (b.Status!='Processing') and (b.Status!='Prospect') AND (b.Status != 'Suspended')", " and b.Status='Uncategorized Archive'"); sSqlx10 = "select isnull(SUM(b.Amount),0.00) as TotalAmount,count(1) as Total from lpfn_GetUserLoans(" + this.iCurrentUserID + ") as a inner join V_ProcessingPipelineInfo as b on a.LoanID=b.FileId " + "where 1=1 " + sWhere10; } //object oSum = LPWeb.DAL.DbHelperSQL.ExecuteScalar(sSqlx10); //decimal dSum = oSum == DBNull.Value ? decimal.Zero : Convert.ToDecimal(oSum); //LoanAnaylysisRow["Amount"] = dSum; decimal dSum = 0; int Total = 0; var dt = LPWeb.DAL.DbHelperSQL.ExecuteDataTable(sSqlx10); if (dt.Rows.Count > 0) { dSum = dt.Rows[0]["TotalAmount"] == DBNull.Value ? decimal.Zero : Convert.ToDecimal(dt.Rows[0]["TotalAmount"]); Total = dt.Rows[0]["Total"] == DBNull.Value ? 0 : Convert.ToInt32(dt.Rows[0]["Total"]); } LoanAnaylysisRow["Amount"] = dSum; LoanAnaylysisRow["LoanCounts"] = Total; #endregion #region Href string sPipelineUrl = string.Empty; if (sWorkflowType == "Prospect") { string sAliasString = this.BuildQueryString_PipelineSummary(sRegionID, sDivisionID, sBranchID, sDateType, sFromDate, sToDate, sWorkflowType, sStageAlias, sStageFilter); sPipelineUrl = "Pipeline/ProspectPipelineSummaryLoan.aspx?q=" + Encrypter.Base64Encode(sAliasString); } else if (sWorkflowType == "Archived") { string sAliasString = this.BuildQueryString_PipelineSummary(sRegionID, sDivisionID, sBranchID, sDateType, sFromDate, sToDate, sStageAlias, string.Empty, sStageFilter); sPipelineUrl = "Pipeline/ProcessingPipelineSummary.aspx?q=" + Encrypter.Base64Encode(sAliasString); } LoanAnaylysisRow["Href"] = sPipelineUrl; #endregion } else { #region Amount object oLoanAmount = null; //oLoanAmount = UserLoanList.Compute("Sum(Amount)", "Stage='" + sStageName + "'"); oLoanAmount = UserLoanList.Compute("Sum(Amount)", "Stage='" + sStageAlias + "'"); //gdc CR40 object oLoanTotal = null; oLoanTotal = UserLoanList.Compute("Count(Amount)", "Stage='" + sStageAlias + "'"); decimal dLoanAmount = decimal.Zero; int iLoanTotal = 0; if ((oLoanAmount != null) && (oLoanAmount != DBNull.Value)) { dLoanAmount = Convert.ToDecimal(oLoanAmount, null); } //gdc CR40 if ((oLoanTotal != null) && (oLoanTotal != DBNull.Value)) { iLoanTotal = Convert.ToInt32(oLoanTotal, null); } LoanAnaylysisRow["Amount"] = dLoanAmount; LoanAnaylysisRow["LoanCounts"] = iLoanTotal; //gdc CR40 #endregion #region Href string sPipelineUrl = string.Empty; if (sWorkflowType == "Processing") { string sAliasString = this.BuildQueryString_PipelineSummary(sRegionID, sDivisionID, sBranchID, sDateType, sFromDate, sToDate, sWorkflowType, sStageAlias, sStageFilter); sPipelineUrl = "Pipeline/ProcessingPipelineSummary.aspx?q=" + Encrypter.Base64Encode(sAliasString); } else if (sWorkflowType == "Prospect") { string sAliasString = this.BuildQueryString_PipelineSummary(sRegionID, sDivisionID, sBranchID, sDateType, sFromDate, sToDate, sWorkflowType, sStageAlias, sStageFilter); sPipelineUrl = "Pipeline/ProspectPipelineSummaryLoan.aspx?q=" + Encrypter.Base64Encode(sAliasString); } else if (sWorkflowType == "Archived") { string sAliasString = this.BuildQueryString_PipelineSummary(sRegionID, sDivisionID, sBranchID, sDateType, sFromDate, sToDate, sStageAlias, string.Empty, sStageFilter); sPipelineUrl = "Pipeline/ProcessingPipelineSummary.aspx?q=" + Encrypter.Base64Encode(sAliasString); } string sHref = sPipelineUrl; LoanAnaylysisRow["Href"] = sHref; #endregion } } #endregion this.rptLoanAnalysis.DataSource = this.LoanAnalysisData; this.rptLoanAnalysis.DataBind(); #endregion #region peter's codes string strRootUrl = ""; if (null != ConfigurationManager.AppSettings["WPOWARootUrl"]) { strRootUrl = ConfigurationManager.AppSettings["WPOWARootUrl"]; } try { OWAInboxPart myInbox = new OWAInboxPart(); myInbox.OWAServerAddressRoot = strRootUrl; myInbox.ViewName = ConfigurationManager.AppSettings["WPOWAInboxViewName"]; this.phInbox.Controls.Add(myInbox); } catch (Exception ex) { Label lbl = new Label(); lbl.Text = "Failed to load Webpart OWAInbox error: " + ex.Message; this.phInbox.Controls.Add(lbl); LPLog.LogMessage(LogType.Logerror, "Failed to load Webpart OWAInbox error: " + ex.Message); } try { OWACalendarPart myCalendar = new OWACalendarPart(); myCalendar.OWAServerAddressRoot = strRootUrl; myCalendar.ViewName = ConfigurationManager.AppSettings["WPOWACalendarViewName"]; this.phMyCalendar.Controls.Add(myCalendar); } catch (Exception ex) { Label lbl = new Label(); lbl.Text = "Failed to load Webpart OWACalendar error: " + ex.Message; this.phMyCalendar.Controls.Add(lbl); LPLog.LogMessage(LogType.Logerror, "Failed to load Webpart OWACalendar error: " + ex.Message); } SPWeb web = this.Web; //SPList spList = web.Lists[System.Configuration.ConfigurationManager.AppSettings["WPComAnnName"]]; //SPView spView = spList.Views[System.Configuration.ConfigurationManager.AppSettings["WPComAnnViewName"]]; //this.xlvwpComAnn.ListId = spList.ID; //this.xlvwpComAnn.ListName = string.Format("{{{0}}}", spList.ID.ToString()); //this.xlvwpComAnn.ViewGuid = spView.ID.ToString(); #region =====show company announcement webpart===== if (this.CurrentUser.userRole.Announcements == true) { this.divCompanyAnn.Visible = true; } else { this.divCompanyAnn.Visible = false; } // User Home Profile if (UserHomePref2 != null) { if (UserHomePref2.Announcements == true) { this.divCompanyAnn.Visible = true; } else { this.divCompanyAnn.Visible = false; } } if (this.divCompanyAnn.Visible == true) { SPList spListComAnn = null; SPView spViewComAnn = null; try { spListComAnn = web.Lists[System.Configuration.ConfigurationManager.AppSettings["WPComAnnName"]]; } catch { spListComAnn = null; } if (null != spListComAnn) { try { spViewComAnn = spListComAnn.Views[System.Configuration.ConfigurationManager.AppSettings["WPComAnnViewName"]]; } catch { spViewComAnn = null; } if (null != spViewComAnn) { strComAnnListUrl = spListComAnn.DefaultViewUrl; XsltListViewWebPart xlvwpComAnn = new XsltListViewWebPart(); xlvwpComAnn.ListId = spListComAnn.ID; xlvwpComAnn.ListName = string.Format("{{{0}}}", spListComAnn.ID.ToString()); xlvwpComAnn.ViewGuid = spViewComAnn.ID.ToString(); //xlvwpComAnn.Toolbar = "None"; xlvwpComAnn.XmlDefinition = @" <View Name=""{EC6E2014-F0A2-4273-B6BC-1A9F00110341}"" MobileView=""TRUE"" Type=""HTML"" Hidden=""TRUE"" DisplayName="""" Url=""/SitePages/Home.aspx"" Level=""1"" BaseViewID=""1"" ContentTypeID=""0x"" ImageUrl=""/_layouts/images/announce.png""> <Query> <OrderBy> <FieldRef Name=""Modified"" Ascending=""FALSE""/> </OrderBy> </Query> <ViewFields> <FieldRef Name=""LinkTitle""/> </ViewFields> <RowLimit Paged=""TRUE"">5</RowLimit> <Toolbar Type=""None""/> </View>"; xlvwpComAnn.Xsl = @" <xsl:stylesheet xmlns:x=""http://www.w3.org/2001/XMLSchema"" xmlns:d=""http://schemas.microsoft.com/sharepoint/dsp"" version=""1.0"" exclude-result-prefixes=""xsl msxsl ddwrt"" xmlns:ddwrt=""http://schemas.microsoft.com/WebParts/v2/DataView/runtime"" xmlns:asp=""http://schemas.microsoft.com/ASPNET/20"" xmlns:__designer=""http://schemas.microsoft.com/WebParts/v2/DataView/designer"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" xmlns:msxsl=""urn:schemas-microsoft-com:xslt"" xmlns:SharePoint=""Microsoft.SharePoint.WebControls"" xmlns:ddwrt2=""urn:frontpage:internal"" xmlns:o=""urn:schemas-microsoft-com:office:office""> <xsl:include href=""/_layouts/xsl/main.xsl""/> <xsl:include href=""/_layouts/xsl/internal.xsl""/> <xsl:param name=""AllRows"" select=""/dsQueryResponse/Rows/Row[$EntityName = '' or (position() >= $FirstRow and position() <= $LastRow)]""/> <xsl:param name=""dvt_apos"">'</xsl:param> <xsl:template name=""FieldRef_ValueOf.Modified"" ddwrt:dvt_mode=""body"" ddwrt:ghost="""" xmlns:ddwrt2=""urn:frontpage:internal""> <xsl:param name=""thisNode"" select="".""/> <span style=""color: #FF00FF""> <xsl:value-of select=""$thisNode/@*[name()=current()/@Name]"" /> </span> </xsl:template> </xsl:stylesheet>"; this.phComAnn.Controls.Add(xlvwpComAnn); } else { Label lbl = new Label(); lbl.Text = string.Format("Can not find the specified webpart view with name \"{0}\".", System.Configuration.ConfigurationManager.AppSettings["WPComAnnViewName"]); this.phComAnn.Controls.Add(lbl); } } else { Label lbl = new Label(); lbl.Text = string.Format("Can not find the specified webpart with name \"{0}\".", System.Configuration.ConfigurationManager.AppSettings["WPComAnnName"]); this.phComAnn.Controls.Add(lbl); } } #endregion #region =====show company calendar webpart===== if (this.CurrentUser.userRole.CompanyCalendar == true) { this.divComCal.Visible = true; } else { this.divComCal.Visible = false; } // User Home Profile if (UserHomePref2 != null) { if (UserHomePref2.CompanyCalendar == true) { this.divComCal.Visible = true; } else { this.divComCal.Visible = false; } } if (this.divComCal.Visible == true) { SPList spListComCal = null; SPView spViewComCal = null; try { spListComCal = web.Lists[System.Configuration.ConfigurationManager.AppSettings["WPComCalName"]]; } catch { spListComCal = null; } if (null != spListComCal) { try { spViewComCal = spListComCal.Views[System.Configuration.ConfigurationManager.AppSettings["WPComCalViewName"]]; } catch { spViewComCal = null; } if (null != spViewComCal) { strComCalListUrl = spListComCal.DefaultViewUrl; XsltListViewWebPart xlvwpComCal = new XsltListViewWebPart(); xlvwpComCal.ListId = spListComCal.ID; xlvwpComCal.ListName = string.Format("{{{0}}}", spListComCal.ID.ToString()); xlvwpComCal.ViewGuid = spViewComCal.ID.ToString(); //xlvwpComCal.Toolbar = "None"; xlvwpComCal.XmlDefinition = @"<View Name=""{3A64E1C5-8CDF-418C-A94F-5E66F61EB5CF}"" MobileView=""TRUE"" Type=""HTML"" Hidden=""TRUE"" DisplayName="""" Url=""/SitePages/Test webparts.aspx"" Level=""1"" BaseViewID=""2"" ContentTypeID=""0x"" MobileUrl=""_layouts/mobile/viewdaily.aspx"" ImageUrl=""/_layouts/images/events.png""> <Query> <Where> <DateRangesOverlap> <FieldRef Name=""EventDate""/> <FieldRef Name=""EndDate""/> <FieldRef Name=""RecurrenceID""/> <Value Type=""DateTime""> <Month/> </Value> </DateRangesOverlap> </Where> </Query> <ViewFields> <FieldRef Name=""Title""/> <FieldRef Name=""EventDate""/> </ViewFields> <Toolbar Type=""None""/> </View>" ; xlvwpComCal.Xsl = @"<xsl:stylesheet xmlns:x=""http://www.w3.org/2001/XMLSchema"" xmlns:d=""http://schemas.microsoft.com/sharepoint/dsp"" version=""1.0"" exclude-result-prefixes=""xsl msxsl ddwrt"" xmlns:ddwrt=""http://schemas.microsoft.com/WebParts/v2/DataView/runtime"" xmlns:asp=""http://schemas.microsoft.com/ASPNET/20"" xmlns:__designer=""http://schemas.microsoft.com/WebParts/v2/DataView/designer"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" xmlns:msxsl=""urn:schemas-microsoft-com:xslt"" xmlns:SharePoint=""Microsoft.SharePoint.WebControls"" xmlns:ddwrt2=""urn:frontpage:internal"" xmlns:o=""urn:schemas-microsoft-com:office:office""> <xsl:include href=""/_layouts/xsl/main.xsl""/> <xsl:include href=""/_layouts/xsl/internal.xsl""/> <xsl:param name=""AllRows"" select=""/dsQueryResponse/Rows/Row[$EntityName = '' or (position() >= $FirstRow and position() <= $LastRow)]""/> <xsl:param name=""dvt_apos"">'</xsl:param> <xsl:template name=""FieldRef_Recurrence_body.fRecurrence"" ddwrt:dvt_mode=""body"" match=""FieldRef[@Name='fRecurrence']"" mode=""Recurrence_body"" ddwrt:ghost="""" xmlns:ddwrt2=""urn:frontpage:internal""> <xsl:param name=""thisNode"" select="".""/> <xsl:variable name=""fRecurrence"" select=""$thisNode/@*[name()=current()/@Name]""/> <xsl:variable name=""src"">/_layouts/images/ <xsl:choose> <xsl:when test=""$fRecurrence='1'""> <xsl:choose> <xsl:when test=""$thisNode/@EventType='3'"">recurEx.gif</xsl:when> <xsl:when test=""$thisNode/@EventType='4'"">recurEx.gif</xsl:when> <xsl:otherwise>recur.gif</xsl:otherwise> </xsl:choose> </xsl:when> <xsl:otherwise>blank.gif</xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name=""alt""> <xsl:if test=""$fRecurrence='1'""> <xsl:choose> <xsl:when test=""@EventType='3'""> <xsl:value-of select=""'Exception to Recurring Event'""/> </xsl:when> <xsl:when test=""@EventType='4'""> <xsl:value-of select=""'Exception to Recurring Event'""/> </xsl:when> <xsl:otherwise> <xsl:value-of select=""'Recurring Event'""/> </xsl:otherwise> </xsl:choose> </xsl:if> </xsl:variable> <img border=""0"" width=""16"" height=""16"" src=""/_layouts/images/ blank.gif"" alt=""{$alt}"" title=""{$alt}""/> </xsl:template></xsl:stylesheet>"; this.phComCal.Controls.Add(xlvwpComCal); } else { Label lbl = new Label(); lbl.Text = string.Format("Can not find the specified webpart view with name \"{0}\".", System.Configuration.ConfigurationManager.AppSettings["WPComCalViewName"]); this.phComCal.Controls.Add(lbl); } } else { Label lbl = new Label(); lbl.Text = string.Format("Can not find the specified webpart with name \"{0}\".", System.Configuration.ConfigurationManager.AppSettings["WPComCalName"]); this.phComCal.Controls.Add(lbl); } } #endregion #region =====show rates sheet webpart===== if (this.CurrentUser.userRole.RateSummary == true) { this.divRates.Visible = true; } else { this.divRates.Visible = false; } // User Home Profile if (UserHomePref2 != null) { if (UserHomePref2.RateSummary == true) { this.divRates.Visible = true; } else { this.divRates.Visible = false; } } if (this.divRates.Visible == true) { SPList spListRates = null; SPView spViewRates = null; try { spListRates = web.Lists[System.Configuration.ConfigurationManager.AppSettings["WPRatesName"]]; } catch { spListRates = null; } if (null != spListRates) { try { spViewRates = spListRates.Views[System.Configuration.ConfigurationManager.AppSettings["WPRatesViewName"]]; } catch { spViewRates = null; } if (null != spViewRates) { strRatesListUrl = spListRates.DefaultViewUrl; XsltListViewWebPart xlvwpRates = new XsltListViewWebPart(); xlvwpRates.ListId = spListRates.ID; xlvwpRates.ListName = string.Format("{{{0}}}", spListRates.ID.ToString()); xlvwpRates.ViewGuid = spViewRates.ID.ToString(); //xlvwpRates.Toolbar = "None"; xlvwpRates.XmlDefinition = @"<View Name=""{FE66F61E-EBF7-49E8-BD37-F9955793DDCE}"" MobileView=""TRUE"" Type=""HTML"" Hidden=""TRUE"" DisplayName="""" Url=""/SitePages/Test webparts.aspx"" Level=""1"" BaseViewID=""1"" ContentTypeID=""0x"" ImageUrl=""/_layouts/images/dlicon.png""> <Query> <OrderBy> <FieldRef Name=""FileLeafRef""/> </OrderBy> </Query> <ViewFields> <FieldRef Name=""LinkFilename""/> </ViewFields> <RowLimit Paged=""TRUE"">30</RowLimit> <Toolbar Type=""None""/> </View>" ; xlvwpRates.Xsl = @" <xsl:stylesheet xmlns:x=""http://www.w3.org/2001/XMLSchema"" xmlns:d=""http://schemas.microsoft.com/sharepoint/dsp"" version=""1.0"" exclude-result-prefixes=""xsl msxsl ddwrt"" xmlns:ddwrt=""http://schemas.microsoft.com/WebParts/v2/DataView/runtime"" xmlns:asp=""http://schemas.microsoft.com/ASPNET/20"" xmlns:__designer=""http://schemas.microsoft.com/WebParts/v2/DataView/designer"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" xmlns:msxsl=""urn:schemas-microsoft-com:xslt"" xmlns:SharePoint=""Microsoft.SharePoint.WebControls"" xmlns:ddwrt2=""urn:frontpage:internal"" xmlns:o=""urn:schemas-microsoft-com:office:office""> <xsl:include href=""/_layouts/xsl/main.xsl""/> <xsl:include href=""/_layouts/xsl/internal.xsl""/> <xsl:param name=""AllRows"" select=""/dsQueryResponse/Rows/Row[$EntityName = '' or (position() >= $FirstRow and position() <= $LastRow)]""/> <xsl:param name=""dvt_apos"">'</xsl:param> <xsl:template name=""FieldRef_ValueOf.Modified"" ddwrt:dvt_mode=""body"" ddwrt:ghost="""" xmlns:ddwrt2=""urn:frontpage:internal""> <xsl:param name=""thisNode"" select="".""/> <span style=""color: #FF00FF""> <xsl:value-of select=""$thisNode/@*[name()=current()/@Name]"" /> </span> </xsl:template> </xsl:stylesheet>"; this.phRates.Controls.Add(xlvwpRates); } else { Label lbl = new Label(); lbl.Text = string.Format("Can not find the specified webpart view with name \"{0}\".", System.Configuration.ConfigurationManager.AppSettings["WPComCalViewName"]); this.phRates.Controls.Add(lbl); } } else { Label lbl = new Label(); lbl.Text = string.Format("Can not find the specified webpart with name \"{0}\".", System.Configuration.ConfigurationManager.AppSettings["WPRatesName"]); this.phRates.Controls.Add(lbl); } } #endregion #endregion }
// Uncomment the method below to handle the event raised after a feature has been activated. public override void FeatureActivated(SPFeatureReceiverProperties properties) { try { Global.Debug = "start"; SPWeb web = properties.Feature.Parent as SPWeb; if (web == null) { } Global.URL = "Tillsyn FeatureActivated: " + web.Url; SPList listKundkort = web.Lists.TryGetList("Kundkort"); Global.Debug = "Kundkort"; SPList listAktiviteter = web.Lists.TryGetList("Aktiviteter"); Global.Debug = "Aktiviteter"; SPList listAdresser = web.Lists.TryGetList("Adresser"); Global.Debug = "Adresser"; SPList listAgare = web.Lists.TryGetList("Ägare"); Global.Debug = "Ägare"; SPList listKontakter = web.Lists.TryGetList("Kontakter"); Global.Debug = "Kontakter"; if (!web.Properties.ContainsKey("activatedOnce")) { web.Properties.Add("activatedOnce", "true"); web.Properties.Update(); Global.Debug = "set activatedOnce flag"; #region sätt default-kommun-värden if (municipals.Count > 0) { Global.WriteLog("Kommuner existerar redan", EventLogEntryType.Information, 1000); } else { municipals.Add("uppsala", new Municipal { AreaCode = "018", Name = "Uppsala", RegionLetter = "C" }); municipals.Add("borlänge", new Municipal { AreaCode = "0243", Name = "Borlänge", RegionLetter = "W" }); } Global.Debug = "added municipals"; #endregion #region hämta listor //SPList listAgare = web.Lists.TryGetList("Ägare"); //Global.Debug = "Ägare"; //SPList listKontakter = web.Lists.TryGetList("Kontakter"); //Global.Debug = "Kontakter"; //SPList listAdresser = web.Lists.TryGetList("Adresser"); //Global.Debug = "Adresser"; SPList listSidor = web.Lists.TryGetList("Webbplatssidor"); Global.Debug = "Webbplatssidor"; SPList listNyheter = web.Lists.TryGetList("Senaste nytt"); Global.Debug = "Senaste nytt"; //SPList listBlanketter = web.Lists.TryGetList("Blanketter"); SPList listGenvagar = web.Lists.TryGetList("Genvägar"); Global.Debug = "Genvägar"; SPList listGruppkopplingar = web.Lists.TryGetList("Gruppkopplingar"); Global.Debug = "Gruppkopplingar"; SPList listGenvagarTillsynsverktyg = web.Lists.TryGetList("Genvägar för tillsynsverktyg"); Global.Debug = "Genvägar för tillsynsverktyg"; SPList listUppgifter = web.Lists.TryGetList("Uppgifter"); Global.Debug = "Uppgifter"; SPList listDokument = web.Lists.TryGetList("Dokument"); Global.Debug = "Dokument"; SPList[] lists = new SPList[] { listAgare, listKontakter, listAdresser, listSidor, listNyheter, listGenvagar, listGruppkopplingar, listGenvagarTillsynsverktyg, listUppgifter, listDokument }; int i = 0; foreach (SPList list in lists) { i++; if (list == null) { Global.WriteLog("Lista " + i.ToString() + " är null", EventLogEntryType.Error, 2000); } } #endregion var roleRead = web.RoleDefinitions.GetByType(SPRoleType.Reader); var roleEdit = web.RoleDefinitions.GetByType(SPRoleType.Editor); SPRoleAssignment assignmentVisitorRead = new SPRoleAssignment(web.AssociatedVisitorGroup); SPRoleAssignment assignmentMemberEdit = new SPRoleAssignment(web.AssociatedMemberGroup); assignmentVisitorRead.RoleDefinitionBindings.Add(roleRead); assignmentMemberEdit.RoleDefinitionBindings.Add(roleEdit); if (listSidor != null) { #region startsida string compoundUrl = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Start.aspx"); //* Define page payout _wikiFullContent = FormatBasicWikiLayout(); Global.Debug = "Skapa startsida"; SPFile startsida = listSidor.RootFolder.Files.Add(compoundUrl, SPTemplateFileType.WikiPage); // Header string relativeUrl = web.ServerRelativeUrl == "/" ? "" : web.ServerRelativeUrl; _wikiFullContent = _wikiFullContent.Replace("[[HEADER]]", "<img alt=\"vinter\" src=\"" + relativeUrl + "/SiteAssets/profil_ettan_vinter_557x100.jpg\" style=\"margin: 5px;\"/><img alt=\"hjärta\" src=\"" + relativeUrl + "/SiteAssets/heart.gif\" style=\"margin: 5px;\"/>"); #region Nyheter ListViewWebPart wpAnnouncements = new ListViewWebPart(); wpAnnouncements.Width = "600px"; wpAnnouncements.ListName = listNyheter.ID.ToString("B").ToUpper(); //wpAnnouncements.ViewGuid = listNyheter.GetUncustomizedViewByBaseViewId(0).ID.ToString("B").ToUpper(); //wpAnnouncements.ViewGuid = listNyheter.DefaultView.ID.ToString("B").ToUpper(); wpAnnouncements.ViewGuid = string.Empty; Guid wpAnnouncementsGuid = AddWebPartControlToPage(startsida, wpAnnouncements); AddWebPartMarkUpToPage(wpAnnouncementsGuid, "[[COL1]]"); #endregion #region Genvägar ListViewWebPart wpLinks = new ListViewWebPart(); wpLinks.ListName = listGenvagar.ID.ToString("B").ToUpper(); //wpLinks.ViewGuid = listGenvagar.GetUncustomizedViewByBaseViewId(0).ID.ToString("B").ToUpper(); //wpLinks.ViewGuid = listGenvagar.DefaultView.ID.ToString("B").ToUpper(); wpLinks.ViewGuid = string.Empty; Guid wpLinksGuid = AddWebPartControlToPage(startsida, wpLinks); AddWebPartMarkUpToPage(wpLinksGuid, "[[COL2]]"); #endregion startsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent; startsida.Item.UpdateOverwriteVersion(); Global.Debug = "Startsida skapad"; #endregion #region lägg till försäljningsställe string compoundUrl2 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Lägg till försäljningsställe.aspx"); //* Define page payout _wikiFullContent = FormatSimpleWikiLayout(); Global.Debug = "Skapa nybutiksida"; SPFile nybutiksida = listSidor.RootFolder.Files.Add(compoundUrl2, SPTemplateFileType.WikiPage); // Header _wikiFullContent = _wikiFullContent.Replace("[[COL1]]", @"<h1>Steg-för-steg - Lägg till nytt försäljningsställe</h1> För att underlätta inläggningen av nya försäljningställen för steg-för-steg guiden nedan. I de första stegen lägger du in information kring försäljningsstället, i det näst sista stegen kopplar du ihop angivna uppgifter och i det sista steg sätter du behörighet på försäljningsställets innehåll i portalen.<br /> <br /> Du skapar ett nytt objekt via länken <b>Nytt objekt</b>. Ange önskad information och tryck <b>Spara</b>. Fält markerade med * är obligatoriska.<br /> <h2>STEG 1 - Lägg till ägare</h2> Registrera ägaren, dvs organisationsnumret för försäljningsstället. <br /> Ange <b>juridiskt namn</b>, <b>adressuppgifter</b> och <b>organisationsnummer</b>.<br /> [[WP1]] <h2>STEG 2 - Lägg till adressuppgifter</h2> Adressuppgifterna till försäljningsstället. <br /> Här anger du <b>försäljningsställets namn</b>, <b>besöksadress</b> och <b>telefon</b>/<b>e-post</b>.<br /> [[WP2]] <h2>STEG 3 - Lägg till kontaktperson</h2> Lägg till de kontaktpersoner som finns för försäljningsstället.<br /> Ange <b>efternamn</b>, <b>förnamn</b>, <b>befattning</b>, <b>företag</b>, <b>telefon</b>, <b>mobil</b> och <b>e-postadress</b>.<br /> [[WP3]] <h2>STEG 4 - Lägg till försäljningsstället</h2> För att slutföra inläggningen av försäljningstället måste du koppla ihop uppgifterna ovan. <br /> Välj Nytt objekt, ange försäljningsstället i fältet <b>Adress</b>, Ägande organisation i <b>Ägare</b> och lägg till önskade <b>kontaktpersoner</b>.<br /> [[WP4]] <h2>STEG 5 - Ge rättigheter</h2> För att ge rätt behörigheter för innehållet kring försäljningsstället måste rättigheter anges. <br /> <br /> Klicka på det nyligen tillagda försäljningsstället i listan <b>Lägg till försäljningsställe</b> (ovan) och välj <b>Ge rättigheter</b>."); Global.Debug = "wpAgare"; XsltListViewWebPart wpAgare = new XsltListViewWebPart(); wpAgare.ChromeType = PartChromeType.None; wpAgare.ListName = listAgare.ID.ToString("B").ToUpper(); wpAgare.ViewGuid = listAgare.Views["Tilläggsvy"].ID.ToString("B").ToUpper(); wpAgare.Toolbar = "Standard"; Guid wpAgareGuid = AddWebPartControlToPage(nybutiksida, wpAgare); AddWebPartMarkUpToPage(wpAgareGuid, "[[WP1]]"); Global.Debug = "wpAdresser"; XsltListViewWebPart wpAdresser = new XsltListViewWebPart(); wpAdresser.ChromeType = PartChromeType.None; wpAdresser.ListName = listAdresser.ID.ToString("B").ToUpper(); wpAdresser.ViewGuid = listAdresser.Views["Tilläggsvy"].ID.ToString("B").ToUpper(); wpAdresser.Toolbar = "Standard"; Guid wpAdresserGuid = AddWebPartControlToPage(nybutiksida, wpAdresser); AddWebPartMarkUpToPage(wpAdresserGuid, "[[WP2]]"); Global.Debug = "wpKontakter"; XsltListViewWebPart wpKontakter = new XsltListViewWebPart(); wpKontakter.ChromeType = PartChromeType.None; wpKontakter.ListName = listKontakter.ID.ToString("B").ToUpper(); wpKontakter.ViewGuid = listKontakter.Views["Tilläggsvy"].ID.ToString("B").ToUpper(); wpKontakter.Toolbar = "Standard"; Guid wpKontakterGuid = AddWebPartControlToPage(nybutiksida, wpKontakter); AddWebPartMarkUpToPage(wpKontakterGuid, "[[WP3]]"); Global.Debug = "wpKundkort"; XsltListViewWebPart wpKundkort = new XsltListViewWebPart(); wpKundkort.ChromeType = PartChromeType.None; wpKundkort.ListName = listKundkort.ID.ToString("B").ToUpper(); wpKundkort.ViewGuid = listKundkort.Views["Tilläggsvy"].ID.ToString("B").ToUpper(); wpKundkort.Toolbar = "Standard"; Guid wpKundkortGuid = AddWebPartControlToPage(nybutiksida, wpKundkort); AddWebPartMarkUpToPage(wpKundkortGuid, "[[WP4]]"); nybutiksida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent; nybutiksida.Item.UpdateOverwriteVersion(); Global.Debug = "Nybutiksida skapad"; #endregion #region mitt försäljningsställe string compoundUrl3 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Mitt försäljningsställe.aspx");//* Define page payout _wikiFullContent = FormatSimpleWikiLayout(); Global.Debug = "Skapa minbutiksida"; SPFile minbutiksida = listSidor.RootFolder.Files.Add(compoundUrl3, SPTemplateFileType.WikiPage); Global.Debug = "wpMinButik"; MinButikWP wpMinButik = new MinButikWP(); wpMinButik.ChromeType = PartChromeType.None; wpMinButik.Adresser = "Adresser"; wpMinButik.Agare = "Ägare"; wpMinButik.Kontakter = "Kontakter"; wpMinButik.Kundkort = "Kundkort"; Guid wpMinButikGuid = AddWebPartControlToPage(minbutiksida, wpMinButik); AddWebPartMarkUpToPage(wpMinButikGuid, "[[COL1]]"); minbutiksida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent; minbutiksida.Item.UpdateOverwriteVersion(); Global.Debug = "Nybutiksida skapad"; #endregion #region skapa tillsynsrapport //string compoundUrl4 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Skapa tillsynsrapport.aspx");//* Define page payout //_wikiFullContent = FormatSimpleWikiLayout(); //Global.Debug = "Skapa tillsynsrapport"; //SPFile skapatillsynsida = listSidor.RootFolder.Files.Add(compoundUrl4, SPTemplateFileType.WikiPage); //Global.Debug = "wpTillsyn"; //TillsynWP wpTillsyn = new TillsynWP(); //wpTillsyn.ChromeType = PartChromeType.None; //Guid wpTillsynGuid = AddWebPartControlToPage(skapatillsynsida, wpTillsyn); //AddWebPartMarkUpToPage(wpTillsynGuid, "[[COL1]]"); //skapatillsynsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent; //skapatillsynsida.Item.UpdateOverwriteVersion(); //Global.Debug = "Skapatillsynsida skapad"; #endregion #region tillsynsverktyg string compoundUrl5 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Tillsynsverktyg.aspx");//* Define page payout _wikiFullContent = FormatBasicWikiLayout().Replace("[[HEADER]]", "").Replace("[[COL1]]", "[[WP1]][[WP2]]"); Global.Debug = "Tillsynsverktyg"; SPFile tillsynsverktygsida = listSidor.RootFolder.Files.Add(compoundUrl5, SPTemplateFileType.WikiPage); #region Att göra ListViewWebPart wpTodo = new ListViewWebPart(); wpTodo.ListName = listUppgifter.ID.ToString("B").ToUpper(); wpTodo.ViewGuid = listUppgifter.DefaultView.ID.ToString("B").ToUpper(); Guid wpTodoGuid = AddWebPartControlToPage(tillsynsverktygsida, wpTodo); AddWebPartMarkUpToPage(wpTodoGuid, "[[WP1]]"); #endregion #region Senaste aktiviteterna ListViewWebPart wpLatest = new ListViewWebPart(); wpLatest.ListName = listAktiviteter.ID.ToString("B").ToUpper(); wpLatest.ViewGuid = string.Empty; Guid wpLatestGuid = AddWebPartControlToPage(tillsynsverktygsida, wpLatest); AddWebPartMarkUpToPage(wpLatestGuid, "[[WP2]]"); #endregion #region Genvägar ListViewWebPart wpLinks2 = new ListViewWebPart(); wpLinks2.ListName = listGenvagarTillsynsverktyg.ID.ToString("B").ToUpper(); wpLinks2.ViewGuid = listGenvagarTillsynsverktyg.DefaultView.ID.ToString("B").ToUpper(); Guid wpLinks2Guid = AddWebPartControlToPage(tillsynsverktygsida, wpLinks2); AddWebPartMarkUpToPage(wpLinks2Guid, "[[COL2]]"); #endregion tillsynsverktygsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent; tillsynsverktygsida.Item.BreakRoleInheritance(false); tillsynsverktygsida.Item.RoleAssignments.Add(assignmentMemberEdit); tillsynsverktygsida.Item.UpdateOverwriteVersion(); Global.Debug = "tillsynsverktygsida skapad"; #endregion #region inställningar string compoundUrl6 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Inställningar.aspx");//* Define page payout _wikiFullContent = FormatSimpleWikiLayout(); Global.Debug = "Inställningar"; SPFile installningarsida = listSidor.RootFolder.Files.Add(compoundUrl6, SPTemplateFileType.WikiPage); Global.Debug = "wpSettings"; SettingsWP wpSettings = new SettingsWP(); wpSettings.ChromeType = PartChromeType.None; Guid wpSettingsGuid = AddWebPartControlToPage(installningarsida, wpSettings); AddWebPartMarkUpToPage(wpSettingsGuid, "[[COL1]]"); installningarsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent; installningarsida.Item.BreakRoleInheritance(false); installningarsida.Item.RoleAssignments.Add(assignmentMemberEdit); installningarsida.Item.UpdateOverwriteVersion(); Global.Debug = "Installningarsida skapad"; #endregion } SPListItem item = null; #region debugdata //Global.Debug = "ägare"; //SPListItem item = listAgare.AddItem(); //item["Title"] = "TESTÄGARE AB"; //item[new Guid("0850AE15-19DD-431f-9C2F-3AFF3AE292CE")] = "123456-7890"; //item.Update(); //try { // Global.Debug = "kontakt"; // item = listKontakter.AddItem(); // item["Title"] = "Testsson"; // item["FirstName"] = "Test"; // item["Email"] = "*****@*****.**"; // item["JobTitle"] = "testare"; // item["CellPhone"] = "070 123 4567"; // item.Update(); // item = listKontakter.AddItem(); // item["Title"] = "Jansson"; // item["FirstName"] = "Peter"; // item["Email"] = "*****@*****.**"; // item.Update(); //} //catch (Exception ex) { // Global.WriteLog("Message:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace, EventLogEntryType.Error, 2001); //} //Global.Debug = "adress"; //item = listAdresser.AddItem(); //item["Title"] = "Testbutiken"; //item["Besöksadress"] = "Testgatan 13b"; //item["Postnummer"] = "790 00"; //item["Ort"] = "Borlänge"; //item["Telefon"] = "0243-123456"; //item.Update(); //Global.Debug = "kundkort"; //item = listKundkort.AddItem(); //item["Title"] = "Testbutiken (W0243-1000)"; //item["butikAdress"] = 1; //item["butikAgare"] = 1; //item["butikKontakt1"] = 1; //item["butikKundnummer"] = "W0243-1000"; //item["butikLopnummer"] = "1000"; //item.Update(); #endregion #region nyhet Global.Debug = "nyhet"; item = listNyheter.AddItem(); item["Title"] = "Vår online plattform för tillsyn av tobak och folköl håller på att starta upp här"; item["Body"] = @"Hej! Nu har första stegen till en online plattform för tillsyn av tobak och folköl tagits. Här kan du som försäljningsställe ladda hem blanketter och ta del av utbildningsmaterial. " + web.Title + " kommun"; item.Update(); #endregion #region länkar Global.Debug = "länkar"; item = listGenvagar.AddItem(); Global.Debug = "Blanketter"; item["Title"] = "Blanketter"; item["URL"] = web.ServerRelativeUrl + "/Blanketter, Blanketter"; item.Update(); item = listGenvagar.AddItem(); Global.Debug = "Utbildningsmaterial"; item["Title"] = "Utbildningsmaterial"; item["URL"] = web.ServerRelativeUrl + "/Utbildningsmaterial, Utbildningsmaterial"; item.Update(); item = listGenvagarTillsynsverktyg.AddItem(); Global.Debug = "Lägg till försäljningsställe"; item["Title"] = "Lägg till försäljningsställe"; item["URL"] = web.ServerRelativeUrl + "/SitePages/Lägg%20till%20försäljningsställe.aspx, Lägg till försäljningsställe"; item.Update(); item = listGenvagarTillsynsverktyg.AddItem(); Global.Debug = "Nytt tillsynsprotokoll"; item["Title"] = "Nytt tillsynsprotokoll"; item["URL"] = web.ServerRelativeUrl + "/_layouts/15/listform.aspx?PageType=8&ListId=" + System.Web.HttpUtility.UrlEncode(listAktiviteter.ID.ToString("B")).ToUpper().Replace("-", "%2D") + "&RootFolder=, Nytt tillsynsprotokoll"; item.Update(); #endregion #region sätt kundnummeregenskaper Global.Debug = "löpnummer"; web.Properties.Add("lopnummer", "1000"); Global.Debug = "prefixformel"; web.Properties.Add("prefixFormula", "%B%R-%N"); Global.Debug = "listAdresserGUID"; web.Properties.Add("listAdresserGUID", listAdresser.ID.ToString()); Global.Debug = "listAgareGUID"; web.Properties.Add("listAgareGUID", listAgare.ID.ToString()); Global.Debug = "gruppkopplingar"; web.Properties.Add("listGruppkopplingarGUID", listGruppkopplingar.ID.ToString()); try { Municipal m = municipals[web.Title.ToLower()]; web.Properties.Add("municipalAreaCode", m.AreaCode); web.Properties.Add("municipalRegionLetter", m.RegionLetter); } catch { } Global.Debug = "properties"; web.Properties.Update(); #endregion #region lägg till navigeringslänkar try { SPNavigationNode blanketter = new SPNavigationNode("Blanketter", "Blanketter", false); SPNavigationNode utbildningsmaterial = new SPNavigationNode("Utbildningsmaterial", "Utbildningsmaterial", false); SPNavigationNode minbutik = new SPNavigationNode("Mitt försäljningsställe", "SitePages/Mitt%20försäljningsställe.aspx", false); SPNavigationNode tillsynsverktyg = new SPNavigationNode("Tillsynsverktyg", "SitePages/Tillsynsverktyg.aspx", false); SPNavigationNode dokument = new SPNavigationNode("Dokument", "Documents", false); //dokument.Properties["Audience"] = ";;;;" + web.AssociatedMemberGroup.Name; SPNavigationNode installningar = new SPNavigationNode("Inställningar", "SitePages/Inställningar.aspx", false); web.Navigation.QuickLaunch.AddAsLast(blanketter); web.Navigation.QuickLaunch.AddAsLast(utbildningsmaterial); web.Navigation.QuickLaunch.AddAsLast(minbutik); web.Navigation.QuickLaunch.AddAsLast(tillsynsverktyg); SPNavigationNode senaste = SPNavigationSiteMapNode.CreateSPNavigationNode("Hantera Senaste Nytt", "Lists/Nyheter/AllItems.aspx", NodeTypes.Default, web.Navigation.QuickLaunch); senaste.Properties.Add("Audience", ";;;;" + web.AssociatedMemberGroup.Name); web.Navigation.QuickLaunch.AddAsLast(dokument); web.Navigation.QuickLaunch.AddAsLast(installningar); SPNavigationNode uppgifter = new SPNavigationNode("Att göra", "Lists/Uppgifter", false); SPNavigationNode aktiviteter = new SPNavigationNode("Aktiviteter", "Lists/Aktiviteter", false); SPNavigationNode kundkort = new SPNavigationNode("Försäljningsställen", "Lists/Kundkort", false); //SPNavigationNode forsaljningsstallen = new SPNavigationNode("Försäljningsställen", "Lists/Adresser", false); SPNavigationNode kontakter = new SPNavigationNode("Kontakter", "Lists/Kundkort/Kontaktlista.aspx", false); SPNavigationNode agare = new SPNavigationNode("Ägare", "Lists/Agare", false); //SPNavigationNode forsaljningstillstand = new SPNavigationNode("Försäljningstillstånd", "Lists/Forsaljningstillstand"); SPNavigationNode laggtill = new SPNavigationNode("Lägg till försäljningsställe", "SitePages/Lägg%20till%20försäljningsställe.aspx", false); SPNavigationNode editkontakter = new SPNavigationNode("Redigera kontakter", "Lists/Kontakter/Redigeringsvy.aspx", false); SPNavigationNode editagare = new SPNavigationNode("Redigera ägare", "Lists/Agare/Redigeringsvy.aspx", false); SPNavigationNode editadresser = new SPNavigationNode("Redigera adresser", "Lists/Adresser/Redigeringsvy.aspx", false); tillsynsverktyg.Children.AddAsFirst(uppgifter); tillsynsverktyg.Children.AddAsLast(aktiviteter); tillsynsverktyg.Children.AddAsLast(kundkort); // tillsynsverktyg.Children.AddAsLast(forsaljningsstallen); tillsynsverktyg.Children.AddAsLast(kontakter); tillsynsverktyg.Children.AddAsLast(agare); tillsynsverktyg.Children.AddAsLast(laggtill); tillsynsverktyg.Children.AddAsLast(editkontakter); tillsynsverktyg.Children.AddAsLast(editagare); tillsynsverktyg.Children.AddAsLast(editadresser); } catch (Exception ex) { Global.WriteLog("lägg till navigeringslänkar\r\n\r\nMessage:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace, EventLogEntryType.Error, 2001); } #endregion #region sätt rättigheter try { Global.Debug = "1"; listGenvagarTillsynsverktyg.BreakRoleInheritance(false); listGenvagarTillsynsverktyg.RoleAssignments.Add(assignmentMemberEdit); listGenvagarTillsynsverktyg.Update(); Global.Debug = "5"; listDokument.BreakRoleInheritance(false); listDokument.RoleAssignments.Add(assignmentMemberEdit); listDokument.Update(); //listKundkort.BreakRoleInheritance(true); //listKundkort.RoleAssignments.Remove(web.AssociatedVisitorGroup); //listKundkort.RoleAssignments.AddToCurrentScopeOnly(assignmentVisitorRead); //listKundkort.Update(); //listAgare.BreakRoleInheritance(true); //listAgare.RoleAssignments.Remove(web.AssociatedVisitorGroup); //listAgare.RoleAssignments.AddToCurrentScopeOnly(assignmentVisitorRead); //listAgare.Update(); //listAdresser.BreakRoleInheritance(true); //listAdresser.RoleAssignments.Remove(web.AssociatedVisitorGroup); //listAdresser.RoleAssignments.AddToCurrentScopeOnly(assignmentVisitorRead); //listAdresser.Update(); } catch (Exception ex) { Global.WriteLog("sätt rättigheter\r\n\r\nMessage:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace + "\r\n\r\nDebug:\r\n" + Global.Debug, EventLogEntryType.Error, 2001); } #endregion } else { Global.WriteLog("Redan aktiverad", EventLogEntryType.Information, 1000); } #region modify template global Global.Debug = "ensure empty working directory"; DirectoryInfo diFeature = new DirectoryInfo(@"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\UPCOR.TillsynKommun"); string webid = web.Url.Replace("http://", "").Replace('/', '_'); string dirname_insp = @"workdir_inspection_" + webid; string dirname_perm = @"workdir_permit_" + webid; DirectoryInfo diWorkDirInspection = diFeature.CreateSubdirectory(dirname_insp); DirectoryInfo diWorkDirPermit = diFeature.CreateSubdirectory(dirname_perm); if (!diWorkDirInspection.Exists) diWorkDirInspection.Create(); if (!diWorkDirPermit.Exists) diWorkDirPermit.Create(); XNamespace xsf = "http://schemas.microsoft.com/office/infopath/2003/solutionDefinition"; XNamespace xsf2 = "http://schemas.microsoft.com/office/infopath/2006/solutionDefinition/extensions"; XNamespace xsf3 = "http://schemas.microsoft.com/office/infopath/2009/solutionDefinition/extensions"; XNamespace xd = "http://schemas.microsoft.com/office/infopath/2003"; XNamespace rs = "urn:schemas-microsoft-com:rowset"; XNamespace z = "#RowsetSchema"; #endregion #region modify template tillsyn { Global.Debug = "deleting files"; foreach (FileInfo fi in diWorkDirInspection.GetFiles()) { fi.Delete(); } #region extract Global.Debug = "extract"; Process p = new Process(); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.StartInfo.FileName = @"C:\Program Files\7-Zip\7z.exe"; //string filename = diTillsyn.FullName + @"\75841904-0c67-4118-826f-b1319db35c6a.xsn"; //string filename = diFeature.FullName + @"\4BEB6318-1CE0-47BE-92C2-E9815D312C1A.xsn"; //string filename = diFeature.FullName + @"\inspection.xsn"; string filename = diFeature.FullName + @"\inspection4.xsn"; p.StartInfo.Arguments = "e \"" + filename + "\" -y -o\"" + diWorkDirInspection.FullName + "\""; bool start = p.Start(); p.WaitForExit(); if (p.ExitCode != 0) { Global.WriteLog(string.Format("7z Error:\r\n{0}\r\n\r\nFilename:\r\n{1}", p.StandardOutput.ReadToEnd(), filename), EventLogEntryType.Error, 1000); } #endregion Global.Debug = "get content type _tillsynName"; SPContentType ctTillsyn = listAktiviteter.ContentTypes[_tillsynName]; #region modify manifest Global.Debug = "modify manifest tillsyn"; XDocument doc = XDocument.Load(diWorkDirInspection.FullName + @"\manifest.xsf"); var xDocumentClass = doc.Element(xsf + "xDocumentClass"); var q1 = from extension in xDocumentClass.Element(xsf + "extensions").Elements(xsf + "extension") where extension.Attribute("name").Value == "SolutionDefinitionExtensions" select extension; var node1 = q1.First().Element(xsf3 + "solutionDefinition").Element(xsf3 + "baseUrl"); node1.Attribute("relativeUrlBase").Value = web.Url + "/Lists/Aktiviteter/" + _tillsynName + "/"; var q2 = from dataObject in xDocumentClass.Element(xsf + "dataObjects").Elements(xsf + "dataObject") //where dataObject.Attribute("name").Value == "Kundkort" select dataObject; foreach (var n in q2) { SPList list = null; switch(n.Attribute("name").Value) { case "Kundkort": case "Kundkort1": list = listKundkort; break; case "Adresser": list = listAdresser; break; case "Ägare": list = listAgare; break; case "Kontakter": list = listKontakter; break; } if (list != null) { var node2 = n.Element(xsf + "query").Element(xsf + "sharepointListAdapterRW"); node2.Attribute("sharePointListID").Value = "{" + list.ID.ToString() + "}"; } } var node3 = xDocumentClass.Element(xsf + "query").Element(xsf + "sharepointListAdapterRW"); node3.Attribute("sharePointListID").Value = "{" + listAktiviteter.ID.ToString() + "}"; node3.Attribute("contentTypeID").Value = ctTillsyn.Id.ToString(); var q3 = q1.First().Element(xsf2 + "solutionDefinition").Element(xsf2 + "dataConnections").Elements(xsf2 + "sharepointListAdapterRWExtension"); foreach (var n in q3) { var oldkey = n.Attribute("queryKey").Value; oldkey = oldkey.Substring(oldkey.IndexOf('<')); oldkey = web.Url + "/" + oldkey; Regex r = new Regex("{.*?}"); Guid newguid = Guid.Empty; switch (n.Attribute("ref").Value) { case "Kundkort1": newguid = listKundkort.ID; break; case "Adresser": newguid = listAdresser.ID; break; case "Ägare": newguid = listAgare.ID; break; case "Kontakter": newguid = listKontakter.ID; break; } n.Attribute("queryKey").Value = r.Replace(oldkey, "{" + newguid.ToString() + "}"); } doc.Save(diWorkDirInspection.FullName + @"\manifest.xsf"); Global.Debug = "modify view1"; XDocument doc2 = XDocument.Load(diWorkDirInspection.FullName + @"\view1.xsl"); foreach (var d in doc2.Descendants("object")) { d.Attribute(xd + "server").Value = web.Url + "/"; } doc2.Save(diWorkDirInspection.FullName + @"\view1.xsl"); Global.Debug = "modify offline files"; foreach (FileInfo fi in diWorkDirInspection.GetFiles("*_offline.xml")) { XDocument doc3 = XDocument.Load(fi.FullName); foreach (var n in doc3.Descendants(z + "row")) { string oldFileRef = n.Attribute("ows_FileRef").Value; n.Attribute("ows_FileRef").Value = oldFileRef.Replace("sites/blg27", web.ServerRelativeUrl.Substring(1)); } doc3.Save(fi.FullName); } #endregion #region repack Global.Debug = "repack"; string directive = "directives_inspection_" + webid + ".txt"; string cabinet = "template_inspection_" + webid + ".xsn"; FileInfo fiDirectives = new FileInfo(diFeature.FullName + '\\' + directive); if (fiDirectives.Exists) fiDirectives.Delete(); using (StreamWriter sw = fiDirectives.CreateText()) { sw.WriteLine(".OPTION EXPLICIT"); sw.WriteLine(".set CabinetNameTemplate=" + cabinet); sw.WriteLine(".set DiskDirectoryTemplate=\"" + diFeature.FullName + "\""); sw.WriteLine(".set Cabinet=on"); sw.WriteLine(".set Compress=on"); foreach (FileInfo file in diWorkDirInspection.GetFiles()) { sw.WriteLine('"' + file.FullName + '"'); } } Process p2 = new Process(); p2.StartInfo.RedirectStandardOutput = true; p2.StartInfo.UseShellExecute = false; //p2.StartInfo.FileName = diTillsyn.FullName + @"\makecab.exe"; p2.StartInfo.FileName = @"c:\windows\system32\makecab.exe"; p2.StartInfo.WorkingDirectory = diFeature.FullName; p2.StartInfo.Arguments = "/f " + fiDirectives.Name; bool start2 = p2.Start(); p2.WaitForExit(); if (p.ExitCode != 0) { Global.WriteLog(string.Format("makecab Error:\r\n{0}", p2.StandardOutput.ReadToEnd()), EventLogEntryType.Error, 1000); } #endregion #region upload Global.Debug = "upload"; FileInfo fiTemplate = new FileInfo(diFeature.FullName + '\\' + cabinet); if (fiTemplate.Exists) { // delete it if it already exists SPFile f = web.GetFile("Lists/Aktiviteter/" + _tillsynName + "/template.xsn"); if (f.Exists) f.Delete(); using (FileStream fs = fiTemplate.OpenRead()) { byte[] data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length); SPFile file = listAktiviteter.RootFolder.Files.Add("Lists/Aktiviteter/" + _tillsynName + "/template.xsn", data); Global.Debug = "set file properties"; //file.Properties["vti_contenttag"] = "{6908F1AD-3962-4293-98BB-0AA4FB54B9C9},3,1"; file.Properties["ipfs_streamhash"] = "0NJ+LASyxjJGhaIwPftKfwraa3YBBfJoNUPNA+oNYu4="; file.Properties["ipfs_listform"] = "true"; file.Update(); } Global.Debug = "set folder properties"; SPFolder folder = listAktiviteter.RootFolder.SubFolders["Tillsyn"]; folder.Properties["_ipfs_solutionName"] = "template.xsn"; folder.Properties["_ipfs_infopathenabled"] = "True"; folder.Update(); } else { Global.WriteLog("template.xsn missing", EventLogEntryType.Error, 1000); } #endregion } #endregion #region modify template permit { Global.Debug = "delete"; foreach (FileInfo fi in diWorkDirPermit.GetFiles()) { fi.Delete(); } #region extract Global.Debug = "extract"; Process p = new Process(); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.StartInfo.FileName = @"C:\Program Files\7-Zip\7z.exe"; string filename = diFeature.FullName + @"\givepermit.xsn"; p.StartInfo.Arguments = "e \"" + filename + "\" -y -o\"" + diWorkDirPermit.FullName + "\""; bool start = p.Start(); p.WaitForExit(); if (p.ExitCode != 0) { Global.WriteLog(string.Format("7z Error:\r\n{0}\r\n\r\nFilename:\r\n{1}", p.StandardOutput.ReadToEnd(), filename), EventLogEntryType.Error, 1000); } #endregion Global.Debug = "get content type permit"; SPContentType ctPermit = listAktiviteter.ContentTypes[_permitName]; #region modify manifest Global.Debug = "modify manifest permit"; XDocument doc = XDocument.Load(diWorkDirPermit.FullName + @"\manifest.xsf"); var xDocumentClass = doc.Element(xsf + "xDocumentClass"); var q1 = from extension in xDocumentClass.Element(xsf + "extensions").Elements(xsf + "extension") where extension.Attribute("name").Value == "SolutionDefinitionExtensions" select extension; var node1 = q1.First().Element(xsf3 + "solutionDefinition").Element(xsf3 + "baseUrl"); node1.Attribute("relativeUrlBase").Value = web.Url + "/Lists/Aktiviteter/" + _permitName + "/"; var q2 = from dataObject in xDocumentClass.Element(xsf + "dataObjects").Elements(xsf + "dataObject") where dataObject.Attribute("name").Value == "Kundkort" select dataObject; var node2 = q2.First().Element(xsf + "query").Element(xsf + "sharepointListAdapterRW"); node2.Attribute("sharePointListID").Value = "{" + listKundkort.ID.ToString() + "}"; var node3 = xDocumentClass.Element(xsf + "query").Element(xsf + "sharepointListAdapterRW"); node3.Attribute("sharePointListID").Value = "{" + listAktiviteter.ID.ToString() + "}"; node3.Attribute("contentTypeID").Value = ctPermit.Id.ToString(); doc.Save(diWorkDirPermit.FullName + @"\manifest.xsf"); //Global.Debug = "modify view1"; //XDocument doc2 = XDocument.Load(diWorkDir.FullName + @"\view1.xsl"); //foreach (var d in doc2.Descendants("object")) { // d.Attribute(xd + "server").Value = web.Url + "/"; //} //doc2.Save(diWorkDir.FullName + @"\view1.xsl"); #endregion #region repack Global.Debug = "repack"; string directive = "directives_permit_" + webid + ".txt"; string cabinet = "template_permit_" + webid + ".xsn"; FileInfo fiDirectives = new FileInfo(diFeature.FullName + '\\' + directive); if (fiDirectives.Exists) fiDirectives.Delete(); using (StreamWriter sw = fiDirectives.CreateText()) { sw.WriteLine(".OPTION EXPLICIT"); sw.WriteLine(".set CabinetNameTemplate=" + cabinet); sw.WriteLine(".set DiskDirectoryTemplate=\"" + diFeature.FullName + "\""); sw.WriteLine(".set Cabinet=on"); sw.WriteLine(".set Compress=on"); foreach (FileInfo file in diWorkDirPermit.GetFiles()) { sw.WriteLine('"' + file.FullName + '"'); } } Process p2 = new Process(); p2.StartInfo.RedirectStandardOutput = true; p2.StartInfo.UseShellExecute = false; //p2.StartInfo.FileName = diTillsyn.FullName + @"\makecab.exe"; p2.StartInfo.FileName = @"c:\windows\system32\makecab.exe"; p2.StartInfo.WorkingDirectory = diFeature.FullName; p2.StartInfo.Arguments = "/f " + fiDirectives.Name; bool start2 = p2.Start(); p2.WaitForExit(); if (p.ExitCode != 0) { Global.WriteLog(string.Format("makecab Error:\r\n{0}", p2.StandardOutput.ReadToEnd()), EventLogEntryType.Error, 1000); } #endregion #region upload Global.Debug = "upload"; FileInfo fiTemplate = new FileInfo(diFeature.FullName + '\\' + cabinet); if (fiTemplate.Exists) { // delete it if it already exists SPFile f = web.GetFile("Lists/Aktiviteter/" + _permitName + "/template.xsn"); if (f.Exists) f.Delete(); using (FileStream fs = fiTemplate.OpenRead()) { byte[] data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length); SPFile file = listAktiviteter.RootFolder.Files.Add("Lists/Aktiviteter/" + _permitName + "/template.xsn", data); Global.Debug = "set file properties"; //file.Properties["vti_contenttag"] = "{6908F1AD-3962-4293-98BB-0AA4FB54B9C9},3,1"; file.Properties["ipfs_streamhash"] = "0NJ+LASyxjJGhaIwPftKfwraa3YBBfJoNUPNA+oNYu4="; file.Properties["ipfs_listform"] = "true"; file.Update(); } Global.Debug = "set folder properties"; SPFolder folder = listAktiviteter.RootFolder.SubFolders["Ge försäljningstillstånd"]; folder.Properties["_ipfs_solutionName"] = "template.xsn"; folder.Properties["_ipfs_infopathenabled"] = "True"; folder.Update(); } else { Global.WriteLog("template.xsn missing", EventLogEntryType.Error, 1000); } #endregion } #endregion #region set default forms Global.Debug = "set default forms"; foreach (SPContentType ct in listAktiviteter.ContentTypes) { switch (ct.Name) { case "Tillsyn": case "Ge försäljningstillstånd": ct.DisplayFormUrl = "~list/" + ct.Name + "/displayifs.aspx"; ct.EditFormUrl = "~list/" + ct.Name + "/editifs.aspx"; ct.NewFormUrl = "~list/" + ct.Name + "/newifs.aspx"; ct.Update(); break; default: ct.DisplayFormUrl = ct.EditFormUrl = ct.NewFormUrl = string.Empty; ct.Update(); break; } } // create our own array since it will be modified (which would throw an exception) var forms = new SPForm[listAktiviteter.Forms.Count]; int j = 0; foreach (SPForm form in listAktiviteter.Forms) { forms[j] = form; j++; } foreach (var form in forms) { SPFile page = web.GetFile(form.Url); SPLimitedWebPartManager limitedWebPartManager = page.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); foreach (System.Web.UI.WebControls.WebParts.WebPart wp in limitedWebPartManager.WebParts) { if (wp is BrowserFormWebPart) { BrowserFormWebPart bfwp = (BrowserFormWebPart)wp.WebBrowsableObject; string[] aLocation = form.Url.Split('/'); string contenttype = aLocation[aLocation.Length - 2]; bfwp.FormLocation = "~list/" + contenttype + "/template.xsn"; limitedWebPartManager.SaveChanges(bfwp); StringBuilder sb = new StringBuilder(); sb.AppendLine(); sb.Append("BrowserFormWebPart FormLocation: "); sb.AppendLine(bfwp.FormLocation); sb.Append("BrowserFormWebPart Title: "); sb.AppendLine(bfwp.Title); sb.Append("BrowserFormWebPart ID: "); sb.AppendLine(bfwp.ID); sb.Append("Form URL: "); sb.AppendLine(form.Url); sb.Append("Form TemplateName: "); sb.AppendLine(form.TemplateName); sb.Append("Form ID: "); sb.AppendLine(form.ID.ToString()); sb.Append("Form ServerRelativeUrl: "); sb.AppendLine(form.ServerRelativeUrl); sb.AppendLine("BrowserFormWebPart Schema: "); sb.AppendLine(); sb.AppendLine(form.SchemaXml); //Global.WriteLog(sb.ToString(), EventLogEntryType.Information, 1000); } } // foreach webpart } // foreach form #endregion #region cleanup Global.Debug = "cleanup"; //diWorkDirInspection.Delete(true); diWorkDirPermit.Delete(true); foreach (FileInfo fi in diFeature.GetFiles("template*.xsn")) fi.Delete(); foreach (FileInfo fi in diFeature.GetFiles("directives*.xsn")) fi.Delete(); #endregion #region stäng av required på rubrik Global.Debug = "stäng av required på rubrik - kundkort"; SPField title = listKundkort.Fields[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")]; if (title != null) { title.Required = false; title.ShowInNewForm = false; title.ShowInEditForm = false; title.Update(); } title = listAktiviteter.Fields[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")]; Global.WriteLog("listAktiviteter Title - Required: " + title.Required.ToString() + ", ShowInNew: " + title.ShowInNewForm.ToString() + ", ShowInEdit: " + title.ShowInEditForm.ToString(), EventLogEntryType.Information, 1000); title.Required = false; title.ShowInNewForm = false; title.ShowInEditForm = false; title.Update(); Global.Debug = "stäng av required på rubrik - aktiviteter"; foreach (SPContentType ct in listAktiviteter.ContentTypes) { SPFieldLink flTitle = ct.FieldLinks[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")]; if (flTitle != null) { flTitle.Required = false; flTitle.Hidden = true; ct.Update(); } } #endregion Global.WriteLog("Feature Activated", EventLogEntryType.Information, 1001); } catch (Exception ex) { Global.WriteLog("Message:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace, EventLogEntryType.Error, 2001); } } // feature activated
// Uncomment the method below to handle the event raised after a feature has been activated. public override void FeatureActivated(SPFeatureReceiverProperties properties) { try { Global.Debug = "start"; SPWeb web = properties.Feature.Parent as SPWeb; if (web == null) { } SPList listKundkort = web.Lists.TryGetList("Kundkort"); Global.Debug = "Kundkort"; SPList listAktiviteter = web.Lists.TryGetList("Aktiviteter"); Global.Debug = "Aktiviteter"; if (!web.Properties.ContainsKey("activatedOnce")) { web.Properties.Add("activatedOnce", "true"); web.Properties.Update(); Global.Debug = "set activatedOnce flag"; #region sätt default-kommun-värden if (municipals.Count > 0) { Global.WriteLog("Kommuner existerar redan", EventLogEntryType.Information, 1000); } else { municipals.Add("uppsala", new Municipal { AreaCode = "018", Name = "Uppsala", RegionLetter = "C" }); municipals.Add("borlänge", new Municipal { AreaCode = "0243", Name = "Borlänge", RegionLetter = "W" }); } Global.Debug = "added municipals"; #endregion #region hämta listor SPList listAgare = web.Lists.TryGetList("Ägare"); Global.Debug = "Ägare"; SPList listKontakter = web.Lists.TryGetList("Kontakter"); Global.Debug = "Kontakter"; SPList listAdresser = web.Lists.TryGetList("Adresser"); Global.Debug = "Adresser"; SPList listSidor = web.Lists.TryGetList("Webbplatssidor"); Global.Debug = "Webbplatssidor"; SPList listNyheter = web.Lists.TryGetList("Senaste nytt"); Global.Debug = "Senaste nytt"; //SPList listBlanketter = web.Lists.TryGetList("Blanketter"); SPList listGenvagar = web.Lists.TryGetList("Genvägar"); Global.Debug = "Genvägar"; SPList listGruppkopplingar = web.Lists.TryGetList("Gruppkopplingar"); Global.Debug = "Gruppkopplingar"; SPList[] lists = new SPList[] { listAgare, listKontakter, listAdresser, listSidor, listNyheter, listGenvagar, listGruppkopplingar }; int i = 0; foreach (SPList list in lists) { i++; if (list == null) { Global.WriteLog("Lista " + i.ToString() + " är null", EventLogEntryType.Error, 2000); } } #endregion if (listSidor != null) { #region startsida string compoundUrl = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Start.aspx"); //* Define page payout _wikiFullContent = FormatBasicWikiLayout(); Global.Debug = "Skapa startsida"; SPFile startsida = listSidor.RootFolder.Files.Add(compoundUrl, SPTemplateFileType.WikiPage); // Header string relativeUrl = web.ServerRelativeUrl == "/" ? "" : web.ServerRelativeUrl; _wikiFullContent = _wikiFullContent.Replace("[[HEADER]]", "<img alt=\"vinter\" src=\"" + relativeUrl + "/SiteAssets/profil_ettan_vinter_557x100.jpg\" style=\"margin: 5px;\"/><img alt=\"hjärta\" src=\"" + relativeUrl + "/SiteAssets/heart.gif\" style=\"margin: 5px;\"/>"); #region Nyheter ListViewWebPart wpAnnouncements = new ListViewWebPart(); wpAnnouncements.ListName = listNyheter.ID.ToString("B").ToUpper(); //wpAnnouncements.ViewGuid = listNyheter.GetUncustomizedViewByBaseViewId(0).ID.ToString("B").ToUpper(); //wpAnnouncements.ViewGuid = listNyheter.DefaultView.ID.ToString("B").ToUpper(); wpAnnouncements.ViewGuid = string.Empty; Guid wpAnnouncementsGuid = AddWebPartControlToPage(startsida, wpAnnouncements); AddWebPartMarkUpToPage(wpAnnouncementsGuid, "[[COL1]]"); #endregion #region Genvägar ListViewWebPart wpLinks = new ListViewWebPart(); wpLinks.ListName = listGenvagar.ID.ToString("B").ToUpper(); //wpLinks.ViewGuid = listGenvagar.GetUncustomizedViewByBaseViewId(0).ID.ToString("B").ToUpper(); //wpLinks.ViewGuid = listGenvagar.DefaultView.ID.ToString("B").ToUpper(); wpLinks.ViewGuid = string.Empty; Guid wpLinksGuid = AddWebPartControlToPage(startsida, wpLinks); AddWebPartMarkUpToPage(wpLinksGuid, "[[COL2]]"); #endregion startsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent; startsida.Item.UpdateOverwriteVersion(); Global.Debug = "Startsida skapad"; #endregion #region lägg till försäljningsställe string compoundUrl2 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Lägg till försäljningsställe.aspx"); //* Define page payout _wikiFullContent = FormatSimpleWikiLayout(); Global.Debug = "Skapa nybutiksida"; SPFile nybutiksida = listSidor.RootFolder.Files.Add(compoundUrl2, SPTemplateFileType.WikiPage); // Header _wikiFullContent = _wikiFullContent.Replace("[[COL1]]", @"<h1>Sida för att lägga till nya försäljningsställen</h1> <h2>STEG 1 - Lägg till ägare</h2> [[WP1]] <h2>STEG 2 - Lägg till adressuppgifter</h2> [[WP2]] <h2>STEG 3 - Lägg till kontaktperson</h2> [[WP3]] <h2>STEG 4 - Lägg till försäljningsstället</h2> [[WP4]]"); Global.Debug = "wpAgare"; XsltListViewWebPart wpAgare = new XsltListViewWebPart(); wpAgare.ChromeType = PartChromeType.None; wpAgare.ListName = listAgare.ID.ToString("B").ToUpper(); wpAgare.ViewGuid = listAgare.Views["Tilläggsvy"].ID.ToString("B").ToUpper(); wpAgare.Toolbar = "Standard"; Guid wpAgareGuid = AddWebPartControlToPage(nybutiksida, wpAgare); AddWebPartMarkUpToPage(wpAgareGuid, "[[WP1]]"); Global.Debug = "wpAdresser"; XsltListViewWebPart wpAdresser = new XsltListViewWebPart(); wpAdresser.ChromeType = PartChromeType.None; wpAdresser.ListName = listAdresser.ID.ToString("B").ToUpper(); wpAdresser.ViewGuid = listAdresser.Views["Tilläggsvy"].ID.ToString("B").ToUpper(); wpAdresser.Toolbar = "Standard"; Guid wpAdresserGuid = AddWebPartControlToPage(nybutiksida, wpAdresser); AddWebPartMarkUpToPage(wpAdresserGuid, "[[WP2]]"); Global.Debug = "wpKontakter"; XsltListViewWebPart wpKontakter = new XsltListViewWebPart(); wpKontakter.ChromeType = PartChromeType.None; wpKontakter.ListName = listKontakter.ID.ToString("B").ToUpper(); wpKontakter.ViewGuid = listKontakter.Views["Tilläggsvy"].ID.ToString("B").ToUpper(); wpKontakter.Toolbar = "Standard"; Guid wpKontakterGuid = AddWebPartControlToPage(nybutiksida, wpKontakter); AddWebPartMarkUpToPage(wpKontakterGuid, "[[WP3]]"); Global.Debug = "wpKundkort"; XsltListViewWebPart wpKundkort = new XsltListViewWebPart(); wpKundkort.ChromeType = PartChromeType.None; wpKundkort.ListName = listKundkort.ID.ToString("B").ToUpper(); wpKundkort.ViewGuid = listKundkort.Views["Tilläggsvy"].ID.ToString("B").ToUpper(); wpKundkort.Toolbar = "Standard"; Guid wpKundkortGuid = AddWebPartControlToPage(nybutiksida, wpKundkort); AddWebPartMarkUpToPage(wpKundkortGuid, "[[WP4]]"); nybutiksida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent; nybutiksida.Item.UpdateOverwriteVersion(); Global.Debug = "Nybutiksida skapad"; #endregion #region mitt försäljningsställe string compoundUrl3 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Mitt försäljningsställe.aspx");//* Define page payout _wikiFullContent = FormatSimpleWikiLayout(); Global.Debug = "Skapa minbutiksida"; SPFile minbutiksida = listSidor.RootFolder.Files.Add(compoundUrl3, SPTemplateFileType.WikiPage); Global.Debug = "wpMinButik"; MinButikWP wpMinButik = new MinButikWP(); wpMinButik.ChromeType = PartChromeType.None; wpMinButik.Adresser = "Adresser"; wpMinButik.Agare = "Ägare"; wpMinButik.Kontakter = "Kontakter"; wpMinButik.Kundkort = "Kundkort"; Guid wpMinButikGuid = AddWebPartControlToPage(minbutiksida, wpMinButik); AddWebPartMarkUpToPage(wpMinButikGuid, "[[COL1]]"); minbutiksida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent; minbutiksida.Item.UpdateOverwriteVersion(); Global.Debug = "Nybutiksida skapad"; #endregion #region skapa tillsynsrapport //string compoundUrl4 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Skapa tillsynsrapport.aspx");//* Define page payout //_wikiFullContent = FormatSimpleWikiLayout(); //Global.Debug = "Skapa tillsynsrapport"; //SPFile skapatillsynsida = listSidor.RootFolder.Files.Add(compoundUrl4, SPTemplateFileType.WikiPage); //Global.Debug = "wpTillsyn"; //TillsynWP wpTillsyn = new TillsynWP(); //wpTillsyn.ChromeType = PartChromeType.None; //Guid wpTillsynGuid = AddWebPartControlToPage(skapatillsynsida, wpTillsyn); //AddWebPartMarkUpToPage(wpTillsynGuid, "[[COL1]]"); //skapatillsynsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent; //skapatillsynsida.Item.UpdateOverwriteVersion(); //Global.Debug = "Skapatillsynsida skapad"; #endregion #region inställningar string compoundUrl5 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Inställningar.aspx");//* Define page payout _wikiFullContent = FormatSimpleWikiLayout(); Global.Debug = "Inställningar"; SPFile installningarsida = listSidor.RootFolder.Files.Add(compoundUrl5, SPTemplateFileType.WikiPage); Global.Debug = "wpSettings"; SettingsWP wpSettings = new SettingsWP(); wpSettings.ChromeType = PartChromeType.None; Guid wpSettingsGuid = AddWebPartControlToPage(installningarsida, wpSettings); AddWebPartMarkUpToPage(wpSettingsGuid, "[[COL1]]"); installningarsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent; installningarsida.Item.UpdateOverwriteVersion(); Global.Debug = "Installningarsida skapad"; #endregion } #region debugdata Global.Debug = "ägare"; SPListItem item = listAgare.AddItem(); item["Title"] = "TESTÄGARE AB"; item.Update(); try { Global.Debug = "kontakt"; item = listKontakter.AddItem(); item["Title"] = "Testsson"; item["FirstName"] = "Test"; item["Email"] = "*****@*****.**"; item.Update(); item = listKontakter.AddItem(); item["Title"] = "Jansson"; item["FirstName"] = "Peter"; item["Email"] = "*****@*****.**"; item.Update(); } catch (Exception ex) { Global.WriteLog("Message:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace, EventLogEntryType.Error, 2001); } Global.Debug = "adress"; item = listAdresser.AddItem(); item["Title"] = "Testgatan 13b"; item.Update(); #endregion #region nyhet Global.Debug = "nyhet"; item = listNyheter.AddItem(); item["Title"] = "Vår online plattform för tillsyn av tobak och folköl håller på att starta upp här"; item["Body"] = @"Hej! Nu har första stegen till en online plattform för tillsyn av tobak och folköl tagits. Här kan du som försäljningsställe ladda hem blanketter och ta del av utbildningsmaterial. " + web.Title + " kommun"; item.Update(); #endregion #region länkar Global.Debug = "länkar"; item = listGenvagar.AddItem(); Global.Debug = "Blanketter"; item["Title"] = "Blanketter"; item["URL"] = web.ServerRelativeUrl + "/Blanketter, Blanketter"; item.Update(); item = listGenvagar.AddItem(); Global.Debug = "Utbildningsmaterial"; item["Title"] = "Utbildningsmaterial"; item["URL"] = web.ServerRelativeUrl + "/Utbildningsmaterial, Utbildningsmaterial"; item.Update(); #endregion #region sätt kundnummeregenskaper Global.Debug = "löpnummer"; web.Properties.Add("lopnummer", "1000"); Global.Debug = "prefixformel"; web.Properties.Add("prefixFormula", "%B%R-%N"); Global.Debug = "listAdresserGUID"; web.Properties.Add("listAdresserGUID", listAdresser.ID.ToString()); Global.Debug = "listAgareGUID"; web.Properties.Add("listAgareGUID", listAgare.ID.ToString()); Global.Debug = "gruppkopplingar"; web.Properties.Add("listGruppkopplingarGUID", listGruppkopplingar.ID.ToString()); try { Municipal m = municipals[web.Title.ToLower()]; web.Properties.Add("municipalAreaCode", m.AreaCode); web.Properties.Add("municipalRegionLetter", m.RegionLetter); } catch { } Global.Debug = "properties"; web.Properties.Update(); #endregion } else { Global.WriteLog("Redan aktiverad", EventLogEntryType.Information, 1000); } #region modify template global Global.Debug = "ensure empty working directory"; DirectoryInfo diFeature = new DirectoryInfo(@"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\UPCOR.TillsynKommun"); string webid = web.Url.Replace("http://", "").Replace('/', '_'); string dirname = @"workdir_" + webid; Global.Debug = "dir: " + dirname; DirectoryInfo diWorkDir = diFeature.CreateSubdirectory(dirname); if (!diWorkDir.Exists) { diWorkDir.Create(); } XNamespace xsf = "http://schemas.microsoft.com/office/infopath/2003/solutionDefinition"; XNamespace xsf3 = "http://schemas.microsoft.com/office/infopath/2009/solutionDefinition/extensions"; XNamespace xd = "http://schemas.microsoft.com/office/infopath/2003"; #endregion #region modify template tillsyn { Global.Debug = "deleting files"; foreach (FileInfo fi in diWorkDir.GetFiles()) { fi.Delete(); } Global.Debug = "extract"; Process p = new Process(); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.StartInfo.FileName = @"C:\Program Files\7-Zip\7z.exe"; //string filename = diTillsyn.FullName + @"\75841904-0c67-4118-826f-b1319db35c6a.xsn"; string filename = diFeature.FullName + @"\4BEB6318-1CE0-47BE-92C2-E9815D312C1A.xsn"; p.StartInfo.Arguments = "e \"" + filename + "\" -y -o\"" + diWorkDir.FullName + "\""; bool start = p.Start(); p.WaitForExit(); if (p.ExitCode != 0) { Global.WriteLog(string.Format("7z Error:\r\n{0}\r\n\r\nFilename:\r\n{1}", p.StandardOutput.ReadToEnd(), filename), EventLogEntryType.Error, 1000); } Global.Debug = "get content type"; SPContentType ctTillsyn = listAktiviteter.ContentTypes[_tillsynName]; Global.Debug = "modify manifest"; XDocument doc = XDocument.Load(diWorkDir.FullName + @"\manifest.xsf"); var xDocumentClass = doc.Element(xsf + "xDocumentClass"); var q1 = from extension in xDocumentClass.Element(xsf + "extensions").Elements(xsf + "extension") where extension.Attribute("name").Value == "SolutionDefinitionExtensions" select extension; var node1 = q1.First().Element(xsf3 + "solutionDefinition").Element(xsf3 + "baseUrl"); node1.Attribute("relativeUrlBase").Value = web.Url + "/Lists/Aktiviteter/Tillsyn/"; var q2 = from dataObject in xDocumentClass.Element(xsf + "dataObjects").Elements(xsf + "dataObject") where dataObject.Attribute("name").Value == "Kundkort" select dataObject; var node2 = q2.First().Element(xsf + "query").Element(xsf + "sharepointListAdapterRW"); node2.Attribute("sharePointListID").Value = "{" + listKundkort.ID.ToString() + "}"; var node3 = xDocumentClass.Element(xsf + "query").Element(xsf + "sharepointListAdapterRW"); node3.Attribute("sharePointListID").Value = "{" + listAktiviteter.ID.ToString() + "}"; node3.Attribute("contentTypeID").Value = ctTillsyn.Id.ToString(); doc.Save(diWorkDir.FullName + @"\manifest.xsf"); Global.Debug = "modify view1"; XDocument doc2 = XDocument.Load(diWorkDir.FullName + @"\view1.xsl"); foreach (var d in doc2.Descendants("object")) { d.Attribute(xd + "server").Value = web.Url + "/"; } doc2.Save(diWorkDir.FullName + @"\view1.xsl"); Global.Debug = "repack"; string directive = "directives_inspection_" + webid + ".txt"; string cabinet = "template_inspection_" + webid + ".xsn"; FileInfo fiDirectives = new FileInfo(diFeature.FullName + '\\' + directive); if (fiDirectives.Exists) { fiDirectives.Delete(); } using (StreamWriter sw = fiDirectives.CreateText()) { sw.WriteLine(".OPTION EXPLICIT"); sw.WriteLine(".set CabinetNameTemplate=" + cabinet); sw.WriteLine(".set DiskDirectoryTemplate=\"" + diFeature.FullName + "\""); sw.WriteLine(".set Cabinet=on"); sw.WriteLine(".set Compress=on"); foreach (FileInfo file in diWorkDir.GetFiles()) { sw.WriteLine('"' + file.FullName + '"'); } } Process p2 = new Process(); p2.StartInfo.RedirectStandardOutput = true; p2.StartInfo.UseShellExecute = false; //p2.StartInfo.FileName = diTillsyn.FullName + @"\makecab.exe"; p2.StartInfo.FileName = @"c:\windows\system32\makecab.exe"; p2.StartInfo.WorkingDirectory = diFeature.FullName; p2.StartInfo.Arguments = "/f " + fiDirectives.Name; bool start2 = p2.Start(); p2.WaitForExit(); if (p.ExitCode != 0) { Global.WriteLog(string.Format("makecab Error:\r\n{0}", p2.StandardOutput.ReadToEnd()), EventLogEntryType.Error, 1000); } Global.Debug = "upload"; FileInfo fiTemplate = new FileInfo(diFeature.FullName + '\\' + cabinet); if (fiTemplate.Exists) { using (FileStream fs = fiTemplate.OpenRead()) { byte[] data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length); SPFile file = listAktiviteter.RootFolder.Files.Add("Lists/Aktiviteter/Tillsyn/template.xsn", data); Global.Debug = "set file properties"; //file.Properties["vti_contenttag"] = "{6908F1AD-3962-4293-98BB-0AA4FB54B9C9},3,1"; file.Properties["ipfs_streamhash"] = "0NJ+LASyxjJGhaIwPftKfwraa3YBBfJoNUPNA+oNYu4="; file.Properties["ipfs_listform"] = "true"; file.Update(); } Global.Debug = "set folder properties"; SPFolder folder = listAktiviteter.RootFolder.SubFolders["Tillsyn"]; folder.Properties["_ipfs_solutionName"] = "template.xsn"; folder.Properties["_ipfs_infopathenabled"] = "True"; folder.Update(); } else { Global.WriteLog("template.xsn missing", EventLogEntryType.Error, 1000); } //Global.Debug = "set default forms"; //// create our own array since it will be modified (which would throw an exception) //var forms = new SPForm[listAktiviteter.Forms.Count]; //int j = 0; //foreach (SPForm form in listAktiviteter.Forms) { // forms[j] = form; // j++; //} //foreach (var form in forms) { // SPFile page = web.GetFile(form.Url); // SPLimitedWebPartManager limitedWebPartManager = page.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); // foreach (System.Web.UI.WebControls.WebParts.WebPart wp in limitedWebPartManager.WebParts) { // if (wp is BrowserFormWebPart) { // BrowserFormWebPart bfwp = (BrowserFormWebPart)wp.WebBrowsableObject; // bfwp.FormLocation = bfwp.FormLocation.Replace("/Item/", "/Tillsyn/"); // limitedWebPartManager.SaveChanges(bfwp); // switch (form.Type) { // case PAGETYPE.PAGE_NEWFORM: // listAktiviteter.DefaultNewFormUrl = form.ServerRelativeUrl; // break; // case PAGETYPE.PAGE_EDITFORM: // listAktiviteter.DefaultEditFormUrl = form.ServerRelativeUrl; // break; // case PAGETYPE.PAGE_DISPLAYFORM: // listAktiviteter.DefaultDisplayFormUrl = form.ServerRelativeUrl; // break; // } // } // } //} } #endregion #region modify template permit { Global.Debug = "delete"; foreach (FileInfo fi in diWorkDir.GetFiles()) { fi.Delete(); } Global.Debug = "extract"; Process p = new Process(); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.StartInfo.FileName = @"C:\Program Files\7-Zip\7z.exe"; string filename = diFeature.FullName + @"\givepermit.xsn"; p.StartInfo.Arguments = "e \"" + filename + "\" -y -o\"" + diWorkDir.FullName + "\""; bool start = p.Start(); p.WaitForExit(); if (p.ExitCode != 0) { Global.WriteLog(string.Format("7z Error:\r\n{0}\r\n\r\nFilename:\r\n{1}", p.StandardOutput.ReadToEnd(), filename), EventLogEntryType.Error, 1000); } Global.Debug = "get content type"; SPContentType ctPermit = listAktiviteter.ContentTypes[_permitName]; Global.Debug = "modify manifest"; XDocument doc = XDocument.Load(diWorkDir.FullName + @"\manifest.xsf"); var xDocumentClass = doc.Element(xsf + "xDocumentClass"); var q1 = from extension in xDocumentClass.Element(xsf + "extensions").Elements(xsf + "extension") where extension.Attribute("name").Value == "SolutionDefinitionExtensions" select extension; var node1 = q1.First().Element(xsf3 + "solutionDefinition").Element(xsf3 + "baseUrl"); node1.Attribute("relativeUrlBase").Value = web.Url + "/Lists/Aktiviteter/Ge%20försäljningstillstånd/"; var q2 = from dataObject in xDocumentClass.Element(xsf + "dataObjects").Elements(xsf + "dataObject") where dataObject.Attribute("name").Value == "Kundkort" select dataObject; var node2 = q2.First().Element(xsf + "query").Element(xsf + "sharepointListAdapterRW"); node2.Attribute("sharePointListID").Value = "{" + listKundkort.ID.ToString() + "}"; var node3 = xDocumentClass.Element(xsf + "query").Element(xsf + "sharepointListAdapterRW"); node3.Attribute("sharePointListID").Value = "{" + listAktiviteter.ID.ToString() + "}"; node3.Attribute("contentTypeID").Value = ctPermit.Id.ToString(); doc.Save(diWorkDir.FullName + @"\manifest.xsf"); //Global.Debug = "modify view1"; //XDocument doc2 = XDocument.Load(diWorkDir.FullName + @"\view1.xsl"); //foreach (var d in doc2.Descendants("object")) { // d.Attribute(xd + "server").Value = web.Url + "/"; //} //doc2.Save(diWorkDir.FullName + @"\view1.xsl"); Global.Debug = "repack"; string directive = "directives_permit_" + webid + ".txt"; string cabinet = "template_permit_" + webid + ".xsn"; FileInfo fiDirectives = new FileInfo(diFeature.FullName + '\\' + directive); if (fiDirectives.Exists) { fiDirectives.Delete(); } using (StreamWriter sw = fiDirectives.CreateText()) { sw.WriteLine(".OPTION EXPLICIT"); sw.WriteLine(".set CabinetNameTemplate=" + cabinet); sw.WriteLine(".set DiskDirectoryTemplate=\"" + diFeature.FullName + "\""); sw.WriteLine(".set Cabinet=on"); sw.WriteLine(".set Compress=on"); foreach (FileInfo file in diWorkDir.GetFiles()) { sw.WriteLine('"' + file.FullName + '"'); } } Process p2 = new Process(); p2.StartInfo.RedirectStandardOutput = true; p2.StartInfo.UseShellExecute = false; //p2.StartInfo.FileName = diTillsyn.FullName + @"\makecab.exe"; p2.StartInfo.FileName = @"c:\windows\system32\makecab.exe"; p2.StartInfo.WorkingDirectory = diFeature.FullName; p2.StartInfo.Arguments = "/f " + fiDirectives.Name; bool start2 = p2.Start(); p2.WaitForExit(); if (p.ExitCode != 0) { Global.WriteLog(string.Format("makecab Error:\r\n{0}", p2.StandardOutput.ReadToEnd()), EventLogEntryType.Error, 1000); } Global.Debug = "upload"; FileInfo fiTemplate = new FileInfo(diFeature.FullName + '\\' + cabinet); if (fiTemplate.Exists) { using (FileStream fs = fiTemplate.OpenRead()) { byte[] data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length); SPFile file = listAktiviteter.RootFolder.Files.Add("Lists/Aktiviteter/Ge försäljningstillstånd/template.xsn", data); Global.Debug = "set file properties"; //file.Properties["vti_contenttag"] = "{6908F1AD-3962-4293-98BB-0AA4FB54B9C9},3,1"; file.Properties["ipfs_streamhash"] = "0NJ+LASyxjJGhaIwPftKfwraa3YBBfJoNUPNA+oNYu4="; file.Properties["ipfs_listform"] = "true"; file.Update(); } Global.Debug = "set folder properties"; SPFolder folder = listAktiviteter.RootFolder.SubFolders["Ge försäljningstillstånd"]; folder.Properties["_ipfs_solutionName"] = "template.xsn"; folder.Properties["_ipfs_infopathenabled"] = "True"; folder.Update(); } else { Global.WriteLog("template.xsn missing", EventLogEntryType.Error, 1000); } } #endregion #region set default forms Global.Debug = "set default forms"; foreach (SPContentType ct in listAktiviteter.ContentTypes) { switch (ct.Name) { case "Tillsyn": case "Ge försäljningstillstånd": ct.DisplayFormUrl = "~list/" + ct.Name + "/displayifs.aspx"; ct.EditFormUrl = "~list/" + ct.Name + "/editifs.aspx"; ct.NewFormUrl = "~list/" + ct.Name + "/newifs.aspx"; ct.Update(); break; default: ct.DisplayFormUrl = ct.EditFormUrl = ct.NewFormUrl = string.Empty; ct.Update(); break; } } // create our own array since it will be modified (which would throw an exception) var forms = new SPForm[listAktiviteter.Forms.Count]; int j = 0; foreach (SPForm form in listAktiviteter.Forms) { forms[j] = form; j++; } foreach (var form in forms) { SPFile page = web.GetFile(form.Url); SPLimitedWebPartManager limitedWebPartManager = page.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); foreach (System.Web.UI.WebControls.WebParts.WebPart wp in limitedWebPartManager.WebParts) { if (wp is BrowserFormWebPart) { BrowserFormWebPart bfwp = (BrowserFormWebPart)wp.WebBrowsableObject; //bfwp.FormLocation = bfwp.FormLocation.Replace("/Item/", "/Ge försäljningstillstånd/"); //limitedWebPartManager.SaveChanges(bfwp); string[] aLocation = form.Url.Split('/'); string contenttype = aLocation[aLocation.Length - 2]; bfwp.FormLocation = "~list/" + contenttype + "/template.xsn"; limitedWebPartManager.SaveChanges(bfwp); StringBuilder sb = new StringBuilder(); sb.AppendLine(); sb.Append("BrowserFormWebPart FormLocation: "); sb.AppendLine(bfwp.FormLocation); sb.Append("BrowserFormWebPart Title: "); sb.AppendLine(bfwp.Title); sb.Append("BrowserFormWebPart ID: "); sb.AppendLine(bfwp.ID); sb.Append("Form URL: "); sb.AppendLine(form.Url); sb.Append("Form TemplateName: "); sb.AppendLine(form.TemplateName); sb.Append("Form ID: "); sb.AppendLine(form.ID.ToString()); sb.Append("Form ServerRelativeUrl: "); sb.AppendLine(form.ServerRelativeUrl); sb.AppendLine("BrowserFormWebPart Schema: "); sb.AppendLine(); sb.AppendLine(form.SchemaXml); Global.WriteLog(sb.ToString(), EventLogEntryType.Information, 1000); //switch (form.Type) { // case PAGETYPE.PAGE_NEWFORM: // listAktiviteter.DefaultNewFormUrl = form.ServerRelativeUrl; // break; // case PAGETYPE.PAGE_EDITFORM: // listAktiviteter.DefaultEditFormUrl = form.ServerRelativeUrl; // break; // case PAGETYPE.PAGE_DISPLAYFORM: // listAktiviteter.DefaultDisplayFormUrl = form.ServerRelativeUrl; // break; //} } } } #endregion #region cleanup Global.Debug = "cleanup"; diWorkDir.Delete(true); foreach (FileInfo fi in diFeature.GetFiles("template*.xsn")) { fi.Delete(); } foreach (FileInfo fi in diFeature.GetFiles("directives*.xsn")) { fi.Delete(); } #endregion #region stäng av required på rubrik SPField title = listKundkort.Fields[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")]; Global.WriteLog("listKundkort Title - Required: " + title.Required.ToString() + ", ShowInNew: " + title.ShowInNewForm.ToString() + ", ShowInEdit: " + title.ShowInEditForm.ToString(), EventLogEntryType.Information, 1000); title.Required = false; title.ShowInNewForm = false; title.ShowInEditForm = false; title.Update(); //title = listAktiviteter.Fields[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")]; //Global.WriteLog("listAktiviteter Title - Required: " + title.Required.ToString() + ", ShowInNew: " + title.ShowInNewForm.ToString() + ", ShowInEdit: " + title.ShowInEditForm.ToString(), EventLogEntryType.Information, 1000); //title.Required = false; //title.ShowInNewForm = false; //title.ShowInEditForm = false; //title.Update(); foreach (SPContentType ct in listAktiviteter.ContentTypes) { SPFieldLink flTitle = ct.FieldLinks[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")]; flTitle.Required = false; flTitle.Hidden = true; ct.Update(); } #endregion Global.WriteLog("Feature Activated", EventLogEntryType.Information, 1001); } catch (Exception ex) { Global.WriteLog("Message:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace, EventLogEntryType.Error, 2001); } } // feature activated
/// <summary> /// Adds a List View Web Part to the specified page. /// </summary> /// <param name="pageUrl">The page URL.</param> /// <param name="listUrl">The list URL.</param> /// <param name="title">The title.</param> /// <param name="viewTitle">Title of the view.</param> /// <param name="zoneId">The zone ID.</param> /// <param name="zoneIndex">Index within the zone.</param> /// <param name="linkTitle">if set to <c>true</c> [link title].</param> /// <param name="chromeType">Type of the chrome.</param> /// <param name="publish">if set to <c>true</c> [publish].</param> /// <returns></returns> public static Microsoft.SharePoint.WebPartPages.WebPart Add(string pageUrl, string listUrl, string title, string viewTitle, string zoneId, int zoneIndex, bool linkTitle, string jsLink, PartChromeType chromeType, bool publish) { using (SPSite site = new SPSite(pageUrl)) using (SPWeb web = site.OpenWeb()) // The url contains a filename so AllWebs[] will not work unless we want to try and parse which we don't { SPFile file = web.GetFile(pageUrl); // file.Item will throw "The object specified does not belong to a list." if the url passed // does not correspond to a file in a list. SPList list = Utilities.GetListFromViewUrl(listUrl); if (list == null) throw new ArgumentException("List not found."); SPView view = null; if (!string.IsNullOrEmpty(viewTitle)) { view = list.Views.Cast<SPView>().FirstOrDefault(v => v.Title == viewTitle); if (view == null) throw new ArgumentException("The specified view was not found."); } bool checkBackIn = false; if (file.InDocumentLibrary) { if (!Utilities.IsCheckedOut(file.Item) || !Utilities.IsCheckedOutByCurrentUser(file.Item)) { checkBackIn = true; file.CheckOut(); } // If it's checked out by another user then this will throw an informative exception so let it do so. } string displayTitle = string.Empty; Microsoft.SharePoint.WebPartPages.WebPart lvw = null; SPLimitedWebPartManager manager = null; try { manager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared); lvw = new XsltListViewWebPart(); if (list.BaseTemplate == SPListTemplateType.Events) lvw = new ListViewWebPart(); if (lvw is ListViewWebPart) { ((ListViewWebPart)lvw).ListName = list.ID.ToString("B").ToUpperInvariant(); ((ListViewWebPart)lvw).WebId = list.ParentWeb.ID; if (view != null) ((ListViewWebPart)lvw).ViewGuid = view.ID.ToString("B").ToUpperInvariant(); } else { ((XsltListViewWebPart)lvw).ListName = list.ID.ToString("B").ToUpperInvariant(); #if SP2013 if (!string.IsNullOrEmpty(jsLink)) ((XsltListViewWebPart)lvw).JSLink = jsLink; #endif ((XsltListViewWebPart)lvw).WebId = list.ParentWeb.ID; if (view != null) ((XsltListViewWebPart)lvw).ViewGuid = view.ID.ToString("B").ToUpperInvariant(); } if (linkTitle) { if (view != null) lvw.TitleUrl = view.Url; else lvw.TitleUrl = list.DefaultViewUrl; } if (!string.IsNullOrEmpty(title)) lvw.Title = title; lvw.ChromeType = chromeType; displayTitle = lvw.DisplayTitle; manager.AddWebPart(lvw, zoneId, zoneIndex); } finally { if (manager != null) { manager.Web.Dispose(); manager.Dispose(); } if (lvw != null) lvw.Dispose(); if (file.InDocumentLibrary && Utilities.IsCheckedOut(file.Item) && (checkBackIn || publish)) file.CheckIn("Checking in changes to page due to new web part being added: " + displayTitle); if (publish && file.InDocumentLibrary) { file.Publish("Publishing changes to page due to new web part being added: " + displayTitle); if (file.Item.ModerationInformation != null) { file.Approve("Approving changes to page due to new web part being added: " + displayTitle); } } } return lvw; } }
// Uncomment the method below to handle the event raised after a feature has been activated. public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPSite curSite; SPWeb curWeb; properties.GetSiteAndWeb(out curSite, out curWeb); if (curSite != null && curWeb != null) { try { #region Configure Doc Id Prefix string prefix = "CCCM"; if (curSite.RootWeb.Properties.ContainsKey(eCaseConstants.PropertyBagKeys.ECASE_DOC_ID_PREFIX)) { prefix = curSite.RootWeb.Properties[eCaseConstants.PropertyBagKeys.ECASE_DOC_ID_PREFIX]; } if (!curWeb.Properties.ContainsKey(eCaseConstants.PropertyBagKeys.ECASE_DOC_ID_PREFIX)) { curWeb.Properties.Add(eCaseConstants.PropertyBagKeys.ECASE_DOC_ID_PREFIX, prefix); curWeb.Properties.Update(); } #endregion #region Configure Workflows to Associate string workflowNames = eCaseConstants.PropertyBagDefaultValues.DEFAULT_WORKFLOW_NAMES; if (!curSite.RootWeb.Properties.ContainsKey(eCaseConstants.PropertyBagKeys.ECASE_WORKFLOWS_TO_ASSOCIATE)) { curSite.RootWeb.Properties.Add(eCaseConstants.PropertyBagKeys.ECASE_WORKFLOWS_TO_ASSOCIATE, workflowNames); curSite.RootWeb.Properties.Update(); } #endregion // Activate Case Site Components feature at RootWeb if not already activated try { curSite.Features.Add(eCaseConstants.FeatureIds.CASE_SITE_COMPONENTS); } catch (System.Data.DuplicateNameException x) { Logger.Instance.Info(string.Format("CaseWebComponentsEventReceiver.FeatureActivated: {0} already activated at {1}", eCaseConstants.FeatureIds.CASE_SITE_COMPONENTS.ToString(), curSite.Url), x, DiagnosticsCategories.eCaseWeb); } // Activate Standard Site Collection Features if not already activated try { curSite.Features.Add(eCaseConstants.FeatureIds.LEGACY_WORKFLOWS); } catch (System.Data.DuplicateNameException x) { Logger.Instance.Info(string.Format("CaseWebComponentsEventReceiver.FeatureActivated: {0} already activated at {1}", eCaseConstants.FeatureIds.WORKFLOWS.ToString(), curSite.Url), x, DiagnosticsCategories.eCaseWeb); } // Activate 2010 Workflows feature if not already activated try { curSite.Features.Add(eCaseConstants.FeatureIds.WORKFLOWS); } catch (System.Data.DuplicateNameException x) { Logger.Instance.Info(string.Format("CaseWebComponentsEventReceiver.FeatureActivated: {0} already activated at {1}", eCaseConstants.FeatureIds.WORKFLOWS.ToString(), curSite.Url), x, DiagnosticsCategories.eCaseWeb); } // Associate workflows from our property bag if (curSite.RootWeb.Properties.ContainsKey(eCaseConstants.PropertyBagKeys.ECASE_WORKFLOWS_TO_ASSOCIATE)) { var workFlows = curSite.RootWeb.Properties[eCaseConstants.PropertyBagKeys.ECASE_WORKFLOWS_TO_ASSOCIATE].Split('|'); //ActivateWorkflowFeatures(workFlows, curSite); AssociateWithWorkFlows(workFlows, curSite, curWeb); } #region Create RelatedLegalIssues Lookup Site Column SPFieldLookup relatedLegalIssuesLookup = null; if (curWeb.Fields.ContainsFieldWithStaticName("RelLglIssues")) { relatedLegalIssuesLookup = curWeb.Fields.GetFieldByInternalName("RelLglIssues") as SPFieldLookup; } else { SPList legalIssuesList = curWeb.GetListByInternalName(eCaseConstants.ListInternalNames.LEGAL_ISSUES); curWeb.Fields.AddLookup("RelLglIssues", legalIssuesList.ID, curWeb.ID, false); relatedLegalIssuesLookup = curWeb.Fields["RelLglIssues"] as SPFieldLookup; relatedLegalIssuesLookup.LookupField = legalIssuesList.Fields[eCaseConstants.FieldGuids.OOTB_TITLE].InternalName; relatedLegalIssuesLookup.AllowMultipleValues = true; relatedLegalIssuesLookup.Group = "eCases Site Columns"; relatedLegalIssuesLookup.Title = "Legal Issues"; relatedLegalIssuesLookup.Update(); } #endregion int autoRefreshInterval = 60; #region Referral Documents SPList caseDocsList = curWeb.GetListByInternalName(eCaseConstants.ListInternalNames.REFERRAL_DOCUMENTS); SPContentType caseDocCt = curSite.RootWeb.ContentTypes[eCaseConstants.ContentTypeIds.CASE_DOCUMENT]; SPContentType caseDocCtChild = caseDocsList.ContentTypes["Case Document"]; bool caseDocsCtIsNew = (caseDocCtChild == null); if (caseDocsCtIsNew) { caseDocCtChild = new SPContentType(caseDocCt, curWeb.ContentTypes, "Case Document"); } SPFieldLink relatedLegalIssuesFLink = new SPFieldLink(relatedLegalIssuesLookup); if (caseDocCtChild.FieldLinks[relatedLegalIssuesFLink.Name] == null) { caseDocCtChild.FieldLinks.Add(relatedLegalIssuesFLink); } if (caseDocsCtIsNew) { caseDocsList.ContentTypes.Add(caseDocCtChild); caseDocsList.Update(); } // Enable AJAX using (SPLimitedWebPartManager mgr = curWeb.GetLimitedWebPartManager(caseDocsList.DefaultViewUrl, PersonalizationScope.Shared)) { XsltListViewWebPart xsltListViewWp = mgr.WebParts[0] as XsltListViewWebPart; xsltListViewWp.AutoRefresh = true; xsltListViewWp.AutoRefreshInterval = autoRefreshInterval; mgr.SaveChanges(xsltListViewWp); } #endregion #region Investigation Documents SPList relatedDocsList = curWeb.GetListByInternalName(eCaseConstants.ListInternalNames.INVESTIGATION_DOCUMENTS); SPContentType relDocCt = curSite.RootWeb.ContentTypes[eCaseConstants.ContentTypeIds.INVESTIGATION_DOCUMENT]; SPContentType relDocCtChild = relatedDocsList.ContentTypes["Related Document"]; bool relDocCtIsNew = (relDocCtChild == null); if (relDocCtIsNew) { relDocCtChild = new SPContentType(relDocCt, curWeb.ContentTypes, "Related Document"); } if (relDocCtChild.FieldLinks[relatedLegalIssuesFLink.Name] == null) { relDocCtChild.FieldLinks.Add(relatedLegalIssuesFLink); } if (relDocCtIsNew) { relatedDocsList.ContentTypes.Add(relDocCtChild); relatedDocsList.Update(); } // Enable AJAX using (SPLimitedWebPartManager mgr = curWeb.GetLimitedWebPartManager(relatedDocsList.DefaultViewUrl, PersonalizationScope.Shared)) { XsltListViewWebPart xsltListViewWp = mgr.WebParts[0] as XsltListViewWebPart; xsltListViewWp.AutoRefresh = true; xsltListViewWp.AutoRefreshInterval = autoRefreshInterval; mgr.SaveChanges(xsltListViewWp); } #endregion #region SDO Documents SPList finWorkProdDocsList = curWeb.GetListByInternalName(eCaseConstants.ListInternalNames.SDO_DOCUMENTS); SPContentType finWorkProdCt = curSite.RootWeb.ContentTypes[eCaseConstants.ContentTypeIds.SDO_DOCUMENT]; SPContentType finWorkProdCtChild = finWorkProdDocsList.ContentTypes["Finished Work Product"]; bool finWorkProdCtIsNew = (finWorkProdCtChild == null); if (finWorkProdCtIsNew) { finWorkProdCtChild = new SPContentType(finWorkProdCt, curWeb.ContentTypes, "Finished Work Product"); } if (finWorkProdCtChild.FieldLinks[relatedLegalIssuesFLink.Name] == null) { finWorkProdCtChild.FieldLinks.Add(relatedLegalIssuesFLink); } if (finWorkProdCtIsNew) { finWorkProdDocsList.ContentTypes.Add(finWorkProdCtChild); finWorkProdDocsList.Update(); } // Enable AJAX using (SPLimitedWebPartManager mgr = curWeb.GetLimitedWebPartManager(finWorkProdDocsList.DefaultViewUrl, PersonalizationScope.Shared)) { XsltListViewWebPart xsltListViewWp = mgr.WebParts[0] as XsltListViewWebPart; xsltListViewWp.AutoRefresh = true; xsltListViewWp.AutoRefreshInterval = autoRefreshInterval; mgr.SaveChanges(xsltListViewWp); } #endregion #region Share With External User SPList shareExternalUserDocsList = curWeb.GetListByInternalName(eCaseConstants.ListInternalNames.SHARE_WITH_EXTERNAL_USERS); SPContentType shareExternalUserCt = curSite.RootWeb.ContentTypes[eCaseConstants.ContentTypeIds.SHARE_WITH_EXTERNAL_USER]; SPContentType shareExternalUserCtChild = shareExternalUserDocsList.ContentTypes["ShareWithExternalUser"]; bool shareExternalUserCtIsNew = (shareExternalUserCtChild == null); if (shareExternalUserCtIsNew) { shareExternalUserCtChild = new SPContentType(shareExternalUserCt, curWeb.ContentTypes, "ShareWithExternalUser"); } if (shareExternalUserCtChild.FieldLinks[relatedLegalIssuesFLink.Name] == null) { shareExternalUserCtChild.FieldLinks.Add(relatedLegalIssuesFLink); } if (shareExternalUserCtIsNew) { shareExternalUserDocsList.ContentTypes.Add(shareExternalUserCtChild); shareExternalUserDocsList.Update(); } // Enable AJAX using (SPLimitedWebPartManager mgr = curWeb.GetLimitedWebPartManager(shareExternalUserDocsList.DefaultViewUrl, PersonalizationScope.Shared)) { XsltListViewWebPart xsltListViewWp = mgr.WebParts[0] as XsltListViewWebPart; xsltListViewWp.AutoRefresh = true; xsltListViewWp.AutoRefreshInterval = autoRefreshInterval; mgr.SaveChanges(xsltListViewWp); } #endregion #region Related Dates -- NEVER GOT DONE PROPERLY, BUT DOES FUNCTION FOR THESE LISTS //SPContentType relDatesCt = curSite.RootWeb.ContentTypes[eCaseConstants.ContentTypeIds.RELATED_DATES]; //SPContentType relDatesCtChild = new SPContentType(relDatesCt, curWeb.ContentTypes, "Related Date"); //relDatesCtChild.FieldLinks.Add(relatedLegalIssuesFLink); //SPList caseRelatedDatesList = curWeb.GetListByInternalName(eCaseConstants.ListInternalNames.CASE_RELATED_DATES); //SPContentTypeId ootbEvent = new SPContentTypeId("0x0102"); //caseRelatedDatesList.ContentTypes.Add(relDatesCtChild); ////caseRelatedDatesList.ContentTypes.Delete(ootbEvent); //caseRelatedDatesList.Update(); //SPList matterRelatedDatesList = curWeb.GetListByInternalName(eCaseConstants.ListInternalNames.MATTER_RELATED_DATES); //matterRelatedDatesList.ContentTypes.Add(relDatesCtChild); ////matterRelatedDatesList.ContentTypes.Delete(ootbEvent); //matterRelatedDatesList.Update(); #endregion // Use Custom Logo for Site curWeb.SiteLogoUrl = curSite.RootWeb.Url + "/Style%20Library/images/ecase-logo.png"; // Push all new content types to the SPWeb collection curWeb.Update(); } catch (Exception x) { Logger.Instance.Error("CaseWebComponents FeatureActivation Failure", x, DiagnosticsCategories.eCaseWeb); throw x; } } else // Something is very wrong -- lets throw { string obj; if (curSite == null) { obj = "SPSite"; } else { obj = "SPWeb"; } string exceptionMsg = string.Format("Feature activation did not complete successfully. Unable to find {0} object", obj); throw new Exception(exceptionMsg); } }
protected override void CreateChildControls() { XsltListViewWebPart wp = new XsltListViewWebPart(); this.Controls.Add(wp); }
// Uncomment the method below to handle the event raised after a feature has been activated. public override void FeatureActivated(SPFeatureReceiverProperties properties) { try { Global.Debug = "start"; SPWeb web = properties.Feature.Parent as SPWeb; if (web == null) { } SPList listKundkort = web.Lists.TryGetList("Kundkort"); Global.Debug = "Kundkort"; SPList listAktiviteter = web.Lists.TryGetList("Aktiviteter"); Global.Debug = "Aktiviteter"; if (!web.Properties.ContainsKey("activatedOnce")) { web.Properties.Add("activatedOnce", "true"); web.Properties.Update(); Global.Debug = "set activatedOnce flag"; #region sätt default-kommun-värden if (municipals.Count > 0) { Global.WriteLog("Kommuner existerar redan", EventLogEntryType.Information, 1000); } else { municipals.Add("uppsala", new Municipal { AreaCode = "018", Name = "Uppsala", RegionLetter = "C" }); municipals.Add("borlänge", new Municipal { AreaCode = "0243", Name = "Borlänge", RegionLetter = "W" }); } Global.Debug = "added municipals"; #endregion #region hämta listor SPList listAgare = web.Lists.TryGetList("Ägare"); Global.Debug = "Ägare"; SPList listKontakter = web.Lists.TryGetList("Kontakter"); Global.Debug = "Kontakter"; SPList listAdresser = web.Lists.TryGetList("Adresser"); Global.Debug = "Adresser"; SPList listSidor = web.Lists.TryGetList("Webbplatssidor"); Global.Debug = "Webbplatssidor"; SPList listNyheter = web.Lists.TryGetList("Senaste nytt"); Global.Debug = "Senaste nytt"; //SPList listBlanketter = web.Lists.TryGetList("Blanketter"); SPList listGenvagar = web.Lists.TryGetList("Genvägar"); Global.Debug = "Genvägar"; SPList listGruppkopplingar = web.Lists.TryGetList("Gruppkopplingar"); Global.Debug = "Gruppkopplingar"; SPList[] lists = new SPList[] { listAgare, listKontakter, listAdresser, listSidor, listNyheter, listGenvagar, listGruppkopplingar }; int i = 0; foreach (SPList list in lists) { i++; if (list == null) { Global.WriteLog("Lista " + i.ToString() + " är null", EventLogEntryType.Error, 2000); } } #endregion if (listSidor != null) { #region startsida string compoundUrl = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Start.aspx"); //* Define page payout _wikiFullContent = FormatBasicWikiLayout(); Global.Debug = "Skapa startsida"; SPFile startsida = listSidor.RootFolder.Files.Add(compoundUrl, SPTemplateFileType.WikiPage); // Header string relativeUrl = web.ServerRelativeUrl == "/" ? "" : web.ServerRelativeUrl; _wikiFullContent = _wikiFullContent.Replace("[[HEADER]]", "<img alt=\"vinter\" src=\"" + relativeUrl + "/SiteAssets/profil_ettan_vinter_557x100.jpg\" style=\"margin: 5px;\"/><img alt=\"hjärta\" src=\"" + relativeUrl + "/SiteAssets/heart.gif\" style=\"margin: 5px;\"/>"); #region Nyheter ListViewWebPart wpAnnouncements = new ListViewWebPart(); wpAnnouncements.ListName = listNyheter.ID.ToString("B").ToUpper(); //wpAnnouncements.ViewGuid = listNyheter.GetUncustomizedViewByBaseViewId(0).ID.ToString("B").ToUpper(); //wpAnnouncements.ViewGuid = listNyheter.DefaultView.ID.ToString("B").ToUpper(); wpAnnouncements.ViewGuid = string.Empty; Guid wpAnnouncementsGuid = AddWebPartControlToPage(startsida, wpAnnouncements); AddWebPartMarkUpToPage(wpAnnouncementsGuid, "[[COL1]]"); #endregion #region Genvägar ListViewWebPart wpLinks = new ListViewWebPart(); wpLinks.ListName = listGenvagar.ID.ToString("B").ToUpper(); //wpLinks.ViewGuid = listGenvagar.GetUncustomizedViewByBaseViewId(0).ID.ToString("B").ToUpper(); //wpLinks.ViewGuid = listGenvagar.DefaultView.ID.ToString("B").ToUpper(); wpLinks.ViewGuid = string.Empty; Guid wpLinksGuid = AddWebPartControlToPage(startsida, wpLinks); AddWebPartMarkUpToPage(wpLinksGuid, "[[COL2]]"); #endregion startsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent; startsida.Item.UpdateOverwriteVersion(); Global.Debug = "Startsida skapad"; #endregion #region lägg till försäljningsställe string compoundUrl2 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Lägg till försäljningsställe.aspx"); //* Define page payout _wikiFullContent = FormatSimpleWikiLayout(); Global.Debug = "Skapa nybutiksida"; SPFile nybutiksida = listSidor.RootFolder.Files.Add(compoundUrl2, SPTemplateFileType.WikiPage); // Header _wikiFullContent = _wikiFullContent.Replace("[[COL1]]", @"<h1>Sida för att lägga till nya försäljningsställen</h1> <h2>STEG 1 - Lägg till ägare</h2> [[WP1]] <h2>STEG 2 - Lägg till adressuppgifter</h2> [[WP2]] <h2>STEG 3 - Lägg till kontaktperson</h2> [[WP3]] <h2>STEG 4 - Lägg till försäljningsstället</h2> [[WP4]]"); Global.Debug = "wpAgare"; XsltListViewWebPart wpAgare = new XsltListViewWebPart(); wpAgare.ChromeType = PartChromeType.None; wpAgare.ListName = listAgare.ID.ToString("B").ToUpper(); wpAgare.ViewGuid = listAgare.Views["Tilläggsvy"].ID.ToString("B").ToUpper(); wpAgare.Toolbar = "Standard"; Guid wpAgareGuid = AddWebPartControlToPage(nybutiksida, wpAgare); AddWebPartMarkUpToPage(wpAgareGuid, "[[WP1]]"); Global.Debug = "wpAdresser"; XsltListViewWebPart wpAdresser = new XsltListViewWebPart(); wpAdresser.ChromeType = PartChromeType.None; wpAdresser.ListName = listAdresser.ID.ToString("B").ToUpper(); wpAdresser.ViewGuid = listAdresser.Views["Tilläggsvy"].ID.ToString("B").ToUpper(); wpAdresser.Toolbar = "Standard"; Guid wpAdresserGuid = AddWebPartControlToPage(nybutiksida, wpAdresser); AddWebPartMarkUpToPage(wpAdresserGuid, "[[WP2]]"); Global.Debug = "wpKontakter"; XsltListViewWebPart wpKontakter = new XsltListViewWebPart(); wpKontakter.ChromeType = PartChromeType.None; wpKontakter.ListName = listKontakter.ID.ToString("B").ToUpper(); wpKontakter.ViewGuid = listKontakter.Views["Tilläggsvy"].ID.ToString("B").ToUpper(); wpKontakter.Toolbar = "Standard"; Guid wpKontakterGuid = AddWebPartControlToPage(nybutiksida, wpKontakter); AddWebPartMarkUpToPage(wpKontakterGuid, "[[WP3]]"); Global.Debug = "wpKundkort"; XsltListViewWebPart wpKundkort = new XsltListViewWebPart(); wpKundkort.ChromeType = PartChromeType.None; wpKundkort.ListName = listKundkort.ID.ToString("B").ToUpper(); wpKundkort.ViewGuid = listKundkort.Views["Tilläggsvy"].ID.ToString("B").ToUpper(); wpKundkort.Toolbar = "Standard"; Guid wpKundkortGuid = AddWebPartControlToPage(nybutiksida, wpKundkort); AddWebPartMarkUpToPage(wpKundkortGuid, "[[WP4]]"); nybutiksida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent; nybutiksida.Item.UpdateOverwriteVersion(); Global.Debug = "Nybutiksida skapad"; #endregion #region mitt försäljningsställe string compoundUrl3 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Mitt försäljningsställe.aspx");//* Define page payout _wikiFullContent = FormatSimpleWikiLayout(); Global.Debug = "Skapa minbutiksida"; SPFile minbutiksida = listSidor.RootFolder.Files.Add(compoundUrl3, SPTemplateFileType.WikiPage); Global.Debug = "wpMinButik"; MinButikWP wpMinButik = new MinButikWP(); wpMinButik.ChromeType = PartChromeType.None; wpMinButik.Adresser = "Adresser"; wpMinButik.Agare = "Ägare"; wpMinButik.Kontakter = "Kontakter"; wpMinButik.Kundkort = "Kundkort"; Guid wpMinButikGuid = AddWebPartControlToPage(minbutiksida, wpMinButik); AddWebPartMarkUpToPage(wpMinButikGuid, "[[COL1]]"); minbutiksida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent; minbutiksida.Item.UpdateOverwriteVersion(); Global.Debug = "Nybutiksida skapad"; #endregion #region skapa tillsynsrapport //string compoundUrl4 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Skapa tillsynsrapport.aspx");//* Define page payout //_wikiFullContent = FormatSimpleWikiLayout(); //Global.Debug = "Skapa tillsynsrapport"; //SPFile skapatillsynsida = listSidor.RootFolder.Files.Add(compoundUrl4, SPTemplateFileType.WikiPage); //Global.Debug = "wpTillsyn"; //TillsynWP wpTillsyn = new TillsynWP(); //wpTillsyn.ChromeType = PartChromeType.None; //Guid wpTillsynGuid = AddWebPartControlToPage(skapatillsynsida, wpTillsyn); //AddWebPartMarkUpToPage(wpTillsynGuid, "[[COL1]]"); //skapatillsynsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent; //skapatillsynsida.Item.UpdateOverwriteVersion(); //Global.Debug = "Skapatillsynsida skapad"; #endregion #region inställningar string compoundUrl5 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Inställningar.aspx");//* Define page payout _wikiFullContent = FormatSimpleWikiLayout(); Global.Debug = "Inställningar"; SPFile installningarsida = listSidor.RootFolder.Files.Add(compoundUrl5, SPTemplateFileType.WikiPage); Global.Debug = "wpSettings"; SettingsWP wpSettings = new SettingsWP(); wpSettings.ChromeType = PartChromeType.None; Guid wpSettingsGuid = AddWebPartControlToPage(installningarsida, wpSettings); AddWebPartMarkUpToPage(wpSettingsGuid, "[[COL1]]"); installningarsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent; installningarsida.Item.UpdateOverwriteVersion(); Global.Debug = "Installningarsida skapad"; #endregion } #region debugdata Global.Debug = "ägare"; SPListItem item = listAgare.AddItem(); item["Title"] = "TESTÄGARE AB"; item.Update(); try { Global.Debug = "kontakt"; item = listKontakter.AddItem(); item["Title"] = "Testsson"; item["FirstName"] = "Test"; item["Email"] = "*****@*****.**"; item.Update(); item = listKontakter.AddItem(); item["Title"] = "Jansson"; item["FirstName"] = "Peter"; item["Email"] = "*****@*****.**"; item.Update(); } catch (Exception ex) { Global.WriteLog("Message:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace, EventLogEntryType.Error, 2001); } Global.Debug = "adress"; item = listAdresser.AddItem(); item["Title"] = "Testgatan 13b"; item.Update(); #endregion #region nyhet Global.Debug = "nyhet"; item = listNyheter.AddItem(); item["Title"] = "Vår online plattform för tillsyn av tobak och folköl håller på att starta upp här"; item["Body"] = @"Hej! Nu har första stegen till en online plattform för tillsyn av tobak och folköl tagits. Här kan du som försäljningsställe ladda hem blanketter och ta del av utbildningsmaterial. " + web.Title + " kommun"; item.Update(); #endregion #region länkar Global.Debug = "länkar"; item = listGenvagar.AddItem(); Global.Debug = "Blanketter"; item["Title"] = "Blanketter"; item["URL"] = web.ServerRelativeUrl + "/Blanketter, Blanketter"; item.Update(); item = listGenvagar.AddItem(); Global.Debug = "Utbildningsmaterial"; item["Title"] = "Utbildningsmaterial"; item["URL"] = web.ServerRelativeUrl + "/Utbildningsmaterial, Utbildningsmaterial"; item.Update(); #endregion #region sätt kundnummeregenskaper Global.Debug = "löpnummer"; web.Properties.Add("lopnummer", "1000"); Global.Debug = "prefixformel"; web.Properties.Add("prefixFormula", "%B%R-%N"); Global.Debug = "listAdresserGUID"; web.Properties.Add("listAdresserGUID", listAdresser.ID.ToString()); Global.Debug = "listAgareGUID"; web.Properties.Add("listAgareGUID", listAgare.ID.ToString()); Global.Debug = "gruppkopplingar"; web.Properties.Add("listGruppkopplingarGUID", listGruppkopplingar.ID.ToString()); try { Municipal m = municipals[web.Title.ToLower()]; web.Properties.Add("municipalAreaCode", m.AreaCode); web.Properties.Add("municipalRegionLetter", m.RegionLetter); } catch { } Global.Debug = "properties"; web.Properties.Update(); #endregion } else { Global.WriteLog("Redan aktiverad", EventLogEntryType.Information, 1000); } #region modify template global Global.Debug = "ensure empty working directory"; DirectoryInfo diFeature = new DirectoryInfo(@"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\UPCOR.TillsynKommun"); string webid = web.Url.Replace("http://", "").Replace('/', '_'); string dirname = @"workdir_" + webid; Global.Debug = "dir: " + dirname; DirectoryInfo diWorkDir = diFeature.CreateSubdirectory(dirname); if (!diWorkDir.Exists) diWorkDir.Create(); XNamespace xsf = "http://schemas.microsoft.com/office/infopath/2003/solutionDefinition"; XNamespace xsf3 = "http://schemas.microsoft.com/office/infopath/2009/solutionDefinition/extensions"; XNamespace xd = "http://schemas.microsoft.com/office/infopath/2003"; #endregion #region modify template tillsyn { Global.Debug = "deleting files"; foreach (FileInfo fi in diWorkDir.GetFiles()) { fi.Delete(); } Global.Debug = "extract"; Process p = new Process(); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.StartInfo.FileName = @"C:\Program Files\7-Zip\7z.exe"; //string filename = diTillsyn.FullName + @"\75841904-0c67-4118-826f-b1319db35c6a.xsn"; string filename = diFeature.FullName + @"\4BEB6318-1CE0-47BE-92C2-E9815D312C1A.xsn"; p.StartInfo.Arguments = "e \"" + filename + "\" -y -o\"" + diWorkDir.FullName + "\""; bool start = p.Start(); p.WaitForExit(); if (p.ExitCode != 0) { Global.WriteLog(string.Format("7z Error:\r\n{0}\r\n\r\nFilename:\r\n{1}", p.StandardOutput.ReadToEnd(), filename), EventLogEntryType.Error, 1000); } Global.Debug = "get content type"; SPContentType ctTillsyn = listAktiviteter.ContentTypes[_tillsynName]; Global.Debug = "modify manifest"; XDocument doc = XDocument.Load(diWorkDir.FullName + @"\manifest.xsf"); var xDocumentClass = doc.Element(xsf + "xDocumentClass"); var q1 = from extension in xDocumentClass.Element(xsf + "extensions").Elements(xsf + "extension") where extension.Attribute("name").Value == "SolutionDefinitionExtensions" select extension; var node1 = q1.First().Element(xsf3 + "solutionDefinition").Element(xsf3 + "baseUrl"); node1.Attribute("relativeUrlBase").Value = web.Url + "/Lists/Aktiviteter/Tillsyn/"; var q2 = from dataObject in xDocumentClass.Element(xsf + "dataObjects").Elements(xsf + "dataObject") where dataObject.Attribute("name").Value == "Kundkort" select dataObject; var node2 = q2.First().Element(xsf + "query").Element(xsf + "sharepointListAdapterRW"); node2.Attribute("sharePointListID").Value = "{" + listKundkort.ID.ToString() + "}"; var node3 = xDocumentClass.Element(xsf + "query").Element(xsf + "sharepointListAdapterRW"); node3.Attribute("sharePointListID").Value = "{" + listAktiviteter.ID.ToString() + "}"; node3.Attribute("contentTypeID").Value = ctTillsyn.Id.ToString(); doc.Save(diWorkDir.FullName + @"\manifest.xsf"); Global.Debug = "modify view1"; XDocument doc2 = XDocument.Load(diWorkDir.FullName + @"\view1.xsl"); foreach (var d in doc2.Descendants("object")) { d.Attribute(xd + "server").Value = web.Url + "/"; } doc2.Save(diWorkDir.FullName + @"\view1.xsl"); Global.Debug = "repack"; string directive = "directives_inspection_" + webid + ".txt"; string cabinet = "template_inspection_" + webid + ".xsn"; FileInfo fiDirectives = new FileInfo(diFeature.FullName + '\\' + directive); if (fiDirectives.Exists) fiDirectives.Delete(); using (StreamWriter sw = fiDirectives.CreateText()) { sw.WriteLine(".OPTION EXPLICIT"); sw.WriteLine(".set CabinetNameTemplate=" + cabinet); sw.WriteLine(".set DiskDirectoryTemplate=\"" + diFeature.FullName + "\""); sw.WriteLine(".set Cabinet=on"); sw.WriteLine(".set Compress=on"); foreach (FileInfo file in diWorkDir.GetFiles()) { sw.WriteLine('"' + file.FullName + '"'); } } Process p2 = new Process(); p2.StartInfo.RedirectStandardOutput = true; p2.StartInfo.UseShellExecute = false; //p2.StartInfo.FileName = diTillsyn.FullName + @"\makecab.exe"; p2.StartInfo.FileName = @"c:\windows\system32\makecab.exe"; p2.StartInfo.WorkingDirectory = diFeature.FullName; p2.StartInfo.Arguments = "/f " + fiDirectives.Name; bool start2 = p2.Start(); p2.WaitForExit(); if (p.ExitCode != 0) { Global.WriteLog(string.Format("makecab Error:\r\n{0}", p2.StandardOutput.ReadToEnd()), EventLogEntryType.Error, 1000); } Global.Debug = "upload"; FileInfo fiTemplate = new FileInfo(diFeature.FullName + '\\' + cabinet); if (fiTemplate.Exists) { using (FileStream fs = fiTemplate.OpenRead()) { byte[] data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length); SPFile file = listAktiviteter.RootFolder.Files.Add("Lists/Aktiviteter/Tillsyn/template.xsn", data); Global.Debug = "set file properties"; //file.Properties["vti_contenttag"] = "{6908F1AD-3962-4293-98BB-0AA4FB54B9C9},3,1"; file.Properties["ipfs_streamhash"] = "0NJ+LASyxjJGhaIwPftKfwraa3YBBfJoNUPNA+oNYu4="; file.Properties["ipfs_listform"] = "true"; file.Update(); } Global.Debug = "set folder properties"; SPFolder folder = listAktiviteter.RootFolder.SubFolders["Tillsyn"]; folder.Properties["_ipfs_solutionName"] = "template.xsn"; folder.Properties["_ipfs_infopathenabled"] = "True"; folder.Update(); } else { Global.WriteLog("template.xsn missing", EventLogEntryType.Error, 1000); } //Global.Debug = "set default forms"; //// create our own array since it will be modified (which would throw an exception) //var forms = new SPForm[listAktiviteter.Forms.Count]; //int j = 0; //foreach (SPForm form in listAktiviteter.Forms) { // forms[j] = form; // j++; //} //foreach (var form in forms) { // SPFile page = web.GetFile(form.Url); // SPLimitedWebPartManager limitedWebPartManager = page.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); // foreach (System.Web.UI.WebControls.WebParts.WebPart wp in limitedWebPartManager.WebParts) { // if (wp is BrowserFormWebPart) { // BrowserFormWebPart bfwp = (BrowserFormWebPart)wp.WebBrowsableObject; // bfwp.FormLocation = bfwp.FormLocation.Replace("/Item/", "/Tillsyn/"); // limitedWebPartManager.SaveChanges(bfwp); // switch (form.Type) { // case PAGETYPE.PAGE_NEWFORM: // listAktiviteter.DefaultNewFormUrl = form.ServerRelativeUrl; // break; // case PAGETYPE.PAGE_EDITFORM: // listAktiviteter.DefaultEditFormUrl = form.ServerRelativeUrl; // break; // case PAGETYPE.PAGE_DISPLAYFORM: // listAktiviteter.DefaultDisplayFormUrl = form.ServerRelativeUrl; // break; // } // } // } //} } #endregion #region modify template permit { Global.Debug = "delete"; foreach (FileInfo fi in diWorkDir.GetFiles()) { fi.Delete(); } Global.Debug = "extract"; Process p = new Process(); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.StartInfo.FileName = @"C:\Program Files\7-Zip\7z.exe"; string filename = diFeature.FullName + @"\givepermit.xsn"; p.StartInfo.Arguments = "e \"" + filename + "\" -y -o\"" + diWorkDir.FullName + "\""; bool start = p.Start(); p.WaitForExit(); if (p.ExitCode != 0) { Global.WriteLog(string.Format("7z Error:\r\n{0}\r\n\r\nFilename:\r\n{1}", p.StandardOutput.ReadToEnd(), filename), EventLogEntryType.Error, 1000); } Global.Debug = "get content type"; SPContentType ctPermit = listAktiviteter.ContentTypes[_permitName]; Global.Debug = "modify manifest"; XDocument doc = XDocument.Load(diWorkDir.FullName + @"\manifest.xsf"); var xDocumentClass = doc.Element(xsf + "xDocumentClass"); var q1 = from extension in xDocumentClass.Element(xsf + "extensions").Elements(xsf + "extension") where extension.Attribute("name").Value == "SolutionDefinitionExtensions" select extension; var node1 = q1.First().Element(xsf3 + "solutionDefinition").Element(xsf3 + "baseUrl"); node1.Attribute("relativeUrlBase").Value = web.Url + "/Lists/Aktiviteter/Ge%20försäljningstillstånd/"; var q2 = from dataObject in xDocumentClass.Element(xsf + "dataObjects").Elements(xsf + "dataObject") where dataObject.Attribute("name").Value == "Kundkort" select dataObject; var node2 = q2.First().Element(xsf + "query").Element(xsf + "sharepointListAdapterRW"); node2.Attribute("sharePointListID").Value = "{" + listKundkort.ID.ToString() + "}"; var node3 = xDocumentClass.Element(xsf + "query").Element(xsf + "sharepointListAdapterRW"); node3.Attribute("sharePointListID").Value = "{" + listAktiviteter.ID.ToString() + "}"; node3.Attribute("contentTypeID").Value = ctPermit.Id.ToString(); doc.Save(diWorkDir.FullName + @"\manifest.xsf"); //Global.Debug = "modify view1"; //XDocument doc2 = XDocument.Load(diWorkDir.FullName + @"\view1.xsl"); //foreach (var d in doc2.Descendants("object")) { // d.Attribute(xd + "server").Value = web.Url + "/"; //} //doc2.Save(diWorkDir.FullName + @"\view1.xsl"); Global.Debug = "repack"; string directive = "directives_permit_" + webid + ".txt"; string cabinet = "template_permit_" + webid + ".xsn"; FileInfo fiDirectives = new FileInfo(diFeature.FullName + '\\' + directive); if (fiDirectives.Exists) fiDirectives.Delete(); using (StreamWriter sw = fiDirectives.CreateText()) { sw.WriteLine(".OPTION EXPLICIT"); sw.WriteLine(".set CabinetNameTemplate=" + cabinet); sw.WriteLine(".set DiskDirectoryTemplate=\"" + diFeature.FullName + "\""); sw.WriteLine(".set Cabinet=on"); sw.WriteLine(".set Compress=on"); foreach (FileInfo file in diWorkDir.GetFiles()) { sw.WriteLine('"' + file.FullName + '"'); } } Process p2 = new Process(); p2.StartInfo.RedirectStandardOutput = true; p2.StartInfo.UseShellExecute = false; //p2.StartInfo.FileName = diTillsyn.FullName + @"\makecab.exe"; p2.StartInfo.FileName = @"c:\windows\system32\makecab.exe"; p2.StartInfo.WorkingDirectory = diFeature.FullName; p2.StartInfo.Arguments = "/f " + fiDirectives.Name; bool start2 = p2.Start(); p2.WaitForExit(); if (p.ExitCode != 0) { Global.WriteLog(string.Format("makecab Error:\r\n{0}", p2.StandardOutput.ReadToEnd()), EventLogEntryType.Error, 1000); } Global.Debug = "upload"; FileInfo fiTemplate = new FileInfo(diFeature.FullName + '\\' + cabinet); if (fiTemplate.Exists) { using (FileStream fs = fiTemplate.OpenRead()) { byte[] data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length); SPFile file = listAktiviteter.RootFolder.Files.Add("Lists/Aktiviteter/Ge försäljningstillstånd/template.xsn", data); Global.Debug = "set file properties"; //file.Properties["vti_contenttag"] = "{6908F1AD-3962-4293-98BB-0AA4FB54B9C9},3,1"; file.Properties["ipfs_streamhash"] = "0NJ+LASyxjJGhaIwPftKfwraa3YBBfJoNUPNA+oNYu4="; file.Properties["ipfs_listform"] = "true"; file.Update(); } Global.Debug = "set folder properties"; SPFolder folder = listAktiviteter.RootFolder.SubFolders["Ge försäljningstillstånd"]; folder.Properties["_ipfs_solutionName"] = "template.xsn"; folder.Properties["_ipfs_infopathenabled"] = "True"; folder.Update(); } else { Global.WriteLog("template.xsn missing", EventLogEntryType.Error, 1000); } } #endregion #region set default forms Global.Debug = "set default forms"; foreach (SPContentType ct in listAktiviteter.ContentTypes) { switch (ct.Name) { case "Tillsyn": case "Ge försäljningstillstånd": ct.DisplayFormUrl = "~list/" + ct.Name + "/displayifs.aspx"; ct.EditFormUrl = "~list/" + ct.Name + "/editifs.aspx"; ct.NewFormUrl = "~list/" + ct.Name + "/newifs.aspx"; ct.Update(); break; default: ct.DisplayFormUrl = ct.EditFormUrl = ct.NewFormUrl = string.Empty; ct.Update(); break; } } // create our own array since it will be modified (which would throw an exception) var forms = new SPForm[listAktiviteter.Forms.Count]; int j = 0; foreach (SPForm form in listAktiviteter.Forms) { forms[j] = form; j++; } foreach (var form in forms) { SPFile page = web.GetFile(form.Url); SPLimitedWebPartManager limitedWebPartManager = page.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); foreach (System.Web.UI.WebControls.WebParts.WebPart wp in limitedWebPartManager.WebParts) { if (wp is BrowserFormWebPart) { BrowserFormWebPart bfwp = (BrowserFormWebPart)wp.WebBrowsableObject; //bfwp.FormLocation = bfwp.FormLocation.Replace("/Item/", "/Ge försäljningstillstånd/"); //limitedWebPartManager.SaveChanges(bfwp); string[] aLocation = form.Url.Split('/'); string contenttype = aLocation[aLocation.Length - 2]; bfwp.FormLocation = "~list/" + contenttype + "/template.xsn"; limitedWebPartManager.SaveChanges(bfwp); StringBuilder sb = new StringBuilder(); sb.AppendLine(); sb.Append("BrowserFormWebPart FormLocation: "); sb.AppendLine(bfwp.FormLocation); sb.Append("BrowserFormWebPart Title: "); sb.AppendLine(bfwp.Title); sb.Append("BrowserFormWebPart ID: "); sb.AppendLine(bfwp.ID); sb.Append("Form URL: "); sb.AppendLine(form.Url); sb.Append("Form TemplateName: "); sb.AppendLine(form.TemplateName); sb.Append("Form ID: "); sb.AppendLine(form.ID.ToString()); sb.Append("Form ServerRelativeUrl: "); sb.AppendLine(form.ServerRelativeUrl); sb.AppendLine("BrowserFormWebPart Schema: "); sb.AppendLine(); sb.AppendLine(form.SchemaXml); Global.WriteLog(sb.ToString(), EventLogEntryType.Information, 1000); //switch (form.Type) { // case PAGETYPE.PAGE_NEWFORM: // listAktiviteter.DefaultNewFormUrl = form.ServerRelativeUrl; // break; // case PAGETYPE.PAGE_EDITFORM: // listAktiviteter.DefaultEditFormUrl = form.ServerRelativeUrl; // break; // case PAGETYPE.PAGE_DISPLAYFORM: // listAktiviteter.DefaultDisplayFormUrl = form.ServerRelativeUrl; // break; //} } } } #endregion #region cleanup Global.Debug = "cleanup"; diWorkDir.Delete(true); foreach (FileInfo fi in diFeature.GetFiles("template*.xsn")) fi.Delete(); foreach (FileInfo fi in diFeature.GetFiles("directives*.xsn")) fi.Delete(); #endregion #region stäng av required på rubrik SPField title = listKundkort.Fields[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")]; Global.WriteLog("listKundkort Title - Required: " + title.Required.ToString() + ", ShowInNew: " + title.ShowInNewForm.ToString() + ", ShowInEdit: " + title.ShowInEditForm.ToString(), EventLogEntryType.Information, 1000); title.Required = false; title.ShowInNewForm = false; title.ShowInEditForm = false; title.Update(); //title = listAktiviteter.Fields[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")]; //Global.WriteLog("listAktiviteter Title - Required: " + title.Required.ToString() + ", ShowInNew: " + title.ShowInNewForm.ToString() + ", ShowInEdit: " + title.ShowInEditForm.ToString(), EventLogEntryType.Information, 1000); //title.Required = false; //title.ShowInNewForm = false; //title.ShowInEditForm = false; //title.Update(); foreach (SPContentType ct in listAktiviteter.ContentTypes) { SPFieldLink flTitle = ct.FieldLinks[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")]; flTitle.Required = false; flTitle.Hidden = true; ct.Update(); } #endregion Global.WriteLog("Feature Activated", EventLogEntryType.Information, 1001); } catch (Exception ex) { Global.WriteLog("Message:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace, EventLogEntryType.Error, 2001); } } // feature activated