Getting Values from a session object - c#

these is my code for setting session object. i want to use that object to get the infomation of login user. but i am unable to do that i get the error 'Input String is not in correct format'. i need help here to know how to create an object & get values from my session object
public UserLoginDetails LoggedUserDetails
{
set { Session["loggeduserdetails"] = value; }
get
{
if (Session["loggeduserdetails"] == null)
{
if (Session["username"] == null)
{
Response.Redirect("../Authentication/Login.aspx");
}
if (Session["password"] == null)
{
Response.Redirect("../Authentication/Login.aspx");
}
DAL.LoginHistoryDAL LoginDAL = new DAL.LoginHistoryDAL();
DataSet Ds = LoginDAL.AuthenticateUser(Session["username"].ToString(), EncryptionUtility.Encrypt(Session["password"].ToString()));
UserLoginDetails ULD = new UserLoginDetails();
if (Ds.Tables[0].Rows.Count > 0)
{
// Populating UserObj
bool IsAdmin = false;
bool IsMasterAdmin = false;
if (Ds.Tables[0].Rows[0]["IsAdmin"].ToString() == "1")
{
IsAdmin = true;
}
else
{
IsAdmin = false;
}
if (Ds.Tables[0].Rows[0]["IsMasterAdmin"].ToString() == "1")
{
IsMasterAdmin = true;
}
else
{
IsMasterAdmin = false;
}
ULD = new UserLoginDetails();
ULD.UserId = int.Parse(Ds.Tables[0].Rows[0]["UserId"].ToString());
ULD.IsAdmin = IsAdmin;
ULD.IsMasterAdmin = IsMasterAdmin;
ULD.UserName = Ds.Tables[0].Rows[0]["FullName"].ToString();
ULD.LocationID = int.Parse(Ds.Tables[0].Rows[0]["LocationID"].ToString());
ULD.FullName = Ds.Tables[0].Rows[0]["FullName"].ToString();
ULD.StatusId = int.Parse(Ds.Tables[0].Rows[0]["StatusId"].ToString());
ULD.Email = Ds.Tables[0].Rows[0]["Email"].ToString();
ULD.CellNo = Ds.Tables[0].Rows[0]["Cell"].ToString();
ULD.CityId = int.Parse(Ds.Tables[0].Rows[0]["CityID"].ToString());
ULD.StateId = int.Parse(Ds.Tables[0].Rows[0]["StateId"].ToString());
ULD.CountryId = int.Parse(Ds.Tables[0].Rows[0]["CountryID"].ToString());
}
Session["loggeduserdetails"] = ULD;
}
return (UserLoginDetails)Session["loggeduserdetails"];
}
}
}
public class UserLoginDetails
{
public int UserId = 0;
public bool IsAdmin = false;
public bool IsMasterAdmin = false;
public string UserName = string.Empty;
public int LocationID = 0;
public string FullName = string.Empty;
public int StatusId = 0;
public string Email = string.Empty;
public string CellNo = string.Empty;
public int CityId = 0;
public int StateId = 0;
public int CountryId = 0;
}

Looks like one of the pieces of data you expect to be a numeric value isn't.
I.e. UserId, or CityID isn't a numeric value or any other.
I would have a look at one of the following lines of code:
ULD.UserId = int.Parse(Ds.Tables[0].Rows[0]["UserId"].ToString());
ULD.LocationID = int.Parse(Ds.Tables[0].Rows[0]["LocationID"].ToString());
ULD.StatusId = int.Parse(Ds.Tables[0].Rows[0]["StatusId"].ToString());
ULD.CityId = int.Parse(Ds.Tables[0].Rows[0]["CityID"].ToString());
ULD.StateId = int.Parse(Ds.Tables[0].Rows[0]["StateId"].ToString());
ULD.CountryId = int.Parse(Ds.Tables[0].Rows[0]["CountryID"].ToString());

Related

Can't search for the max value into an array

