Controlling instantiated GameObject using kinect - c#

I tried some scripts to control an object form the hierarchy and it worked great,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Windows.Kinect;
public class DetectJoint : MonoBehaviour {
public GameObject BodySrcManager;
public JointType TrackedJoint;
private BodySourceManager bodyManager;
private Body[] bodies = null;
public float multiplier = 10f;
void Start()
{
if (BodySrcManager == null)
{
Debug.Log("Assign Game Objects with body source manager");
}
else
{
bodyManager = BodySrcManager.GetComponent<BodySourceManager>();
}
}
void Update()
{
if (bodyManager == null)
{
Debug.Log("bodyManager is Null");
return;
}
bodies = bodyManager.GetData();
if (bodies == null)
{
Debug.Log("bodies is Null");
return;
}
foreach (var body in bodies)
{
if (body == null)
{
continue;
}
if (body.IsTracked)
{
var pos = body.Joints[TrackedJoint].Position;
gameObject.transform.position = new Vector3(pos.X * multiplier, pos.Y * multiplier);
}
}
}
}
and a script named BodySourceManager which is
using UnityEngine;
using System.Collections;
using Windows.Kinect;
public class BodySourceManager : MonoBehaviour
{
private KinectSensor _Sensor;
private BodyFrameReader _Reader;
private Body[] _Data = null;
public Body[] GetData()
{
return _Data;
}
void Start ()
{
_Sensor = KinectSensor.GetDefault();
if (_Sensor != null)
{
_Reader = _Sensor.BodyFrameSource.OpenReader();
if (!_Sensor.IsOpen)
{
_Sensor.Open();
}
}
}
void Update ()
{
if (_Reader != null)
{
var frame = _Reader.AcquireLatestFrame();
if (frame != null)
{
if (_Data == null)
{
_Data = new Body[_Sensor.BodyFrameSource.BodyCount];
}
frame.GetAndRefreshBodyData(_Data);
frame.Dispose();
frame = null;
}
}
}
void OnApplicationQuit()
{
if (_Reader != null)
{
_Reader.Dispose();
_Reader = null;
}
if (_Sensor != null)
{
if (_Sensor.IsOpen)
{
_Sensor.Close();
}
_Sensor = null;
}
}
}
the problem is i couldn't control an instantiated one from Prefabs
any ideas how to do it ?

Related

Why is the value of the Image property of the PictureBox element null?

