Hiding Title FIeld in Sharepoint not working - c#

I am trying to do the following to hide the title field from the new and edit form but its still visible.
pls help
/// <summary>
/// Adds source list and content type.
/// </summary>
/// <param name="currentWeb"></param>
private void AddSourcesList(SPWeb currentWeb)
{
currentWeb.AllowUnsafeUpdates = true;
#region Add Source content type.
if(currentWeb.ContentTypes[SponsoringCommon.Constants.CONTENTTYPES_SOURCES_NAME] == null)
{
#region Hides title column
currentWeb.Lists.Add(SponsoringCommon.Constants.LISTNAMES_SOURCES_NAME, string.Empty, SPListTemplateType.GenericList);
SPList sourceList = currentWeb.Lists.TryGetList(SponsoringCommon.Constants.LISTNAMES_SOURCES_NAME);
SPField titleField = sourceList.Fields.GetField("Title");
titleField.Required = false;
titleField.ShowInEditForm = false;
titleField.ShowInDisplayForm = false;
titleField.ShowInNewForm = false;
titleField.Hidden = true;
titleField.Update();
#endregion

I cannot see the rest of the code, but I had similar problem, and the thing I was missing is to .Update() the List and the Web. So in your case try to update sourceList and at the end currentWeb.
Hopefully, it will help solve your problem.

Related

How can you store a Control in a class and reuse it in a binding?

I am trying to reuse NumberBoxes for a GridView because having the NumberBoxes embedded directly in the GridView data template causes undesirable behavior, while reusing them does not. The problem is that I keep getting exceptions. They say "No installed components were detected" on the following line (templateRoot.FindName("NumberBox") as GridViewItem).Content = item.NumberBox; in this context
/// <summary>
/// The callback for updating a container in the GridView named CardGridView.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void UpdateGridViewContainer(ListViewBase sender, ContainerContentChangingEventArgs args)
{
if (args.Phase == 1)
{
Grid templateRoot = args.ItemContainer.ContentTemplateRoot as Grid;
CardItem item = args.Item as CardItem;
(templateRoot.FindName("NumberBox") as GridViewItem).Content = item.NumberBox;
TypedEventHandler<NumberBox, NumberBoxValueChangedEventArgs> handler =
(box, args) =>
{
if (!double.IsNaN(args.NewValue))
{
_viewModel.ChangeCount(args, item);
}
};
item.SetHandler(handler);
}
}
The exception is thrown when the Page that contains the GridView is left and renavigated to. I have tried nulling out the NumberBoxes when the page is left, but that did not work. Well, it appeared to before the issue cropped up again.
This is the code that nulls out the NumberBoxes
/// <summary>
/// Creates new NumberBoxes for when this Page is loaded again.
/// </summary>
private void ResetNumberBoxes()
{
foreach (CardItem card in CardGridView.Items.Cast<CardItem>())
{
card.ResetNumberBox();
}
CardGridView.ItemsSource = null;
CardGridView.Items.Clear();
}
ResetNumberBox is just setting the NumberBox to null and assigning a new one.
The exception details
System.Runtime.InteropServices.COMException
HResult=0x800F1000
Message=No installed components were detected. (0x800F1000)
Source=WinRT.Runtime
StackTrace:
at WinRT.ExceptionHelpers.<ThrowExceptionForHR>g__Throw|20_0(Int32 hr)
at ABI.Microsoft.UI.Xaml.Controls.IContentControlMethods.set_Content(IObjectReference _obj, Object value)
An update. I have removed the GridViewItem control from the DataTemplate and tried doing the following with the same result
CardItem item = args.Item as CardItem;
Grid.SetColumn(item.NumberBox, 1);
item.NumberBox.HorizontalAlignment = HorizontalAlignment.Center;
item.NumberBox.VerticalAlignment = VerticalAlignment.Center;
(templateRoot.FindName("GridViewTemplate") as Grid).Children.Add(item.NumberBox);
I also examined a heap dump right before the line that throws, and there was only one instance of the Grid, and the NumberBox had a parent of null.

Testing WPF ViewModel with Xunit

Recently I was put on new a team at work and the lead told me to write unit tests for the code they had written. I'm really not sure where to start. The application is a WPF written in C#. I'm a newbie to both WPF and C#. They mentioned using Xunit.
Here is first two functions of the class. There is mix of protected and public functions i have to unit test,
The class type is public class DataTableModel<T> : ViewModelBase
public DataTableModel()
{
//Setup Drag and Drop Commands:
RecordReceivedCommand = new DataTableReceivedCommand<T>(this);
RecordRemovedCommand = new DataTableRemovedCommand<T>(this);
RecordInsertedCommand = new DataTableInsertedCommand<T>(this);
View = CollectionViewSource.GetDefaultView(Records);
}
/// <summary>
/// This method sets up the properties for the table. By default, the first DisplayOption is selected, no search criteria is applies, and only 10 records should be returned.
/// </summary>
/// <param name="displayOption">The selected display option</param>
protected void InstantiateTable(int displayOption = 0)
{
_displayOption = displayOption;
_searchCriteria = "";
_displayAmount = "10";
_currentPage = 1;
_userMessage = "Retrieving data...";
TriggerUpdate();
}
These functions are called from above so I thought I'd include them.
/// <summary>
/// This method is responsible for handling the updates to the recordset that the DataGrid will display.
/// Upon changes to the search criteria, display amount, display option and the current page, this method will be triggered
/// </summary>
/// <param name="resetPage">Inidicates whether the grid should return to page 1.</param>
protected void TriggerUpdate(bool resetPage = false)
{
_currentPage = resetPage ? 1 : _currentPage; //only reset to the first page if indicated
UserMessage = "Retrieving data...";
//Retrieve the records if the delegate has been set
GetRecords?.Invoke();
UserMessage = Records.Count == 0 ? "No data found" : "";
Message_ZIndex = !String.IsNullOrWhiteSpace(UserMessage) ? 1 : -1;
//update the page navigations button's settings when the pages are reset
UpdatePagination();
}
/// <summary>
/// Update the ability to navigate through the datatable's pages.
/// Upon changes the the search criteria, display amount, display option, the number of pages and the current page, this method will be
/// triggered
/// </summary>
private void UpdatePagination()
{
if (Pages > 1)
{
if (_currentPage == 1)
{
GoToFirstPage = false;
GoToPrevPage = false;
GoToNextPage = true;
GoToLastPage = true;
}
else if (_currentPage == Pages)
{
GoToFirstPage = true;
GoToPrevPage = true;
GoToNextPage = false;
GoToLastPage = false;
}
else
{
GoToFirstPage = true;
GoToPrevPage = true;
GoToNextPage = true;
GoToLastPage = true;
}
}
else
{
GoToFirstPage = false;
GoToPrevPage = false;
GoToNextPage = false;
GoToLastPage = false;
}
}
/// <summary>
/// Get's the information for the datatable's columns
/// (NOTE: This method is currently only called via ".Invoke" within the DataTable control.)
/// </summary>
/// <returns>A List of the DataTableDisplay attributes for the columns in the table</returns>
public List<DataTableDisplay> GetTableColumnInformation()
{
List<DataTableDisplay> attributes = new List<DataTableDisplay>();
PropertyInfo[] properties = typeof(T).GetProperties();
foreach(PropertyInfo property in properties)
{
DataTableDisplay attr = property.GetCustomAttribute<DataTableDisplay>(false);
if (attr != null && !String.IsNullOrWhiteSpace(attr.ColumnTitle))
{
attributes.Add(attr);
}
}
return attributes;
}
At first I wanted to test the constructor, but then I didn't know how to check for the command vars so i moved on to the InstantiateTable function. This is what i got. Still having to create object so using the Constructor but when i tried calling x.InstantiateTable() I noticed it was protected so I cant do that.
Test case for creating an DataTableModel Object. It had dynamic type so i just made it int.
[Fact]
public void DataTableModel_Created()
{
DataTableModel<int> x = new DataTableModel<int>();
Assert.Equal(0, x.DisplayOption);
Assert.Equal("", x.SearchCriteria);
Assert.Equal("10", x.DisplayAmount);
Assert.Equal(1, x.CurrentPage);
Assert.Equal("Retrieving data...", x.UserMessage);
}
Another protected function i have to unit test.
protected List<T> UpdateTable(List<T> data)
{
_totalCount = data.Count;
int recordLimit = String.IsNullOrEmpty(DisplayAmount) ? 0 : Convert.ToInt32(DisplayAmount);
int startingRecord = recordLimit == 0 ? 0 : (_currentPage == 1 ? 1 : 1 + (recordLimit * (_currentPage - 1)));
int recordsToSkip = (CurrentPage - 1) * recordLimit;
int endingRecord = recordLimit == 0 ? 0 : recordLimit > _totalCount ? _totalCount : startingRecord + recordLimit - 1;
Pages = recordLimit == 0 ? 0 : _totalCount <= recordLimit ? 1 : _totalCount % recordLimit > 0 ? (_totalCount / recordLimit) + 1 : _totalCount / recordLimit;
List<T> displayRecords = data.Skip(recordsToSkip).Take(recordLimit).ToList();
DisplayMessage = endingRecord <= _totalCount ? $"Showing {(displayRecords.Count == 0 ? 0 : startingRecord)} to {endingRecord} of {_totalCount} entries" : $"Showing {startingRecord} to {_totalCount} of {_totalCount} entries";
return displayRecords;
}
And a delegate function? I'm supposed to test
public delegate List<T> Filter(List<T> data);
I am not sure how to approach. The few unit tests i did in university were basic objects and didn't call other objects and what not. I have read about mocking and stubbing objects, I think it may be good to mock database to populate the tables.
Do not unit-test functions. Unit-test view-models.
A view-model exposes properties and commands which are bound by XAML to GUI controls so that the user can interact with them.
All these properties and commands are already public, otherwise they would not be visible from XAML, so your tests can access them too.
Most C# programmers will not think twice before converting private and protected to public, or converting to internal and then using InternalsVisibleTo, but in my opinion that's all misguided. We must be testing against the interface, not against the implementation; therefore, we must be engaging in black-box testing, not white-box testing.
When it comes to testing view-models in WPF, this means you should only test things that are exposed to XAML.
So, your tests should set values to view-model properties as if these values were set by GUI controls, invoke view-model commands as if these commands were triggered by GUI buttons.
Then, your tests should examine nothing but how the values of view-model properties change as a result. That's what the user would see on the screen.

Does Bringtofront() go before or after ResumeLayout? Does it matter?

So I've been digging into the whole SuspendLayout()/ResumeLayout() logic for a while now and I've been trying to implement it in the most efficient manner. One question I'm unable to find an answer for is that of which I've asked in the title : Does the BringToFront() method go before or after you call ResumeLayout()? Does it matter? My initial thought process is no, it doesn't matter, because it's only changing the z-index of the control and not effecting the control's layout, but I just want to be sure.
Here's block of code from my project where my question comes into play:
Note:This project runs on a Motorola MC65 mobile device and uses .net compact 3.5 framework
/// <summary>
/// Initializes the <see cref="VerifyReplacementPanel"/> class
/// </summary>
/// <param name="hostControl">The panel this control is being added to</param>
/// <param name="original">The product being replaced</param>
/// <param name="replacement">The product replacing with</param>
/// <param name="logHelper">The log helper interface</param>
public VerifyReplacementPanel(Control hostControl, ProductModel original, ProductModel replacement, ILogHelper logHelper)
{
hostControl.SuspendLayout();
SuspendLayout();
HostControl = hostControl;
Product = original;
Replacement = replacement;
_logHelper = logHelper;
Size = Size.FullScreen();
// original product panel
var panOrig = new blkPan(472, 75) { Location = new Point(4, 147), BackColor = Color.White };
var originalProductPanel = new ProductPanelArrayModel(panOrig, _logHelper);
originalProductPanel.AddPanelWithPic(original);
Controls.Add(panOrig);
// replacement product panel
var panRepl = new blkPan(472, 75) { Location = new Point(4, panOrig.B + 100), BackColor = Color.White };
var replacementProductPanel = new ProductPanelArrayModel(panRepl, _logHelper);
replacementProductPanel.AddPanelWithPic(replacement);
Controls.Add(panRepl);
// no button
var btnNo = new PushButton("No", ObjectName, true) { Location = new Point(38, Bottom - 93 - 36) };
btnNo.Click += btnNo_Click;
Controls.Add(btnNo);
_btnNoTop = btnNo.Top;
// yes button
var btnYes = new PushButton("Yes", ObjectName, true) { Location = new Point(259, btnNo.Top) };
btnYes.Click += btnYes_Click;
Controls.Add(btnYes);
ResumeLayout(false);
HostControl.Controls.Add(this);
BringToFront();
HostControl.ResumeLayout();
}
My question is interested in this section :
ResumeLayout(false);
HostControl.Controls.Add(this);
BringToFront();
HostControl.ResumeLayout();
Also, am I even using it correctly? Thank you for your time.

DataGridView save filtering after reload

I have some problem with DataGridView in C#.
case is:
I do some update on database then I reload DataGridView with new values:
myDataGridView.DataSource = myDataSet.Tables[0]
Everything is ok, but recently I was asked if there is possibility to keep the same column filtering applied after reloading data?
What would be approach to do this filtering case?
Thanks for any ideas.
Ok, I found the solution, maybe it will help somebody:
[btw. I made some language mistake filtering = sorting ;-)]
DataGridViewColumn oldColumn = dataGridView1.SortedColumn;
ListSortDirection direction;
if (dataGridView1.SortOrder == SortOrder.Ascending) direction = ListSortDirection.Ascending;
else direction = ListSortDirection.Descending;
databaseUpdateFunction();
DataGridViewColumn newColumn = dataGridView1.Columns[oldColumn.Name.ToString()];
dataGridView1.Sort(newColumn,direction);
newColumn.HeaderCell.SortGlyphDirection =
direction == ListSortDirection.Ascending ?
SortOrder.Ascending : SortOrder.Descending;
I used parts of code from : link text
I took kuba's solution, and put it in a utility class I can use on any DataGridView:
private static ListSortDirection _oldSortOrder;
private static DataGridViewColumn _oldSortCol;
/// <summary>
/// Saves information about sorting column, to be restored later by calling RestoreSorting
/// on the same DataGridView
/// </summary>
/// <param name="grid"></param>
public static void SaveSorting(DataGridView grid)
{
_oldSortOrder = grid.SortOrder == SortOrder.Ascending ?
ListSortDirection.Ascending : ListSortDirection.Descending;
_oldSortCol = grid.SortedColumn;
}
/// <summary>
/// Restores column sorting to a datagrid. You MUST call this AFTER calling
/// SaveSorting on the same DataGridView
/// </summary>
/// <param name="grid"></param>
public static void RestoreSorting(DataGridView grid)
{
if (_oldSortCol != null)
{
DataGridViewColumn newCol = grid.Columns[_oldSortCol.Name];
grid.Sort(newCol, _oldSortOrder);
}
}
Using this looks like:
GridUtility.SaveSorting(grid);
grid.DataSource = databaseFetch(); // or whatever
GridUtility.RestoreSorting(grid);
I came across Adam Nofsinger's answer before I encounterd the problem, but I used it anyway. It works wonderfull.
Just needed to add these 2 using lines to my class file:
using System.ComponentModel;
using System.Windows.Forms;
Thanks,
Geert.
This worked for me:
//preserve existing sort column and direction
ListSortDirection direction;
DataGridViewColumn oldsort = MyDataGridView.SortedColumn;
if (MyDataGridView.SortOrder == SortOrder.Ascending)
{ direction = ListSortDirection.Ascending; } else { direction = ListSortDirection.Descending; }
//this is refresh
MyDataGridView.DataSource = data;
//reapply sort and direction
if (oldsort != null) { MyDataGridView.Sort(MyDataGridView.Columns[oldsort.Name], direction); }

Date validating Textbox server control

I'm trying to create a custom server control that is just a textbox with an AJAX asp.net MASKEDEDITEXTENDER to valid the control when it loses focus to ensure that a proper date has been entered.
This is all I have so far and I'm able to build the control but no validation is taking place what am I doing wrong here.
namespace One_Eva_Control_Library
{
[ToolboxData("<{0}:Valid_Date_Textbox runat=server></{0}:Valid_Date_Textbox>")]
public class Valid_Date_Textbox : System.Web.UI.WebControls.TextBox
{
#region Methods
/// <summary>
/// Creates Validator
/// </summary>
/// <param name="e">Init eventArg</param>
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
MaskedEditExtender meDateValidator = new MaskedEditExtender();
meDateValidator.ID = "dateExtender";
meDateValidator.Mask = "99/99/9999";
meDateValidator.MessageValidatorTip = true;
meDateValidator.MaskType = MaskedEditType.Date;
meDateValidator.UserDateFormat = MaskedEditUserDateFormat.DayMonthYear;
meDateValidator.CultureName = "en-GB";
MaskedEditValidator meEditValidtor = new MaskedEditValidator();
meEditValidtor.ControlExtender = meDateValidator.ID;
meEditValidtor.ControlToValidate = base.ID;
meEditValidtor.InvalidValueMessage = "Invalid Date";
meEditValidtor.Display = ValidatorDisplay.Dynamic;
meEditValidtor.TooltipMessage = "Input date in 99/99/9999 format";
meEditValidtor.InvalidValueMessage = "*";
meEditValidtor.ValidationGroup = "MKE";
}
#endregion
}
You need to add them to the controls collection. I don't know that inheriting from TextBox will get you what you want; I think you may need to inherit from CompositeControl, and override CreateChildControls and create the textbox, and the extender/validator. Just make sure to add all of them to the controls collection...

Categories

Resources