My problem is that i can't search into an array using linq in order to find an object property and set that as an id.
I need the method to search in the array for other model.idCliente and set that value as the "nextid + 1", in order to use it as id and the next array index.
Since the array's empty, the program adds the new object correctly, but when entering in the else if case, i get an axception for "a as null".
This is my code (where i get an exception on the else if linq line saying that "a" is null):
//Arrays
ClienteModel[] MemoryClienti = new ClienteModel[19];
OrdineModel[] MemoryOrdini = new OrdineModel[19];
//Aggiungi
public bool CreateCliente(ClienteModel model)
{
if (MemoryClienti[0] == null)
{
int defaultID = 0;
int defaultIndex = 0;
model.IDCliente = defaultID;
MemoryClienti[defaultIndex] = model;
}
else if (MemoryClienti[0]!=null)
{
var maxID = MemoryClienti.Max(a => a.IDCliente);
model.IDCliente = maxID++;
MemoryClienti[maxID++] = model;
}
return true;
}
This is the code of the form click:
//Aggiungi Cliente
private void aggiungiClienteButton_Click(object sender, EventArgs e)
{
clienteModel.Cognome = cognomeTextBox.Text;
clienteModel.Nome = nomeTextBox.Text;
clienteModel.Indirizzo = indirizzoTextbox.Text;
dbMemoryManager.CreateCliente(clienteModel);
MessageBox.Show("Cliente aggiunto correttamente.");
cognomeTextBox.Text = String.Empty;
nomeTextBox.Text = String.Empty;
indirizzoTextbox.Text = String.Empty;
}
This is the ClienteModel class:
public class ClienteModel
{
public int IDCliente { get; set; }
public string Cognome { get; set; }
public string Nome { get; set; }
public string Indirizzo { get; set; }
}
Wouldn't the following code achieve what you are trying to do?
ClienteModel[] MemoryClienti = new ClienteModel[19];
OrdineModel[] MemoryOrdini = new OrdineModel[19];
int maxID = 0; /* 0 is not a valid ID. IDs start from 1 */
//Aggiungi
public bool CreateCliente(ClienteModel model)
{
if(maxID <= MemoryClienti.Length) {
MemoryClienti[maxID++] = model; // copy the reference
model.IDCliente = maxID; // update the object's ID
return true;
} else {
return false; // can't add. array is full
}
}
If you are also doing deletions, you are better off using a List as others have also suggested.

Compare data from ActiveDirectory and store to db