I have the next class:
using System.Drawing;
using System.Windows.Forms;
namespace course_project
{
internal class Pike<T> : Fish
{
Brush brush = new SolidBrush(Color.Green);
public PictureBox aquarium = new AquariumForm().aquarium_picturebox;
public Pike(T data) {
Data = data;
Draw((int[])(object)data);
}
public T Data { get; set; }
public Pike<T> Next { get; set; }
protected override void Draw(int[] coordinates)
{
Graphics graphics = Graphics.FromImage(aquarium.Image);
graphics.FillEllipse(brush, coordinates[0], coordinates[1], 40, 40);
aquarium.Refresh();
}
}
}
Linked List:
using System.Collections;
using System.Collections.Generic;
namespace course_project
{
internal class PikeFlock<T> : IEnumerable<T>
{
Pike<T> head;
Pike<T> tail;
int count;
public void Add(T data)
{
Pike<T> pike = new Pike<T>(data);
if (head == null)
head = pike;
else
tail.Next = pike;
tail = pike;
count++;
}
public bool Remove(T data)
{
Pike<T> current = head;
Pike<T> previous = null;
while (current != null)
{
if (current.Data.Equals(data))
{
if (previous != null)
{
previous.Next = current.Next;
if (current.Next == null)
{
tail = previous;
}
}
else
{
head = head.Next;
if (head == null)
tail = null;
}
count--;
return true;
}
previous = current;
current = current.Next;
}
return false;
}
public int Count { get { return count; } }
public bool isEmpty { get { return count == 0; } }
public void Clear()
{
head = null;
tail = null;
count = 0;
}
public bool Contains(T data)
{
Pike<T> current = head;
while (current != null)
{
if (current.Data.Equals(data))
return true;
current = current.Next;
}
return false;
}
public void AppendFirst(T data)
{
Pike<T> pike = new Pike<T>(data);
pike.Next = head;
head = pike;
if (count == 0)
{
tail = head;
}
count++;
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)this).GetEnumerator();
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
Pike<T> current = head;
while (current != null)
{
yield return current.Data;
current = current.Next;
}
}
}
}
Button click event:
private void add_pike_button_Click(object sender, EventArgs e)
{
PikeFlock<int[]> pikeFlock = new PikeFlock<int[]>();
int[] coords = { 1, 2 };
pikeFlock.Add(coords);
}
Form1_Load:
private void Form1_Load(object sender, EventArgs e)
{
Bitmap bitmap = new Bitmap(aquarium_picturebox.Width, aquarium_picturebox.Height);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.Clear(Color.Blue);
aquarium_picturebox.Image = bitmap;
aquarium_picturebox.Refresh();
}
But when you click the button an ArgumentNullException (System.ArgumentNullException: "The value cannot be undefined.
Parameter name: image".) is thrown because the Image property of the PictureBox element is empty for some reason.
How can it be solved? Please don't throw tomatoes, I just started to learn C# :)

Destroy element when craft is complete Unity 3d c#

I have been making a game on Unity following the tutorial by Sykoo, this one.
And I have a problem with the crafting system, when I want the items to be destroyed when the craft is made, but I dont know how to do it. Can someone help me please?
here is the craft item script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class CraftableItem : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public GameObject thisItem;
public int requiredItems;
public GameObject[] item;
private bool hovered;
private GameObject player;
private GameObject itemManager;
public void Start()
{
player = GameObject.FindWithTag("Player");
itemManager = GameObject.FindWithTag("ItemManager");
}
public void Update()
{
if (hovered == true)
{
if(Input.GetMouseButtonDown(0))
{
CheckForRequiredItems();
}
}
}
public void CheckForRequiredItems()
{
int itemsInManager = itemManager.transform.childCount;
if (itemsInManager > 0)
{
int itemsFound = 0;
for(int i = 0; i < itemsInManager; i++)
{
for (int z = 0; z < requiredItems; z++)
{
if (itemManager.transform.GetChild(i).GetComponent<Item>().type == item[z].GetComponent<Item>().type)
{
itemsFound++;
break;
}
}
}
if (itemsFound >= requiredItems)
{
GameObject spawndedItem = Instantiate(thisItem, /* pos,*/player.transform.position, Quaternion.identity);
}
}
}
public void OnPointerEnter(PointerEventData eventData)
{
hovered = true;
}
public void OnPointerExit(PointerEventData eventData)
{
hovered = false;
}
}
the inventory script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
//Instructions *correct
public GameObject inventory;
public GameObject slotHolder;
public GameObject itemManager;
private bool inventoryEnabled;
private int slots;
private Transform[] slot;
private GameObject itemPickedUp;
private bool itemAdded;
private GameObject player;
//Start *correct
public void Start()
{
// slots being detected
inventoryEnabled = true;
slots = slotHolder.transform.childCount;
slot = new Transform[slots];
DetectInventorySlots();
}
// Inventory GUI
public void Update()
{
if (Input.GetKeyDown(KeyCode.I))
{
inventoryEnabled = !inventoryEnabled;
}
if(inventoryEnabled)
{
inventory.GetComponent<Canvas>().enabled = true;
Time.timeScale = 0;
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
}
else
{
inventory.GetComponent<Canvas>().enabled = false;
Time.timeScale = 1;
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
}
// Inventory Pick *correct
public void OnTriggerStay(Collider other)
{
if (other.tag == "Item")
{
itemPickedUp = other.gameObject;
AddItem(itemPickedUp);
}
}
public void OnTriggerExit(Collider other)
{
if (other.tag == "Item")
{
itemAdded = false;
}
}
// Add Item *correct
public void AddItem(GameObject item)
{
for (int i = 0; i < slots; i++)
{
if (slot[i].GetComponent<Slot>().empty && itemAdded == false)
{
slot[i].GetComponent<Slot>().item = itemPickedUp;
slot[i].GetComponent<Slot>().itemIcon = itemPickedUp.GetComponent<Item>().icon;
//attachs the item to the hand *correct
item.transform.parent = itemManager.transform;
item.transform.position = itemManager.transform.position;
//equipar arma
item.transform.localPosition = item.GetComponent<Item>().position;
item.transform.localEulerAngles = item.GetComponent<Item>().rotation;
item.transform.localScale = item.GetComponent<Item>().scale;
Destroy(item.GetComponent<Rigidbody>());
itemAdded = true;
item.SetActive(false);
}
}
}
// Detect slots *correct
public void DetectInventorySlots()
{
for (int i = 0; i < slots; i++)
{
slot[i] = slotHolder.transform.GetChild(i);
}
inventory.GetComponent<Canvas>().enabled = true;
inventoryEnabled = false;
}
}
and the slot script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems; // Required when using Event data.
using UnityEngine.UI;
public class Slot : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler
{
//instructions *correct
private bool hovered;
public bool empty;
public Image image;
public GameObject item;
public Texture itemIcon;
private GameObject player;
//Update *correct
void Start()
{
player = GameObject.FindWithTag("Player");
hovered = false;
image.enabled = false;
}
void Update()
{
if (item)
{
empty = false;
itemIcon = item.GetComponent<Item>().icon;
this.GetComponent<RawImage>().texture = itemIcon;
} else {
empty = true;
this.GetComponent<RawImage>().texture = null;
}
}
//Pointer *correct
public void OnPointerEnter(PointerEventData eventData)
{
hovered = true;
}
public void OnPointerExit(PointerEventData eventData)
{
hovered = false;
}
public void OnPointerClick(PointerEventData eventData)
{
if(item)
{
Item thisItem = item.GetComponent<Item>();
//water
if(thisItem.type == "Water")
{
player.GetComponent<Player>().Drink(thisItem.decreaseRate);
Destroy(item);
}
//food
if (thisItem.type == "Food")
{
player.GetComponent<Player>().Eat(thisItem.decreaseRate);
Destroy(item);
}
//weapon
if(thisItem.type == "Weapon" && player.GetComponent<Player>().weaponEquipped == false)
{
thisItem.equipped = true;
item.SetActive(true);
imageEnabled();
}
if (thisItem.type == "Weapon" && player.GetComponent<Player>().weaponEquipped == true)
{
thisItem.equipped = false;
item.SetActive(false);
image.enabled = false;
player.GetComponent<Player>().weaponEquipped = false;
}
}
}
public void imageEnabled()
{
image.enabled = !image.enabled;
}
public class StackItem
{
public Item item = new Item();
public int amount = 1;
}
}
but i think you will only need the craft system script. Hope someone can help me.
Seems like your craft is completed on this instruction:
if (itemsFound >= requiredItems)
{
GameObject spawndedItem = Instantiate(thisItem, /* pos,*/player.transform.position, Quaternion.identity);
}
Next to GameObject spawndedItem... string you can specify your element deletion code, as an example:
if (itemsFound >= requiredItems)
{
GameObject spawndedItem = Instantiate(thisItem, /* pos,*/player.transform.position, Quaternion.identity);
Destroy(GameObject.Find("ObjectThatYouWantToDestroyName"));
}

