I set up three models. I'm not sure if I did it the best way, but it's the way I could understand it easily. I invoke the DepartmentProfile class. The first user found is not a manager so it goes into the else statement and successfully fills in the AD_UserProfile and adds it to the DepartmentProfile class.
The second user is the department manager so it goes into the if statement and errors out on the very first line with object not set to instance of object. What am I missing? Did I not set up the models correctly?
When it errors out
public class AD_UserProfile
{
public string distinguishedName { get; set; }
public string email { get; set; }
public string manager { get; set; }
public string name { get; set; }
public string userPrincipalName { get; set; } // Useful if we need to allow a user to 'log on' as a different user.
public string userName { get; set; }
}
public class AD_ManagerProfile
{
public string distinguishedName { get; set; }
public string email { get; set; }
public string manager { get; set; }
public string name { get; set; }
public string userPrincipalName { get; set; } // Useful if we need to allow a user to 'log on' as a different user.
public string userName { get; set; }
}
public class AD_DepartmentProfile
{
public AD_DepartmentProfile()
{
this.AD_UserProfile = new HashSet<AD_UserProfile>();
}
public string name { get; set; }
public virtual AD_ManagerProfile AD_ManagerProfile { get; set; }
public virtual ICollection<AD_UserProfile> AD_UserProfile { get; set; }
}
Here is the invocation of the classes:
public void GetDepartmentInfo(string department, string owner = "jeremy")
{
DirectoryEntry de = new DirectoryEntry("LDAP://server.server.com");
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = ("(&(objectCategory=person)(objectClass=User)(department=" + department + "))");
ds.SearchScope = SearchScope.Subtree;
AD_DepartmentProfile dp = new AD_DepartmentProfile();
dp.name = department; // assign department name
foreach (SearchResult temp in ds.FindAll())
{
if (owner == temp.Properties["sAMAccountName"][0].ToString())
{
//Current user is manager of department
dp.AD_ManagerProfile.distinguishedName = temp.Properties["distinguishedName"][0].ToString(); // This line errors out with instance not set to object error.
dp.AD_ManagerProfile.email = temp.Properties["mail"][0].ToString();
dp.AD_ManagerProfile.manager = temp.Properties["manager"][0].ToString();
dp.AD_ManagerProfile.name = temp.Properties["name"][0].ToString();
dp.AD_ManagerProfile.userPrincipalName = temp.Properties["userPrincipalName"][0].ToString();
dp.AD_ManagerProfile.userName = temp.Properties["sAMAccountName"][0].ToString();
}
else
{
//Current user is in department and does not manage it
AD_UserProfile p = new AD_UserProfile();
p.distinguishedName = temp.Properties["distinguishedName"][0].ToString();
p.email = temp.Properties["mail"][0].ToString();
p.manager = temp.Properties["manager"][0].ToString();
p.name = temp.Properties["name"][0].ToString();
p.userPrincipalName = temp.Properties["userPrincipalName"][0].ToString();
p.userName = temp.Properties["sAMAccountName"][0].ToString();
dp.AD_UserProfile.Add(p);
}
}
}
I don't see anywhere that you're initializing dp.AD_ManagerProfile, so it is likely null. You could either give it a value in GetDepartmentInfo or in the constructor.
if (owner == temp.Properties["sAMAccountName"][0].ToString())
{
//Current user is manager of department
dp.AD_ManagerProfile = new AD_ManagerProfile();
dp.AD_ManagerProfile.distinguishedName = temp.Properties["distinguishedName"][0].ToString(); // This line errors out with instance not set to object error.
or
public AD_DepartmentProfile()
{
this.AD_UserProfile = new HashSet<AD_UserProfile>();
this.AD_ManagerProfile = new AD_ManagerProfile();
}
Related
In my MdiForm I have a menubar that has btnSave on it. I would like to save the data created in my childform that is active by clicking the btnSave on the midForm menubar. I have these classes to save the data to the database:
StudentBal.cs
internal class StudentBal
{
public string DateAdded { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string CityAddress { get; set; }
public string HomeAddress { get; set; }
public string Nationality { get; set; }
public string MaritalStatus { get; set; }
public string DateOfBirth { get; set; }
public string PlaceOfBirth { get; set; }
public string TelNo { get; set; }
public string Father { get; set; }
public string Mother { get; set; }
public string ParentsAddress { get; set; }
public string EmployersName { get; set; }
public string EmplyerTelNo { get; set; }
public string GuardiansName { get; set; }
public string GuradiansAddress { get; set; }
public byte[] StudentImage { get; set; }
public string WorkAddress { get; set; }
public int InsertStudent(StudentBal bal)
{
var dal = new StudentDal();
return dal.InsertStudent(bal);
}
StudentDal.cs
public int InsertStudent(StudentBal bal)
{
const string query =
#"INSERT INTO students VALUES(#DateAdded, #FirstName, #MiddleName, #LastName, #CityAddress, #HomeAddress, #Nationality,
#MaritalStatus, #DateOfBirth, #PlaceOfBirth, #TelNo, #Father, #Mother,
#ParentsAddress, #EmployersName, #EmployersTelNo, #GuardiansName,
#GuardiansAddress, #StudentImage, #WorkAddress)";
using (_cmd = new SqlCommand(query, _cn))
{
_cmd.Parameters.AddWithValue("#DateAdded", Convert.ToDateTime(bal.DateAdded).ToShortDateString());
_cmd.Parameters.AddWithValue("#FirstName", bal.FirstName);
_cmd.Parameters.AddWithValue("#MiddleName", bal.MiddleName);
_cmd.Parameters.AddWithValue("#LastName", bal.LastName);
_cmd.Parameters.AddWithValue("#CityAddress", bal.CityAddress);
_cmd.Parameters.AddWithValue("#HomeAddress", bal.HomeAddress);
_cmd.Parameters.AddWithValue("#Nationality", bal.Nationality);
_cmd.Parameters.AddWithValue("#MaritalStatus", bal.MaritalStatus);
_cmd.Parameters.AddWithValue("#DateOfBirth", bal.DateOfBirth);
_cmd.Parameters.AddWithValue("#PlaceOfBirth", bal.PlaceOfBirth);
_cmd.Parameters.AddWithValue("#TelNo", bal.TelNo);
_cmd.Parameters.AddWithValue("#Father", bal.Father);
_cmd.Parameters.AddWithValue("#Mother", bal.Mother);
_cmd.Parameters.AddWithValue("#ParentsAddress", bal.ParentsAddress);
_cmd.Parameters.AddWithValue("#EmployersName", bal.EmployersName);
_cmd.Parameters.AddWithValue("#EmployersTelNo", bal.EmplyerTelNo);
_cmd.Parameters.AddWithValue("#GuardiansName", bal.GuardiansName);
_cmd.Parameters.AddWithValue("#GuardiansAddress", bal.GuradiansAddress);
_cmd.Parameters.AddWithValue("#StudentImage", bal.StudentImage);
_cmd.Parameters.AddWithValue("#WorkAddress", bal.WorkAddress);
_cn.Open();
return(_cmd.ExecuteNonQuery());
}
}
This is in my AddStudent Form
private void btnSaveInformation_Click(object sender, EventArgs e)
{
var stream = new MemoryStream();
pictureBox2.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
if (!CheckTextBox()) return;
var bal = new StudentBal
{
CityAddress = string.IsNullOrWhiteSpace(txtCityAddress.Text) ? "N/A" : txtCityAddress.Text,
DateAdded = DateTime.Now.ToShortDateString(),
DateOfBirth = txtDateOfBirth.Text,
EmployersName = string.IsNullOrWhiteSpace(txtEmployersName.Text) ? "N/A" : txtEmployersName.Text,
EmplyerTelNo = string.IsNullOrWhiteSpace(txtEmpContactNumber.Text) ? "N/A" : txtEmpContactNumber.Text,
Father = string.IsNullOrWhiteSpace(txtFathersName.Text) ? "N/A" : txtFathersName.Text,
FirstName = txtFirstName.Text,
GuardiansName = string.IsNullOrWhiteSpace(txtGuardiansName.Text) ? "N/A" : txtGuardiansName.Text,
GuradiansAddress = string.IsNullOrWhiteSpace(txtGuardiansAddress.Text) ? "N/A" : txtGuardiansAddress.Text,
HomeAddress = txtHomeAddress.Text,
LastName = txtLastName.Text,
MaritalStatus = txtMaritalStatus.Text,
MiddleName = string.IsNullOrWhiteSpace(txtMiddleName.Text) ? "N/A" : txtMiddleName.Text,
Mother = txtMothersName.Text,
Nationality = txtNationality.Text,
ParentsAddress = txtParentsAddress.Text,
PlaceOfBirth = txtPlaceOfBirth.Text,
TelNo = string.IsNullOrWhiteSpace(txtTelNo.Text) ? "N/A" : txtTelNo.Text,
StudentImage = pic,
WorkAddress = string.IsNullOrWhiteSpace(txtWorkAddress.Text) ? "N/A" : txtWorkAddress.Text,
};
var result = bal.InsertStudent(bal);
if (result > 0)
{
MessageBox.Show(#"Data successfully added.");
}
var obj = (MdiForm)Application.OpenForms["MdiForm"];
if (obj != null) obj.FillComboBox();
}
I would need to pass all the information from my childform(AddStudent) to the parentform(MdiFOrm) so I can save all the details by clicking on the btnSave in the menubar. I tried creating a public method (SaveDetails()) that can be invoked in the parent form like so:
AddStudent add = new AddStudent();
add.SaveDetails();
But doing the code above will create a new instance and will not save the active childform that has the values to be saved. If there is a way to call a method in the active childform without instantiating (var addStudent = new AddStudent();) that will be great.
Making the method public static won't work in this scenario.
Thank you for your help.
This is the abstract example of doing a callback:
public class Parent
{
public void CreateChild()
{
Child childNew = new Child(this); //here you give over the parents reverence
}
public void SaveStuff(int number)
{
//here you can save the number
}
}
class Child
{
private Parent parent;
public Child(Parent parent)
{
this.parent = parent;
}
public void PressOkButton()
{
this.parent.SaveStuff(4); //here you are doing the callback
}
}
I created two registration forms
1.User Registration
2.Company Registration (In one database)
I created a sign In page. How to retrieve the particular user from the tables.
class UserReg
{
[AutoIncrement, PrimaryKey]
public int UserID { get; set; }
public string Name { get; set; }
public string UserName { get; set; }
public string UserPassword { get; set; }
public string Gender { get; set; }
public string State { get; set; }
}
The above code is for user registration table
class FuelReg
{
[AutoIncrement,PrimaryKey]
public int FuelID { get; set; }
public string FuelName { get; set; }
public string FuelPassword { get; set; }
public string CompanyName { get; set; }
public string CompanyAddress { get; set; }
}
The above code is for company registration.
Now the user and company should login with the same login page. How to implement this.
I tried some code but I cannot compare the particular user. My main problem is if the user and company provides similar user and password that would be a failure. So how to change it. (No validations given in the project)
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
var dbpath = ApplicationData.Current.LocalFolder.Path + "/Map.db";
var con = new SQLiteAsyncConnection(dbpath);
try
{
UserReg t = new UserReg();
string query = string.Format("select UserName,UserPassword,Gender,State,Name from UserReg where UserName='{0}' and UserPassword='{1}'", text_user.Text, text_pass.Password);
List<UserReg> mylist = await con.QueryAsync<UserReg>(query);
if (mylist.Count == 1)
{
t = mylist[0];
}
if (t.UserName == text_user.Text && t.UserPassword == text_pass.Password && t.Gender!=null && t.Name!=null && t.State!=null)
{
this.Frame.Navigate(typeof(MainPage));
}
else
{
FuelReg f = new FuelReg();
string query1 = string.Format("select FuelName,FuelPassword,CompanyName,CompanyAddress from FuelReg where FuelName='{0}' and FuelPassword='{1}'", text_user.Text, text_pass.Password);
List<FuelReg> mylist1 = await con.QueryAsync<FuelReg>(query1);
if (mylist1.Count == 1)
{
f = mylist1[0];
}
if (f.FuelName == text_user.Text && f.FuelPassword == text_pass.Password && f.CompanyName!=null && f.CompanyAddress!=null)
{
this.Frame.Navigate(typeof(NewPage));
}
}
}
catch(Exception ex)
{
var msd = new MessageDialog("" + ex).ShowAsync();
}
}
So how to fetch the exact data when the user inputs in the SignIn page from the two tables
I am having the following criteria:-
1.Create gmail group using query execution in sql db. This query will filter contacts on the basis of region.
2.These contacts may or may not be different for each send request. It depends upon the users those who are active at the time of send.
3.I am able to send mail to group.
Main problem is related with how i can update group each time before sending mail to group members excluding inactive members.
Please let me know if you need more explanation.I will try my best.
UPDATE:
I had done the following code from a Console application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Contacts;
using Google.GData.Contacts;
using Google.GData.Client;
using Google.GData.Extensions;
namespace IMAPCommands
{
class Program
{
static void Main(string[] args)
{ GoogleContactService.InitializeService("mailid", "password");
List<ContactDetail> test = GoogleContactService.GetContacts("System Group: My Contacts");
//Use break point here
Console.ReadLine();
}
public class GoogleContactService
{
#region Properties
public static ContactsService GContactService = null;
#endregion
#region Methods
public static void InitializeService(string username, string password)
{
GContactService = new ContactsService("Contact Infomation");
GContactService.setUserCredentials(username, password);
}
public static List<ContactDetail> GetContacts(string GroupName = null)
{
List<ContactDetail> contactDetails = new List<ContactDetail>();
ContactsQuery contactQuery = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
contactQuery.NumberToRetrieve = 1000;
if (!String.IsNullOrEmpty(GroupName))
{
GroupEntry ge = GetGroup(GroupName);
if (ge != null)
contactQuery.Group = ge.Id.AbsoluteUri;
}
else
{
string groupName = "";
GroupEntry ge = GetGroup(groupName);
if (ge != null)
contactQuery.Group = ge.Id.AbsoluteUri;
}
ContactsFeed feed = GContactService.Query(contactQuery);
foreach (ContactEntry entry in feed.Entries)
{
if (entry.Title.Text == "TechnicalBulletinName")
{
int test = entry.Emails.Count;
ContactDetail contact = new ContactDetail
{
Name = entry.Title.Text,
EmailAddress1 = entry.Emails.Count >= 1 ? entry.Emails[0].Address : "",
EmailAddress2 = entry.Emails.Count >= 2 ? entry.Emails[1].Address : "",
Phone1 = entry.Phonenumbers.Count >= 1 ? entry.Phonenumbers[0].Value : "",
Phone2 = entry.Phonenumbers.Count >= 2 ? entry.Phonenumbers[1].Value : "",
Address = entry.PostalAddresses.Count >= 1 ? entry.PostalAddresses[0].FormattedAddress : "",
Details = entry.Content.Content
};
contact.UserDefinedFields = new List<UDT>();
foreach (var udt in entry.UserDefinedFields)
{
contact.UserDefinedFields.Add(new UDT { Key = udt.Key, Value = udt.Value });
}
contactDetails.Add(contact);
}
}
return contactDetails;
}
#endregion
#region Helpers
public static GroupEntry GetGroup(string GroupName)
{
GroupEntry groupEntry = null;
GroupsQuery groupQuery = new GroupsQuery(GroupsQuery.CreateGroupsUri("default"));
groupQuery.NumberToRetrieve = 100;
GroupsFeed groupFeed = GContactService.Query(groupQuery);
foreach (GroupEntry entry in groupFeed.Entries)
{
if (entry.Title.Text.Equals(GroupName, StringComparison.CurrentCultureIgnoreCase))
{
groupEntry = entry;
break;
}
}
return groupEntry;
}
#endregion
}
public class ContactDetail
{
public string Name { get; set; }
public string EmailAddress1 { get; set; }
public string EmailAddress2 { get; set; }
public string Phone1 { get; set; }
public string Phone2 { get; set; }
public string Address { get; set; }
public string Details { get; set; }
public string Pipe { get; set; }
public string Relationship { get; set; }
public string Status { get; set; }
public List<UDT> UserDefinedFields { get; set; }
}
public class UDT
{
public string Key { get; set; }
public string Value { get; set; }
}
}
Still not able to get list of contacts which are member of group TechnicalBulletinName. I am only able to get emailID of this group not members of the group.
i want to add items in a sql database to a dictionary but the values enter as null in the object reference heres the code im using atm
public static Dictionary<string, prizedbinfo> dbprizes = new Dictionary<string, prizedbinfo>();
private void LoadData(string dataloc)
{
if (!File.Exists(dataloc))
{
MessageBox.Show(dataloc + " not found.");
return;
}
var connection = new SQLiteConnection("Data Source=" + dataloc);
connection.Open();
var datacommand = new SQLiteCommand("SELECT prizeID, createdOn, expiresOn, modifiedOn, status, redeemedOn, giftedOn, claimedOn FROM mySnackData", connection);
List<string[]> datas = ExecuteStringCommand(datacommand, 9);
foreach (string[] row in datas)
{
if (!Program.dbprizes.ContainsKey(row[0]))
{
Program.dbprizes.Add(row[0], new prizedbinfo(row));
}
}
connection.Close();
}
and the prizedbinfo object is
class prizedbinfo
{
public prizedbinfo(string[] dbdata)
{
string prizeID = dbdata[0];
string createdOn = dbdata[1];
string expiresOn = dbdata[2];
string modifiedOn = dbdata[3];
string status = dbdata[4];
string redeemedOn = dbdata[5];
string giftedOn = dbdata[6];
string claimedOn = dbdata[7];
string name = dbdata[8];
}
public string prizeID { get; set; }
public string createdOn { get; set; }
public string expiresOn { get; set; }
public string modifiedOn { get; set; }
public string status { get; set; }
public string redeemedOn { get; set; }
public string giftedOn { get; set; }
public string claimedOn { get; set; }
public string name { get; set; }
}
i have tested it with breakpoints and all the data is correctly added to datas and row but not to the prizedbinfo object for some reason
Remove the string keyword from all your variables in the prizedbinfo constructor. You're creating local variables that immediately go out of scope, so you're losing your values.
public prizedbinfo(string[] dbdata)
{
prizeID = dbdata[0];
createdOn = dbdata[1];
expiresOn = dbdata[2];
modifiedOn = dbdata[3];
status = dbdata[4];
redeemedOn = dbdata[5];
giftedOn = dbdata[6];
claimedOn = dbdata[7];
name = dbdata[8];
}
In my controller I'm looping through items and saving them to my db. The problem is that it saves the first item, but none of the others. I put a breakpoint on the "SaveItem()" line in the loop and it hits it every time, but what seems odd to me is that it only goes through to the method for the 1st item.
What am I doing wrong?
public void SubmitItem(Cart cart, ShippingDetails shippingDetails, ProcessedItems processedItem, string orderID)
{
var cartItems = cart.Lines;
//CartIndexViewModel cartIndex = new CartIndexViewModel();
//var customID = cartIndex.OrderID;
foreach(var item in cartItems)
{
processedItem.OrderID = orderID;
processedItem.ProductID = item.Product.ProductID;
processedItem.Name = item.Product.Name;
processedItem.Description = item.Product.Description;
processedItem.Price = item.Product.Price;
processedItem.Category = item.Product.Category;
processedItem.ImageName = item.Product.ImageName;
processedItem.Image2Name = item.Product.Image2Name;
processedItem.Image3Name = item.Product.Image3Name;
processedItem.BuyerName = shippingDetails.Name;
processedItem.Line1 = shippingDetails.Line1;
processedItem.Line2 = shippingDetails.Line2;
processedItem.Line3 = shippingDetails.Line3;
processedItem.City = shippingDetails.City;
processedItem.State = shippingDetails.State;
processedItem.Zip = shippingDetails.Zip;
processedItem.Country = shippingDetails.Country;
processedItem.Status = "Submitted";
processedItems.SaveItem(processedItem);
}
}
public class EFProcessedItemsRepository : IProcessedItems
{
private EFDbContext context = new EFDbContext();
public IQueryable<ProcessedItems> ProcessedItem
{
get { return context.ProcessedItems; }
}
public void SaveItem(ProcessedItems processedItem)
{
if(processedItem.ProcessedID == 0)
{
try
{
context.ProcessedItems.Add(processedItem);
context.SaveChanges();
}
catch (Exception)
{
throw;
}
}
else
{
context.Entry(processedItem).State = EntityState.Modified;
}
}
public void DeleteItem(ProcessedItems processedItem)
{
context.ProcessedItems.Remove(processedItem);
context.SaveChanges();
}
}
here is the class for the processedItem:
public class ProcessedItems
{
[Key]
public int ProcessedID { get; set; }
public string OrderID { get; set; }
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
public string ImageName { get; set; }
public string Image2Name { get; set; }
public string Image3Name { get; set; }
public string Status { get; set; }
//shipping
public string BuyerName { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
}
Interface:
public interface IProcessedItems
{
IQueryable<ProcessedItems> ProcessedItem { get; }
void SaveItem(ProcessedItems processedItem);
void DeleteItem(ProcessedItems processedItem);
}
try calling context.SaveChanges() after adding all of the items, I think it should persist them all in one go.
Another thing to try:
Refactor your code so that SaveItem accepts only one item to save, Add it and call SaveChanges()
Loop through the cart items outside the method and call the method with one item to save at a time.
// set orderID, shippingDetails above
foreach(var item in cartItems)
{
ProcessedItems processedItem = new ProcessedItems();
processedItem.OrderID = orderID;
processedItem.ProductID = item.Product.ProductID;
processedItem.Name = item.Product.Name;
processedItem.Description = item.Product.Description;
processedItem.Price = item.Product.Price;
processedItem.Category = item.Product.Category;
processedItem.ImageName = item.Product.ImageName;
processedItem.Image2Name = item.Product.Image2Name;
processedItem.Image3Name = item.Product.Image3Name;
processedItem.BuyerName = shippingDetails.Name;
processedItem.Line1 = shippingDetails.Line1;
processedItem.Line2 = shippingDetails.Line2;
processedItem.Line3 = shippingDetails.Line3;
processedItem.City = shippingDetails.City;
processedItem.State = shippingDetails.State;
processedItem.Zip = shippingDetails.Zip;
processedItem.Country = shippingDetails.Country;
SubmitItem(processedItem);
}
public void SubmitItem(ProcessedItems processedItem)
{
processedItem.Status = "Submitted";
processedItems.SaveItem(processedItem);
}
I think it is because processedItem is the same instance for each loop iteration. So after it has been through SaveItem once, it has its ProcessedID set and therefore won't get processed again.
My first guess is that you always store one entity, which is stored in processedItem, which is a input parameter. Try to create new Entity on each loop and then save it. In other words, you assign values to input parameter
processedItem.OrderID = orderID;
and then store same entity each time, but with changed fields
processedItems.SaveItem(processedItem);