Currently I create that ActiveDirectory user is store to file and it's working perfect. What I want for now is that I need to comapre data from ActiveDirectory and data from database and if status is 0 change it and store to database result. It means if account is active = 1 is not active = 0.
So far I create this
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.DirectoryServices;
using System.IO;
namespace ActiverDirectory
{
public class Korisnik
{
public int Id { get; set; }
public string Username { get; set; } //samaccountname
public string DisplayName { get; set; } //displayname
public bool isEnabled { get; set; } //AccountExpires
public bool PassNevExp { get; set; } //PassExpires
}
class Program
{
static void Main(string[] args)
{
foreach (Korisnik korisnik in VratiKorisnike())
{
Console.WriteLine(korisnik);
}
}
public static List<Korisnik> VratiKorisnike()
{
List<Korisnik> lstADUsers = new List<Korisnik>();
string sDomainName = "saoos";
string DomainPath = "LDAP://" + sDomainName;
string constring = #"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True";
string Query = "SELECT * FROM tblZaposleni_AD";
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(Query, constring);
adapter.Fill(table);
string txt = "";
string fileLoc = #"C:\output.txt";
foreach (DataRow row in table.Rows)
{
string line = "";
foreach (DataColumn column in table.Columns)
{
line += "," + row[column.ColumnName].ToString();
}
txt += line.Substring(1);
}
using (var sw = new StreamWriter(fileLoc))
{
sw.WriteLine(txt);
}
Console.WriteLine("Ok");
DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.Filter = "(&(objectClass=user)(objectCategory=person))";
search.PropertiesToLoad.Add("samaccountname"); // Username
search.PropertiesToLoad.Add("displayname"); // display name
search.PropertiesToLoad.Add("userAccountControl"); // isEnabled
search.PropertiesToLoad.Add("pwdLastSet"); //passwordExpires
DataTable resultsTable = new DataTable();
resultsTable.Columns.Add("samaccountname");
resultsTable.Columns.Add("displayname");
resultsTable.Columns.Add("Neaktivan");
resultsTable.Columns.Add("dontexpirepassword");
SearchResult result;
SearchResultCollection resultCol = search.FindAll();
if (resultCol != null)
{
for (int counter = 0; counter < resultCol.Count; counter++)
{
string UserNameEmailString = string.Empty;
result = resultCol[counter];
if (result.Properties.Contains("samaccountname")
&& result.Properties.Contains("displayname"))
{
int userAccountControl = Convert.ToInt32(result.Properties["userAccountControl"][0]);
string samAccountName = Convert.ToString(result.Properties["samAccountName"][0]);
int isEnable;
int Dont_Expire_Password;
if (userAccountControl > 0)
{
isEnable = 0;
}
else
{
isEnable = 1;
}
if ((userAccountControl & 65536) != 0)
{
Dont_Expire_Password = 1;
}
else
{
Dont_Expire_Password = 0;
}
Korisnik korisnik = new Korisnik();
korisnik.Username = (result.Properties["samaccountname"][0]).ToString();
korisnik.DisplayName = result.Properties["displayname"][0].ToString();
korisnik.isEnabled = Convert.ToBoolean(result.Properties["userAccountControl"][0]);
//long value = (long)result.Properties["pwdLastSet"][0];
//DateTime pwdLastSet = DateTime.FromFileTimeUtc(value);
DataRow dr = resultsTable.NewRow();
dr["samaccountname"] = korisnik.Username.ToString();
dr["displayname"] = korisnik.DisplayName.ToString();
dr["neaktivan"] = Math.Abs(isEnable);
dr["dontexpirepassword"] = Dont_Expire_Password;
resultsTable.Rows.Add(dr);
lstADUsers.Add(korisnik);
}
}
var json = JsonConvert.SerializeObject(resultCol, Formatting.Indented);
var res = json;
Console.WriteLine("Ispis uspjesno obavljen");
Console.ReadLine();
File.WriteAllText(fileLoc, json);
}
return lstADUsers;
}
}
}
So far everything is here, I just need to store this to [db].[table]
This is some peace of code which check from ActiveDirectory if UserAccount is active or disable
If account is active in ActiveDirectory and in [db].[table] is inactive change status to 1 and store data. When I run this I get properly output, but status is not changed.
Any ideas
Try something like this :
public class Korisnik
{
public int Id { get; set; }
public string Username { get; set; } //samaccountname
public string DisplayName { get; set; } //displayname
private bool _isEnabled { get; set; } //AccountExpires
public int isEnabled {
get { return (_isEnabled == true)? 1 : 0;}
set { _isEnabled = (value == 0) ? false : true; }
} //AccountExpires
public bool PassNevExp { get; set; } //PassExpires
}

How do I return a class array from one WPF window to another window?