Dialogue does not begin with the first sentence and it starts before I press key to begin dialogue in Unity

I am working on a dialogue and questing system for a 2d game I am working on. I am attempting to have multiple NPCs that will give different quests with different dialogue that is unique to each quest. I attempt to trigger my dialogue whenever a player presses the E key. Currently my game displays the dialogue whenever the player becomes in contact with the NPCs collider. The dialogue also begins with the second sentence of the dialogue array. Additionally, once the player has interacted with multiple npcs, the dialogue for all npc becomes the dialogue of the last npc that was interacted with.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class QuestGiver : NPC
{
public bool AssignedQuest { get; set; }
public bool Helped { get; set; }
[SerializeField]
private GameObject quests;
[SerializeField]
private string questType;
private Quest Quest { get; set; }
public CharacterController2D player;
public GameObject questWindow;
public Text titleText;
public Text descriptionText;
public Text expRewardText;
public Text currencyRewardText;
private void Start()
{
}
public override void Interact()
{
if (!AssignedQuest && !Helped)
{
DialogueManager.Instance.AddNewDialogue(dialogue, name);
AssignQuest();
}
else if (AssignedQuest && !Helped)
{
CheckQuest();
}
else
{
DialogueManager.Instance.AddNewDialogue(Quest.completedDialogue, name);
}
}
void AssignQuest()
{
AssignedQuest = true;
Quest = (Quest)quests.AddComponent(Type.GetType(questType));
}
void CheckQuest()
{
if (Quest.Completed)
{
Quest.GiveReward();
Helped = true;
AssignedQuest = false;
DialogueManager.Instance.AddNewDialogue(Quest.rewardDialogue, name);
Destroy(quests.GetComponent(Type.GetType(questType)));
}
else
{
DialogueManager.Instance.AddNewDialogue(Quest.inProgressDialogue, name);
}
}
public void OpenQuestWindow()
{
questWindow.SetActive(true);
titleText.text = Quest.QuestName;
descriptionText.text = Quest.Description;
expRewardText.text = Quest.ExpRewards.ToString();
currencyRewardText.text = Quest.CurrencyReward.ToString();
}
public void AcceptQuest()
{
questWindow.SetActive(false);
Quest.Completed = false;
player.questsList.Add(Quest);
}
}
This is the Quest script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
[System.Serializable]
public class Quest : MonoBehaviour
{
public List<QuestGoal> Goals { get; set; } = new List<QuestGoal>();
public string[] inProgressDialogue, rewardDialogue, completedDialogue;
public string QuestName { get; set; }
public string Description { get; set; }
public int ExpRewards { get; set; }
public int CurrencyReward { get; set; }
public Item ItemReward { get; set; }
public bool Completed { get; set; }
public void CheckGoals()
{
Completed = Goals.All(q => q.Completed);
if (Completed) GiveReward();
}
public void GiveReward()
{
if (ItemReward != null)
Inventory.inventory.Add(ItemReward);
}
This is the NPC:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPC : Interactable
{
public string[] dialogue;
public string name;
public override void Interact()
{
base.Interact();
DialogueManager.Instance.AddNewDialogue(dialogue, name);
Debug.Log("Interacting with " + name);
}
public void TriggerDialogue()
{
FindObjectOfType<DialogueManager>().AddNewDialogue(dialogue, name);
}
}
This is my dialogue script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class DialogueManager : MonoBehaviour
{
#region
public static DialogueManager Instance { get; set; }
public GameObject dialoguePanel;
private void Awake()
{
dialoguePanel.SetActive(false);
if (Instance != null && Instance != this)
{
Debug.Log(Instance);
Destroy(Instance);
}
else
{
Instance = this;
}
}
#endregion
public Text nameText, dialogueText;
public Button continueButton;
public Animator animator;
public string npcName;
int dialogueIndex;
public List<string> dialogueLines = new List<string>();
void Start()
{
}
public void AddNewDialogue(string[] lines, string npcName)
{
dialogueIndex = 0;
dialogueLines = new List<string>();
foreach (string line in lines)
{
dialogueLines.Add(line);
}
this.npcName = npcName;
Debug.Log(dialogueLines.Count);
Debug.Log(npcName);
CreateDialogue();
}
public void CreateDialogue()
{
nameText.text = npcName;
dialogueText.text = dialogueLines[dialogueIndex];
dialoguePanel.SetActive(true);
animator.SetBool("IsOpen", true);
ContinueDialogue();
}
public void ContinueDialogue()
{
if (dialogueIndex < dialogueLines.Count - 1)
{
dialogueIndex++;
dialogueText.text = dialogueLines[dialogueIndex];
}
else
{
EndDialogue();
}
StopAllCoroutines();
StartCoroutine(TypeSentence(dialogueText.text));
}
IEnumerator TypeSentence (string sentence)
{
dialogueText.text = "";
foreach (char letter in sentence.ToCharArray())
{
dialogueText.text += letter;
yield return null;
}
}
void EndDialogue()
{
animator.SetBool("IsOpen", false);
Debug.Log("End of conversation");
}
}
This is part of the Player controller:
using UnityEngine;
using UnityEngine.Events;
using Spine.Unity;
using UnityEngine.EventSystems;
using System.Collections.Generic;
public class CharacterController2D : MonoBehaviour
{
private GameObject triggeringNpc;
public GameObject npcText;
public List<Quest> questsList = new List<Quest>();
private bool triggering;
private void OnTriggerEnter2D(Collider2D other)
{
Interactable interactable = other.gameObject.GetComponent<Interactable>();
if (interactable != null)
{
interactable.Interact();
}
if (other.tag == "NPC")
{
triggering = true;
triggeringNpc = other.gameObject;
}
if (other.tag == "QuestGiver")
{
triggering = true;
triggeringNpc = other.gameObject;
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.tag == "NPC")
{
triggering = false;
triggeringNpc = null;
}
if (other.tag == "QuestGiver")
{
triggering = false;
triggeringNpc = null;
}
}
private void Update()
{
if (triggering)
{
npcText.SetActive(true);
if (Input.GetKeyDown(KeyCode.E))
{
FindObjectOfType<QuestGiver>().TriggerDialogue();
}
}
else
{
npcText.SetActive(false);
}
}
}
Thank you in advance, sorry for the long post.
Dialogue starting on the second line:
In the CreateDialogue() method, at the end you are calling ContinueDialogue(). So you create dialogue and then immediately tell it to go to the next line. I think instead you might want to be calling StartCoroutine(TypeSentence(dialogueText.text)) at the end of CreateDialogue().
Interaction issues:
You're calling Interact() at the beginning of OnTriggerEnter2D by doing interactable.Interact(). Here, erase all the code inside your OnTriggerEnter2D method and replace it with this.
if (other.tag == "NPC" || other.tag == "QuestGiver") {
triggering = true;
triggeringNpc = other.gameObject;
} else if (interactable != null) { interactable.Interact(); }

Why am I getting #endregoin diretive expected error

I am getting #endregoin diretive expected in this class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MobileInput : MonoBehaviour {
private const float DEADZONE = 100.0f;
public static MobileInput Instance { set; get; }
private bool tap, swipeLeft, swipeLeft, swipeRight, swipeUp, swipeUp, swipeDown;
private Vector2 swipeDelta, startTouch;
public bool Tap { get { return tap; } }
public Vector2 SwipeDelta { get { return swipeDelta; } }
public Vector2 SwipeLeft { get { return swipeLeft; } }
public Vector2 SwipeRight { get { return swipeRight; } }
public Vector2 SwipeUp { get { return swipeUp; } }
public Vector2 SwipeDown { get { return swipeDown; } }
private void Awake()
{
Instance = this;
}
private void Update()
{
//reseting all the bool
tap = swipeLeft = swipeRight = swipeDown = swipeUp = false;
//lets check input
#region Standalone Inputs
if (Input.GetMouseButtonDown(0))
{
tap = true;
startTouch = Input.mousePosition;
}
else if (Input.GetMouseBottonUp(0))
{
startTouch = swipeDelta = Vector2.zero;
}
#region Mobile Inputs
if (Input.touches.Length != 0)
{
if (Input.touches[0].phase == TouchPhase.Began)
{
tap = true;
startTouch = Input.mousePosition;
}
else if (Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled)
{
startTouch = swipeDelta = Vector2.zero;
}
}
#endregion
//Calculate
swipeDelta = Vector2.zero;
if (startTouch != Vector2.zero)
{
//let's check
if (Input.touches.Length != 0)
{
swipeDelta = Input.touches[0].position - startTouch;
}
//lets check standalone
else if (Input.GetMouseButton(0))
{
swipeDelta = (Vector2)Input.mousePosition - startTouch;
}
}
//Check dead zone
if (swipeDelta.magnitude > DEADZONE)
{
// this is a confirmed swip
float x = swipeDelta.x;
float y = swipeDelta.y;
if (Mathf.Abs(x) > Mathf.Abs(y))
{
//left
if (x < 0)
swipeLeft = true;
else
swipeRight = true;
}
else
{
//up or down
if (y < 0)
swipeDown = true;
else
swipeUp = true;
}
startTouch = swipeDelta = Vector2.zero;
}
}
}
Your #region Standalone Inputs is missing an #endregion further down in your code.

