I saw 2 different way to create web parts for sharepoint. Which one is preferred by most?
http://msdn.microsoft.com/en-us/library/aa973249%28office.12%29.aspx
Anything involving VSeWSS is just going to end in pain, so method 1 is definitely out. Method 2 isn't ideal either, as setting up html elements as controls becomes unmanageable at a level just beyond what you see in that demo. I use a fairly simple generic base class that takes a user control as a type parameter and lets me keep all the layout nicely seperated from the sharepoint infrastructure. If you are creating pages/web parts programatically most of the web part xml turns out to be optional also.
public abstract class UserControlWebPart<T> : Microsoft.SharePoint.WebPartPages.WebPart where T:UserControl
{
protected UserControlWebPart()
{
this.ExportMode = WebPartExportMode.All;
}
protected virtual void TransferProperties(T ctrl)
{
var tc = typeof(T);
var tt = this.GetType();
foreach (var p in tt.GetProperties()) {
if (p.IsDefined(typeof(ControlPropertyAttribute), true)) {
foreach (var p2 in tc.GetProperties()) {
if (p2.Name == p.Name) {
p2.SetValue(ctrl, p.GetValue(this, null), null);
}
}
}
}
}
protected override void CreateChildControls()
{
string controlURL = ControlFolder+typeof(T).Name+".ascx";
var ctrl = Page.LoadControl(controlURL) as T;
TransferProperties(ctrl);
this.Controls.Add(ctrl);
}
protected virtual string ControlFolder
{
get {
return "~/_layouts/UserControlWebParts/";
}
}
}
For the few web parts I've written, I guess I've gone more with method #2 than method #1. Seems more straightforward and has the potential to be reused outside of the SharePoint environment (depending on the depth of your business logic).
Related
When I bind a "back button" to a the router in ReactiveUI, my ViewModel is no longer garbage collected (my view too). Is this a bug, or is this me doing something dumb?
Here is my MeetingPageViewModel:
public class MeetingPageViewModel : ReactiveObject, IRoutableViewModel
{
public MeetingPageViewModel(IScreen hs, IMeetingRef mRef)
{
HostScreen = hs;
}
public IScreen HostScreen { get; private set; }
public string UrlPathSegment
{
get { return "/meeting"; }
}
}
Here is my MeetingPage.xaml.cs file:
public sealed partial class MeetingPage : Page, IViewFor<MeetingPageViewModel>
{
public MeetingPage()
{
this.InitializeComponent();
// ** Comment this out and both the View and VM will get garbage collected.
this.BindCommand(ViewModel, x => x.HostScreen.Router.NavigateBack, y => y.backButton);
// Test that goes back right away to make sure the Execute
// wasn't what was causing the problem.
this.Loaded += (s, a) => ViewModel.HostScreen.Router.NavigateBack.Execute(null);
}
public MeetingPageViewModel ViewModel
{
get { return (MeetingPageViewModel)GetValue(ViewModelProperty); }
set { SetValue(ViewModelProperty, value); }
}
public static readonly DependencyProperty ViewModelProperty =
DependencyProperty.Register("ViewModel", typeof(MeetingPageViewModel), typeof(MeetingPage), new PropertyMetadata(null));
object IViewFor.ViewModel
{
get { return ViewModel; }
set { ViewModel = (MeetingPageViewModel)value; }
}
}
I then run, and to see what is up, I use VS 2013 Pro, and turn on the memory analyzer. I also (as a test) put in forced GC collection of all generations and a wait for finalizers. When that line is uncommented above, when all is done, there are three instances of MeetingPage and MeetingPageViewModel. If I remove the BindCommand line, there are no instances.
I was under the impression that these would go away on their own. Is the problem the HostScreen object or the Router that refers to an object that lives longer than this VM? And that pins things down?
If so, what is the recommended away of hooking up the back button? Using Splat and DI? Many thanks!
Following up on the idea I had at the end, I can solve this in the following way. In my App.xaml.cs, I make sure to declare the RoutingState to the dependency injector:
var r = new RoutingState();
Locator.CurrentMutable.RegisterConstant(r, typeof(RoutingState));
then, in the ctor of each view (the .xaml.cs code) with a back button for my Windows Store app, I no longer use the code above, but replace it with:
var router = Locator.Current.GetService<RoutingState>();
backButton.Click += (s, args) => router.NavigateBack.Execute(null);
After doing that I can visit the page as many times as I want and never do I see the instances remaining in the analyzer.
I'll wait to mark this as an answer to give real experts some time to suggest another (better?) approach.
I'm making a simple 2D game for Android using the Unity3D game engine. I created all the levels and everything but I'm stuck at making the game over/retry menu. So far I've been using new scenes as a game over menu. I used this simple script:
#pragma strict
var level = Application.LoadLevel;
function OnCollisionEnter(Collision : Collision)
{
if(Collision.collider.tag == "Player")
{
Application.LoadLevel("GameOver");
}
}
And this as a 'menu':
#pragma strict
var myGUISkin : GUISkin;
var btnTexture : Texture;
function OnGUI() {
GUI.skin = myGUISkin;
if (GUI.Button(Rect(Screen.width/2-60,Screen.height/2+30,100,40),"Retry"))
Application.LoadLevel("Easy1");
if (GUI.Button(Rect(Screen.width/2-90,Screen.height/2+100,170,40),"Main Menu"))
Application.LoadLevel("MainMenu");
}
The problem stands at the part where I have to create over 200 game over scenes, obstacles (the objects that kill the player) and recreate the same script over 200 times for each level. Is there any other way to make this faster and less painful?
Edit : If possible,please when you suggest your ideas,use javascript only,I don't understand C#,not even a little bit.I know Im asking too much but it realy confuses me.
Thank you.
There are several different solutions, but I would recommend using PlayerPrefs. This has the extra benefit of persisting even when the application is closed and then re-opened.
In your Awake() function of your Main Menu class, you can get the current level and store it in a static string of your Main Menu class. If it is the player's 1st time, use the name for level 1.
Something like this:
static string currentLevelName;
void Awake()
{
currentLevelName = PlayerPrefs.GetString("CurrentLevel");
if (currentLevelName == defaultValue)
{
currentLevelName = "Level1"
}
}
Then, modify your button to do this instead:
if (GUI.Button(Rect(Screen.width/2-60,Screen.height/2+30,100,40),"Retry"))
Application.LoadLevel(currentLevelName);
Whenever the player advances to the next level, set the string in PlayerPrefs to the new level name:
PlayerPrefs.SetString("CurrentLevel", Application.loadedLevelName);
You can create a class with static properties. For example (in c#)
public class GameOverInput
{
public static string name;
public static string retryLevel;
//all the info you need
}
Then you can easily read the input in your game over scene (only one is needed)
public class GameOverMenu : MonoBehavior
{
void Start()
{
Debug.Log("You were killed by " + GameOverInput.name);
Application.LoadLevel(GameOverInput.retryLevel);
}
}
And you set this info just before loading the game over scene
if (Collision.collider.tag == "Player")
{
GameOverInput.name = "Baddie";
Application.LoadLevel("GameOver");
}
Another option would be to make something like a singleton LevelManager MonoBehavior and add it to an object named "Level Manager". Use the DontDestroyOnLoad function to make the object persist even when you load another level.
class LevelManager : MonoBehavior
{
static LevelManager _instance;
public string currentLevelName;
public string killedBy;
function Awake ()
{
if (_instance == null)
{
_instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject); // Make sure we never have more than 1 Level Manager.
}
}
LevelManager Instance
{
get
{
if (_instance == null)
{
GameObject levelManagerObject = GameObject.Find("Level Manager");
_instance = levelManagerObject.GetComponent<LevelManager>();
}
return _instance
}
}
}
Then, from the main menu class, you can always access the Level Manager like so:
Debug.Log("Killed by " + LevelManager.Instance.killedBy);
or
LevelManager.Instance.currentLevelName = Application.loadedLevelName;
In a cross platform Xamarin app built with the MvvmCross framework I'm using a ToggleButton Widget in an Android .axml layout. I've bound the Checked property to a View Model property using a converter using the following binding syntax:
Checked MarketBuySellViewModel.Direction, Converter=DirectionBool, ConverterParameter='Sell'
Everything works well. On the iOS side, it appears you can use UIButton as a ToggleButton by using the Selected property. This implies that the following binding should achieve what I want on iOS:
set.Bind (SellButton).For(b => b.Selected).To (vm => vm.MarketBuySellViewModel.Direction).WithConversion("DirectionBool", "Sell");
I don't get any binding errors in the application output but the binding itself doesn't seem to work. Clicking the button doesn't set the Direction property and setting the direction to a different value does not set the Selected property on the UIButton.
Do I need to create a Custom Binding or am I simply setting up the binding incorrectly?
I also tried using a UISegmentedControl to achieve the same effect. Is binding to this control supported at all in MvvmCross? I don't see any reference to it in the source code. Does this mean I need to create custom bindings for it too?
For the UIButton, I don't believe there's any included Selected binding built into MvvmCross. Because of this - and because Selected doesn't have a simple paired event SelectedChanged, then I believe Selected binding should work one-way (from ViewModel to View) but not two-way.
There is a binding for the On of a UISwitch control and that's the control I've seen used most in these situations.
If you wanted to add a custom 2-way binding for Selected then I guess you'd have to do this using the ValueChanged event (but would need to check that is correct).
To do so, you'd just build a target binding something like:
public class MvxUIButtonSelectedTargetBinding : MvxPropertyInfoTargetBinding<UIButton>
{
public MvxUIButtonSelectedTargetBinding(object target, PropertyInfo targetPropertyInfo)
: base(target, targetPropertyInfo)
{
var view = View;
view.ValueChanged += HandleValueChanged;
}
private void HandleValueChanged(object sender, System.EventArgs e)
{
var view = View;
if (view == null)
return;
FireValueChanged(view.Selected);
}
public override MvxBindingMode DefaultMode
{
get { return MvxBindingMode.TwoWay; }
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (isDisposing)
{
var view = View;
if (view != null)
{
view.ValueChanged -= HandleValueChanged;
}
}
}
}
and this could be registered in Setup in protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry) using something like:
registry.RegisterPropertyInfoBindingFactory(typeof(MvxUIButtonSelectedTargetBinding), typeof(UIButton),
"Selected");
Similarly, I don't believe anyone has added a two way UISegmentedControl binding yet - but would happily see one added.
Building a two way UISegmentedControl binding would be quite straight-forward - you'd just have to bind to the pair SelectedSegment and ValueChanged - with code similar to above.
Alternatively, you could switch to using a custom MySegmentedControl which had a nicer Value`ValueChanged` pair which would automatically work without a custom binding - e.g.:
public class MySegmentedControl : UISegmentedControl
{
// add more constructors if required
public int Value
{
get { return base.SelectedSegment; }
set { base.SelectedSegment = value; }
}
}
If any or all of these custom bindings are needed, then the Mvx project is happy to get these bindings added as issues or pull requests along with test/demo UIs in the https://github.com/slodge/MvvmCross-Tutorials/blob/master/ApiExamples/ApiExamples.Touch/Views/FirstView.cs project
Could be helpful to someone else, so i'm sharing my experience. I needed a two way binding for UISegmentedControl.SelectedSegment property to a ViewModel. The one way biding (ViewModel => View) works by default. I couldn't able to properly utilize the solution proposed by Stuart - to subclass the UISegmentedControl. I tried to ensure that the linker does not rip off the new custom control code, but this didn't help me a bit. So a perfectly viable solution is the one with MvxPropertyInfoTargetBinding. Here is the code working ok for me:
public class MvxUISegmentedControlSelectedSegmentTargetBinding : MvxPropertyInfoTargetBinding<UISegmentedControl>
{
public MvxUISegmentedControlSelectedSegmentTargetBinding(object target, PropertyInfo targetPropertyInfo)
: base(target, targetPropertyInfo)
{
this.View.ValueChanged += HandleValueChanged;
}
private void HandleValueChanged(object sender, System.EventArgs e)
{
var view = this.View;
if (view == null)
{
return;
}
FireValueChanged(view.SelectedSegment);
}
public override MvxBindingMode DefaultMode
{
get { return MvxBindingMode.TwoWay; }
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (isDisposing)
{
var view = this.View;
if (view != null)
{
view.ValueChanged -= HandleValueChanged;
}
}
}
}
public class Setup : MvxTouchSetup
{
...
protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
{
registry.RegisterPropertyInfoBindingFactory(typeof(MvxUISegmentedControlSelectedSegmentTargetBinding), typeof(UISegmentedControl), "SelectedSegment");
}
}
I'm new to WCF RIA Services, and have been working with LightSwitch for 4 or so months now.
I created a generic screen to be used for editing lookup tables all over my LightSwitch application, mostly to learn how to create a generic screen that can be used with different entity sets on a dynamic basis.
The screen is pretty simple:
Opened with arguments similar to this:
Application.ShowLookupTypesList("StatusTypes", "StatusTypeId"); which correspond to the entity set for the lookup table in the database.
Here's my WCF RIA service code:
using System.Data.Objects.DataClasses;
using System.Diagnostics;
using System.Reflection;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.ServiceModel.DomainServices.EntityFramework;
using System.ServiceModel.DomainServices.Server;
namespace WCF_RIA_Project
{
public class LookupType
{
[Key]
public int TypeId { get; set; }
public string Name { get; set; }
}
public static class EntityInfo
{
public static Type Type;
public static PropertyInfo Key;
public static PropertyInfo Set;
}
public class WCF_RIA_Service : LinqToEntitiesDomainService<WCSEntities>
{
public IQueryable<LookupType> GetLookupTypesByEntitySet(string EntitySetName, string KeyName)
{
EntityInfo.Set = ObjectContext.GetType().GetProperty(EntitySetName);
EntityInfo.Type = EntityInfo.Set.PropertyType.GetGenericArguments().First();
EntityInfo.Key = EntityInfo.Type.GetProperty(KeyName);
return GetTypes();
}
[Query(IsDefault = true)]
public IQueryable<LookupType> GetTypes()
{
var set = (IEnumerable<EntityObject>)EntityInfo.Set.GetValue(ObjectContext, null);
var types = from e in set
select new LookupType
{
TypeId = (int)EntityInfo.Key.GetValue(e, null),
Name = (string)EntityInfo.Type.GetProperty("Name").GetValue(e, null)
};
return types.AsQueryable();
}
public void InsertLookupType(LookupType lookupType)
{
dynamic e = Activator.CreateInstance(EntityInfo.Type);
EntityInfo.Key.SetValue(e, lookupType.TypeId, null);
e.Name = lookupType.Name;
dynamic set = EntityInfo.Set.GetValue(ObjectContext, null);
set.AddObject(e);
}
public void UpdateLookupType(LookupType currentLookupType)
{
var set = (IEnumerable<EntityObject>)EntityInfo.Set.GetValue(ObjectContext, null);
dynamic modified = set.FirstOrDefault(t => (int)EntityInfo.Key.GetValue(t, null) == currentLookupType.TypeId);
modified.Name = currentLookupType.Name;
}
public void DeleteLookupType(LookupType lookupType)
{
var set = (IEnumerable<EntityObject>)EntityInfo.Set.GetValue(ObjectContext, null);
var e = set.FirstOrDefault(t => (int)EntityInfo.Key.GetValue(t, null) == lookupType.TypeId);
Debug.Assert(e.EntityState != EntityState.Detached, "Entity was in a detached state.");
ObjectContext.ObjectStateManager.ChangeObjectState(e, EntityState.Deleted);
}
}
}
When I add an item to the list from the running screen, save it, then edit it and resave, I receive data conflict "Another user has deleted this record."
I can workaround this by reloading the query after save, but it's awkward.
If I remove, save, then readd and save an item with the same name I get unable to save data, "The context is already tracking a different entity with the same resource Uri."
Both of these problems only affect my generic screen using WCF RIA Services. When I build a ListDetail screen for a specific database entity there are no problems. It seems I'm missing some logic, any ideas?
I've learned that this the wrong approach to using LightSwitch.
There are several behind-the-scenes things this generic screen won't fully emulate and may not be do-able without quite a bit of work. The errors I've received are just one example. LightSwitch's built-in conflict resolution will also fail.
LS's RAD design means just creating a bunch of similar screens is the way to go, with some shared methods. If the actual layout needs changed across many identical screens at once, you can always find & replace the .lsml files if you're careful and make backups first. Note that modifying these files directly isn't supported.
I got that error recently. In my case I create a unique ID in my WCF RIA service, but in my screen behind code I must explicitly set a unique ID when I create the object that will later be passed to the WCF RIA Service insert method (this value will then be overwritten with the unique counter ID in the table of the underlying database).
See the sample code for this project:
http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/157/A-Visual-Studio-LightSwitch-Picture-File-Manager.aspx
I want to create a custom web part that has more than 1 filter web part and that can be connected to Report Viewer Web Part (Integrated Mode) at runtime/design time.
I searched a lot for this, but could not find a way to have single web part that is a provider to more than 1 filters.
Say for example -
My Report accepts 2 parameter Department and Region.
I want to connect both parameters with single web part having two drop down (one for Department and one for Region)
Values from both the drop down should be passed to Department and Region
Report should be rendered in Report Viewer Web Part
Solution Tried so far
Create a web part that adds two custom drop down
Custom drop down class that implements from ITransformableFilterValues
Have 2 methods on the web pat each having ConnectionProvider attribute and return instance of drop down control
Problem:
Even though 2 connection option is shown on my custom filter web part only one can be added.
For example if I connect Filter1(custom web part) to Department then I am unable to connect it to Report Viewer web part again.
My web part have methods like this:
[ConnectionProvider("Departmet", "UniqueIDForDept", AllowsMultipleConnections = true)]
public ITransformableFilterValues ReturnCity()
{
return dropDownDepartment; // It implemets ITransformableFilterValues
}
[ConnectionProvider("Region", "UniqueIDForRegion", AllowsMultipleConnections = true)]
public ITransformableFilterValues ReturnMyRegionB()
{
return dropDownRegion; //It implemets ITransformableFilterValues
}
I did something similar. This might help point you in the right direction. I used data in a form library to create a detailed report. I used reporting services and connected to sharepoint using web services. http://server/_vti_bin/Lists.asmx. The report parameter I used was the item ID or GUID. Then I configured my report viewer. On the form library I used JavaScript to override the context menu to add "View Report". On the report page I used a Query String filter to grab the item ID out of the url.
Not sure if you were able to fix your problem..
Actually I tried with AllowsMultipleConnections = true and it worked fine:
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using aspnetwebparts = System.Web.UI.WebControls.WebParts;
using Microsoft.Office.Server.Utilities;
using wsswebparts = Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Portal.WebControls;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using Microsoft.SharePoint.Utilities;
namespace FromMultiSource
{
[Guid("a0d068dd-9475-4055-a219-88513e173502")]
public class MultiSource : aspnetwebparts.WebPart
{
List<wsswebparts.IFilterValues> providers = new List<wsswebparts.IFilterValues>();
public MultiSource()
{
}
[aspnetwebparts.ConnectionConsumer("Multiple Source Consumer", "IFilterValues", AllowsMultipleConnections = true)]
public void SetConnectionInterface(wsswebparts.IFilterValues provider)
{
this.providers.Add(provider);
if (provider != null)
{
List<wsswebparts.ConsumerParameter> l = new List<wsswebparts.ConsumerParameter>();
l.Add (new wsswebparts.ConsumerParameter ("Value", wsswebparts.ConsumerParameterCapabilities.SupportsMultipleValues | Microsoft.SharePoint.WebPartPages.ConsumerParameterCapabilities.SupportsAllValue));
provider.SetConsumerParameters(new ReadOnlyCollection<wsswebparts.ConsumerParameter>(l));
}
}
protected override void CreateChildControls()
{
base.CreateChildControls();
// TODO: add custom rendering code here.
// Label label = new Label();
// label.Text = "Hello World";
// this.Controls.Add(label);
}
protected override void RenderContents(HtmlTextWriter writer)
{
base.RenderContents(writer);
this.EnsureChildControls();
foreach (wsswebparts.IFilterValues provider in this.providers)
{
if (provider != null)
{
string prop = provider.ParameterName;
ReadOnlyCollection<string> values = provider.ParameterValues;
if (prop != null && values != null)
{
writer.Write("<div>" + SPEncode.HtmlEncode(prop) + ":</div>");
foreach (string v in values)
{
if (v == null)
{
writer.Write("<div> <i>"(empty)"/null</i></div>");
}
else if (v.Length == 0)
{
writer.Write("<div> <i>empty string</i></div>");
}
else
{
writer.Write("<div> " + v + "</div>");
}
}
}
else
{
writer.Write("<div>No filter specified (all).</div>");
}
}
else
{
writer.Write("<div>Not connected.</div>");
}
writer.Write("<hr>");
}
}
}
}