In a WPF window called from the MainWindow.xaml.cs I have a class I defined with multiple elements. I create an array of this class type.
In FieldLengths.xaml.cs I have:
public partial class FieldLengths : Window
{
public FieldJustifyFill[] fjfFields = new FieldJustifyFill[0];
public class FieldJustifyFill
{
public int ColumnNumber { get; set; }
public bool RightJustify { get; set; }
public bool LeftJustify { get; set; }
public bool LeftZeroFill { get; set; }
public bool RightZeroFill { get; set; }
}
I load is this way:
try
{
dtFields = ((DataView)dtGrid.ItemsSource).ToTable();
intNumFields = 0;
for (int intRowCnt = 0; intRowCnt < dtFields.Rows.Count; intRowCnt++)
{
bool blnJustifyRight = Convert.ToBoolean(dtFields.Rows[intRowCnt][2]);
bool blnJustifyLeft = Convert.ToBoolean(dtFields.Rows[intRowCnt][3]);
bool blnLeftZeroFill = Convert.ToBoolean(dtFields.Rows[intRowCnt][4]);
bool blnRightZeroFill = Convert.ToBoolean(dtFields.Rows[intRowCnt][5]);
if (blnJustifyRight || blnJustifyLeft || blnLeftZeroFill || blnRightZeroFill)
{
Array.Resize(ref fjfFields, intNumFields + 1);
fjfFields[intNumFields] = new FieldJustifyFill
{
ColumnNumber = intRowCnt,
RightJustify = blnJustifyRight,
LeftJustify = blnJustifyLeft,
LeftZeroFill = blnLeftZeroFill,
RightZeroFill = blnRightZeroFill
};
intNumFields += 1;
}
}
}
catch (Exception ex)
{
string strMsg;
strMsg = "RefreshRowSize, error '" + ex.Message + "' has occurred.";
System.Windows.MessageBox.Show(strMsg);
}
In MainWindow.xaml.cs I have this:
public partial class MainWindow : Window
{
FieldJustifyFillDest[] fjfFieldsDest = new FieldJustifyFillDest[0];
And in a routine I try to get the values from FixedLengths.xaml.cs like this:
FieldLengths flWin = new FieldLengths(strInputName, strFieldInfo, null, null, null, strMappingMetadata);
flWin.Left = System.Windows.Application.Current.MainWindow.Left + 15;
flWin.Top = desktopWorkArea.Top + 25;
flWin.ShowDialog();
if (flWin.blnFLCreateFile)
{
string strPrgFileName;
Array.Resize(ref fjfFieldsDest, flWin.fjfFields.Length);
for (int i = 0; i < flWin.fjfFields.Length; i++)
{
int intColumnNumber = flWin.fjfFields[i].ColumnNumber;
bool blnRightJustify = flWin.fjfFields[i].RightJustify;
bool blnLeftJustify = flWin.fjfFields[i].LeftJustify;
bool blnLeftZeroFill = flWin.fjfFields[i].LeftZeroFill;
bool blnRightZeroFill = flWin.fjfFields[i].RightZeroFill;
fjfFieldsDest[i] = new FieldJustifyFillDest
{
ColumnNumber = intColumnNumber,
RightJustify = blnRightJustify,
LeftJustify = blnLeftJustify,
LeftZeroFill = blnLeftZeroFill,
RightZeroFill = blnRightZeroFill
};
}
The variable intColumnNumber, blnRightJustify, blnLeftJustify, blnLeftZeroFill, blnRightZeroFill have the correct values but when it is loaded into fjfFieldsDest[i] they are not correct.
How do I return the class array correctly? I can not find a good example anywhere.
My apologies, my code is working correctly as coded. The debugger reordered the class elements alphabetically and I did not notice. Sorry all. However if the way I am coding it is not correct I welcome any feedback to code correctly.

Call Salesforce API to Add Leads using ASP.net

I am trying to call Salesforce Parnter wsdl to Create Leads to their system through my c# code.
but its giving me error:
Cannot implicitly convert type Contact[]' to 'sforce.sObject'
private string userID = "sasxxasasas#saasforce.in";
private string password = "sadwdasdasdasdsadasdsxzdddw";
private DateTime _nextLoginTime;
private string _sessionId;
string url="valueleads.in/pushleads/websvc/cigna/wsdl.xml";
SforceService binding;
private void getSessionInfo()
{
sforce.SforceService partnerService = new sforce.SforceService();
sforce.LoginResult lr = new sforce.LoginResult();
lr = partnerService.login(userID, password);
_sessionId = lr.sessionId;
Session["_sessionId"] = lr.sessionId;
Session["_serverUrl"] = lr.serverUrl;
Session["_nextLoginTime"] = DateTime.Now;
binding.SessionHeaderValue = new sforce.SessionHeader();
binding.SessionHeaderValue.sessionId = _sessionId;
binding.Url = lr.serverUrl;
}
public bool IsConnected()
{
bool blnResult = false;
if (!string.IsNullOrEmpty(_sessionId) & _sessionId != null)
{
if (DateTime.Now > _nextLoginTime)
blnResult = false;
else
blnResult = true;
}
else
blnResult = false;
return blnResult;
}
public void create()
{
if (!IsConnected())
{
getSessionInfo();
}
binding = new SforceService();
Contact contact=new Contact();
contact.fname="Eric";
contact.lname="Peter";
contact.mobile="9898989889";
Contact[] contacts = { contact };
string result;
sforce.SaveResult[] createResults = binding.create(new sObject[] { contacts });
if (createResults[0].success)
{
result = createResults[0].id;
}
else
{
result = createResults[0].errors[0].message;
}
Response.Write(result);
}
}
public class Contact
{
public String fname { get; set; }
public String lname { get; set; }
public String mobile { get; set; }
}
}
please help, very much new to this salesforce API.
You need to create an array of SObjects, not contacts, so do
sforce.sObject[] contacts = { contact };
string result;
sforce.SaveResult[] createResults = binding.create(contacts);

Binding to New Member Display; BuildComboList

I am trying to build a combo list for a program to fill the combobox with a list of applications. it keeps throwing up "Cannot bind to the new display member. Parameter name: newDisplayMember"
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "DisplayName";
applicantList.ValueMember = "DisplayValue";
}
Applicant Class
public class Applicant
{
//Members
private int applicant_ID;
private string applicant_fname;
private string applicant_lname;
private string applicant_phone;
private string applicant_address1;
private string applicant_address2;
private string applicant_city;
private string applicant_state;
private string applicant_zip;
private string applicant_email;
//properties
public int Applicant_ID
{
get { return applicant_ID; }
set { applicant_ID = value; }
}
public string Applicant_fname
{
get { return applicant_fname; }
set { applicant_fname = value; }
}
public string Applicant_lname
{
get { return applicant_lname; }
set { applicant_lname = value; }
}
public string Applicant_phone
{
get { return applicant_phone; }
set { applicant_phone = value; }
}
public string Applicant_address1
{
get { return applicant_address1; }
set { applicant_address1 = value; }
}
public string Applicant_address2
{
get { return applicant_address2; }
set { applicant_address2 = value; }
}
public string Applicant_city
{
get { return applicant_city; }
set { applicant_city = value; }
}
public string Applicant_state
{
get { return applicant_state; }
set { applicant_state = value; }
}
public string Applicant_zip
{
get { return applicant_zip; }
set { applicant_zip = value; }
}
public string Applicant_email
{
get { return applicant_email; }
set { applicant_email = value; }
}
//Constructors
private void DefaultValues()
{
applicant_ID = 0;
applicant_fname = "";
applicant_lname = "";
applicant_phone = "";
applicant_address1 = "";
applicant_address2 = "";
applicant_city = "";
applicant_state = "";
applicant_zip = "";
applicant_email = "";
}
private void Rec2Members(ApplicantRecord record)//defined in ApplicantDL
{
applicant_ID = record.applicant_ID;
applicant_fname = record.applicant_fname;
applicant_lname = record.applicant_lname;
applicant_phone = record.applicant_phone;
applicant_address1 = record.applicant_address1;
applicant_address2 = record.applicant_address2;
applicant_city = record.applicant_city;
applicant_state = record.applicant_state;
applicant_zip = record.applicant_zip;
applicant_email = record.applicant_email;
}
public ApplicantRecord ToRecord()
{
ApplicantRecord record = new ApplicantRecord();
record.applicant_ID = applicant_ID;
record.applicant_fname = applicant_fname;
record.applicant_lname = applicant_lname;
record.applicant_phone = applicant_phone;
record.applicant_address1 = applicant_address1;
record.applicant_address2 = applicant_address2;
record.applicant_city = applicant_city;
record.applicant_state = applicant_state;
record.applicant_zip = applicant_zip;
record.applicant_email = applicant_email;
return record;
}
public List<ApplicantRecord> GetList()
{
return Approval_Form.ApplicantRecord.ApplicantDL.GetList();
}
public void Insert()
{
applicant_ID = Approval_Form.ApplicantRecord.ApplicantDL.Insert(applicant_fname, applicant_lname, applicant_phone, applicant_address1, applicant_address2, applicant_city, applicant_state, applicant_zip, applicant_email);
}
public void Select(int applicant_ID)
{
ApplicantRecord record = Approval_Form.ApplicantRecord.ApplicantDL.Select(applicant_ID);
Rec2Members(record);
}
public void Update()
{
if (applicant_ID != 0)
{
Approval_Form.ApplicantRecord.ApplicantDL.Update(applicant_ID, applicant_fname, applicant_lname, applicant_phone, applicant_address1, applicant_address2, applicant_city, applicant_state, applicant_zip, applicant_email);
}
}
}
I think it should be:
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "Applicant_fname";
applicantList.ValueMember = "Applicant_ID";
}
You can change the applicant class further as follows:
Add two properties.
public string DisplayName
{
get { return (applicant_fname + " " + applicant_lname; }
}
public string DisplayValue
{
get { return (applicant_ID.ToString(); }
}
Keep data binding as:
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "DisplayName";
applicantList.ValueMember = "DisplayValue";
}

Categories