On Property change took too much time and finally crash application

I am working on WPF MVVM Application.
I have a view (Employee) shown inside Main Region
this view (Employee) contain scoped regions within it where I show/display Employee details views. Its working fine till this place New, display update and delete
But I am facing strange problem with New Operation
If I create view for first time and click on new , Object got initialized my Data Object CurrentEmployee.
But If I load some previous data its been shown properly and then I click on New, my Data Object CurrentEmployee took too much time and finaly crash. the problem so far traced is in OnPropertyChange
Thanks any sort of help/suggestion is highly appriciated
whole code of view model
[Export(typeof(ITB_EMPLOYEEViewModel))]
public class TB_EMPLOYEEViewModel : ViewModelBase, ITB_EMPLOYEEViewModel
{
private TB_EMPLOYEE _currentTB_EMPLOYEE;
IRegionManager RefRegionManager;
IEventAggregator _eventAggregator;
[ImportingConstructor]
public TB_EMPLOYEEViewModel(IRegionManager regionManager, IEventAggregator eventAggregator)
: base(regionManager, eventAggregator)
{
RefRegionManager = regionManager;
HeaderInfo = "TB_EMPLOYEE";
_eventAggregator = eventAggregator;
OpenImageDialog = new DelegateCommand(OpenDialog, CanOpenDialog);
//CurrentTB_EMPLOYEE = new TB_EMPLOYEE();
//empHistoryVM = new TB_EMPLOYEE_HISTORYViewModel();
//UnLoadChild();
//LoadChild();
New();
}
private void LoadChild()
{
IRegionManager regionManager = ServiceLocator.Current.GetInstance<IRegionManager>();
if (regionManager.Regions.ContainsRegionWithName(RegionNames.EmployeeDetail))
{
IRegion region = regionManager.Regions[RegionNames.EmployeeDetail];
var empHistory = ServiceLocator.Current.GetInstance<uTB_EMPLOYEE_HISTORYView>();
if (region.GetView("EmployeeHistory") == null)// .Views.OfType<uTB_EMPLOYEE_HISTORYView>().SingleOrDefault() == null)
{
region.Add(empHistory, "EmployeeHistory");
}
if (CurrentTB_EMPLOYEE != null && CurrentTB_EMPLOYEE.ID!=0)
{
empHistoryVM = new TB_EMPLOYEE_HISTORYViewModel(CurrentTB_EMPLOYEE.ID);
}
else
{
empHistoryVM = new TB_EMPLOYEE_HISTORYViewModel();
}
empHistory.ViewModel = empHistoryVM;
region.Activate(region.GetView("EmployeeHistory"));
}
}
private void UnLoadChild()
{
IRegionManager regionManager = ServiceLocator.Current.GetInstance<IRegionManager>();
if (regionManager.Regions.ContainsRegionWithName(RegionNames.EmployeeDetail))
{
IRegion region = regionManager.Regions[RegionNames.EmployeeDetail];
if (region.GetView("EmployeeHistory") != null)// .Views.OfType<uTB_EMPLOYEE_HISTORYView>().SingleOrDefault() == null)
{
region.Remove(region.GetView("EmployeeHistory"));
}
}
}
#region DetailUserControls ViewModels
private TB_EMPLOYEE_HISTORYViewModel empHistoryVM;
#endregion DetailUserControls ViewModels
#region Commands
public DelegateCommand OpenImageDialog { get; set; }
private bool CanOpenDialog() { return true; }
public void OpenDialog()
{
using (OpenFileDialog objOpenFile = new OpenFileDialog())
{
if (objOpenFile.ShowDialog() == DialogResult.OK)
{
_currentTB_EMPLOYEE.PHOTO = Utility.ConvertImageToByte(objOpenFile.FileName);
CurrentEmployeeImage = Utility.ConvertByteToImage(_currentTB_EMPLOYEE.PHOTO);
}
}
}
public override void ShowSelectedRow()
{
if (RefRegionManager.Regions[RegionNames.MainRegion].Views.OfType<uTB_EMPLOYEEView>().SingleOrDefault() == null)
{
RefRegionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(uTB_EMPLOYEEView));
}
RefRegionManager.RequestNavigate(RegionNames.MainRegion, "uTB_EMPLOYEEView");
UnLoadChild();
LoadChild();
}
public override void RegisterCommands()
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault() != null)
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault().ToString() == "WPFApp.View.uTB_EMPLOYEEView")
{
GlobalCommands.ShowAllCommand.RegisterCommand(ShowAllCommand);
GlobalCommands.SaveCommand.RegisterCommand(SaveCommand);
GlobalCommands.NewCommand.RegisterCommand(NewCommand);
GlobalCommands.DeleteCommand.RegisterCommand(DeleteCommand);
GlobalCommands.CloseCommand.RegisterCommand(CloseCommand);
}
}
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault() != null)
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault().ToString() == "WPFApp.ListView.uListTB_EMPLOYEE")
{
GlobalCommands.CloseCommand.RegisterCommand(CloseCommand);
GlobalCommands.SearchCommand.RegisterCommand(SearchCommand);
GlobalCommands.PrintCommand.RegisterCommand(PrintCommand);
GlobalCommands.ExportToExcelCommand.RegisterCommand(ExportToExcelCommand);
GlobalCommands.ExportToWordCommand.RegisterCommand(ExportToWordCommand);
GlobalCommands.ExportToPDFCommand.RegisterCommand(ExportToPDFCommand);
}
}
}
public override bool CanShowAll()
{
return IsActive;
}
public override void ShowAll()
{
HeaderInfo = "TB_EMPLOYEE List";
if (RefRegionManager.Regions[RegionNames.MainRegion].Views.OfType<uListTB_EMPLOYEE>().SingleOrDefault() == null)
{
RefRegionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(uListTB_EMPLOYEE));
}
RefRegionManager.RequestNavigate(RegionNames.MainRegion, "uListTB_EMPLOYEE");
UpdateListFromDB();
}
public override void UpdateListFromDB()
{
using (DBMain objDBMain = new DBMain())
{
TB_EMPLOYEEList = objDBMain.EntTB_EMPLOYEE.ToList<TB_EMPLOYEE>();
}
}
public override void New()
{
this.CurrentTB_EMPLOYEE = new TB_EMPLOYEE();
UnLoadChild();
LoadChild();
}
public override void Close()
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault() != null)
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault().ToString() == "WPFApp.View.uTB_EMPLOYEEView")
{
RefRegionManager.Regions[RegionNames.MainRegion].Remove(RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault());
UnLoadChild();
}
}
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault() != null)
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault().ToString() == "WPFApp.ListView.uListTB_EMPLOYEE")
{
RefRegionManager.Regions[RegionNames.MainRegion].Remove(RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault());
}
}
}
public override void Delete()
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault() != null ||
RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault() != null)
{
if (CurrentTB_EMPLOYEE != null)
{
ConfirmationDialog confirmationMessage = new ConfirmationDialog("Do You want to Delete this Record of [TB_EMPLOYEE]", "Confirmation Dialog Box");
confirmationMessage.AllowsTransparency = true;
DoubleAnimation animFadeIn = new DoubleAnimation();
animFadeIn.From = 0;
animFadeIn.To = 1;
animFadeIn.Duration = new Duration(TimeSpan.FromSeconds(1));
confirmationMessage.BeginAnimation(Window.OpacityProperty, animFadeIn);
confirmationMessage.ShowDialog();
if (confirmationMessage.DialogValue)
{
if (CurrentTB_EMPLOYEE.ID != 0)
{
using (DBMain objDBMain = new DBMain())
{
objDBMain.Entry<TB_EMPLOYEE>(CurrentTB_EMPLOYEE).State = EntityState.Deleted;
objDBMain.SaveChanges();
OnPropertyChanged("CurrentTB_EMPLOYEE");
CurrentTB_EMPLOYEE = null;
}
}
else
{
CurrentTB_EMPLOYEE = null;
}
UpdateListFromDB();
}
}
}
}
public override bool CanSave()
{
return IsActive;
}
public override void Save()
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault() != null ||
RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault() != null)
{
if (CurrentTB_EMPLOYEE != null)
{
using (DBMain objDBMain = new DBMain())
{
objDBMain.Entry<TB_EMPLOYEE>(CurrentTB_EMPLOYEE).State = CurrentTB_EMPLOYEE.ID == 0 ? EntityState.Added : EntityState.Modified;
foreach (TB_EMPLOYEE_HISTORY obj in empHistoryVM.TB_EMPLOYEE_HISTORYList)
{
objDBMain.Entry<TB_EMPLOYEE_HISTORY>(obj).State = EntityState.Added;
CurrentTB_EMPLOYEE.TB_EMPLOYEE_HISTORYList.Add(obj);
objDBMain.SaveChanges();
}
}
UpdateListFromDB();
}
}
}
#endregion Commands
#region Properties
private ImageSource _CurrentEmployeeImage;
public ImageSource CurrentEmployeeImage { get { return _CurrentEmployeeImage; } private set { _CurrentEmployeeImage = value; OnPropertyChanged("CurrentEmployeeImage"); } }//OnPropertyChanged("CurrentTB_EMPLOYEE");
public string CurrentEmployeeImagePath { get; set; }
private List<TB_EMPLOYEE> _TB_EMPLOYEEList;
public List<TB_EMPLOYEE> TB_EMPLOYEEList
{
get { return _TB_EMPLOYEEList; }
set
{
_TB_EMPLOYEEList = value;
RaisePropertyChanged();
}
}
public TB_EMPLOYEE CurrentTB_EMPLOYEE
{
get { return _currentTB_EMPLOYEE; }
set
{
_currentTB_EMPLOYEE = value;
if (_currentTB_EMPLOYEE != null && _currentTB_EMPLOYEE.PHOTO != null)
{ CurrentEmployeeImage = Utility.ConvertByteToImage(_currentTB_EMPLOYEE.PHOTO); }
//OnPropertyChanged("CurrentTB_EMPLOYEE");
RaisePropertyChanged();
}
}
private IList<TB_SETUP_RELIGION> _listRELIGION;
public IList<TB_SETUP_RELIGION> listRELIGION
{
get
{
using (DBMain objDBMain = new DBMain())
{
_listRELIGION = objDBMain.EntTB_SETUP_RELIGION.ToList();
}
return _listRELIGION;
}
}
private IList<string> _listTitles;
public IList<string> listTitles
{
get
{
if (_listTitles == null)
{
_listTitles = new List<string>();
_listTitles.Add("Mr");
_listTitles.Add("Miss");
_listTitles.Add("Mrs");
//_listTitles.Add("Mr");
}
return _listTitles;
}
}
private IList<TB_SETUP_GENDER> _listGENDER;
public IList<TB_SETUP_GENDER> listGENDER
{
get
{
using (DBMain objDBMain = new DBMain())
{
_listGENDER = objDBMain.EntTB_SETUP_GENDER.ToList();
}
return _listGENDER;
}
}
#endregion Properties
#region FormNavigation
private bool isActive;
public override bool IsActive
{
get
{
return this.isActive;
}
set
{
isActive = value;
OnIsActiveChanged();
}
}
protected virtual void OnIsActiveChanged()
{
if (IsActive)
{
_eventAggregator.GetEvent<SubscribeToEvents>().Publish(new Dictionary<string, string>() { { "View", "TB_EMPLOYEE" }, { "FileName", #"Subscribtion to Events" } });
}
else
{
_eventAggregator.GetEvent<UnSubscribeToEvents>().Publish(new Dictionary<string, string>() { { "View", "TB_EMPLOYEE" }, { "FileName", #"UnSubscribtion to Events" } });
}
UnRegisterCommands();
RegisterCommands();
}
public override bool IsNavigationTarget(NavigationContext navigationContext)
{
this.isActive = true;
return this.isActive;
}
public override void OnNavigatedFrom(NavigationContext navigationContext)
{
UnRegisterCommands();
this.isActive = false;
}
public override void OnNavigatedTo(NavigationContext navigationContext)
{
HeaderInfo = "TB_EMPLOYEE";
this.isActive = true;
RegisterCommands();
}
#endregion FormNavigation
}
Finally solve the problem. I was using single Object CurrentTB_EMPLOYEE as current data for my form and ActiveData Item of another List view. this view model handle both form and list views. I just remove CurrentTB_EMPLOYEE from ActiveData Item to my list view and bind them through another object.. when CurrentTB_EMPLOYEE become responsible only for form its start working properly. Thanks every one for your precious time.

Categories