I am working on winforms, where I have 2 codes, working for the same thing, and they are same just the query difference but one is working completely fine and other one has issues as it misplace the images.
the problem is everytime I run code, images are at wrong place.
the correct functionality code:
int c2 = -1;
List<string> searchpath =new List<string>();
List<string> searchtitle = new List<string>();
listView2.Clear();
homerecipe.Clear();
searchtitle.Clear();
searchpath.Clear();
imageList3.Images.Clear();
var text = textBox1.Text;
char[] separator = { ' ' };
string[] words = null;
words = text.Split(separator);
foreach (string word in words)
{
try
{
cmd = new SqlCommand($"select Title, Thumbnail,RecipeName from RecipeInfo where RecipeName like '%{word}%'", con);
con.Open();
SqlDataReader read = cmd.ExecuteReader();
if (read.HasRows)
{
while (read.Read())
{
// if (homerecipe.Any(item => item == read[2].ToString())) continue;
searchtitle.Add(read[0].ToString());
searchpath.Add($#"{read[1].ToString()}");
homerecipe.Add(read[2].ToString());
}
read.Close();
//con.Close();
foreach (string ipath in searchpath)
{
ListViewItem img = listView2.FindItemWithText(ipath);
if (img == null)
{
imageList3.Images.Add(Image.FromFile(ipath));
}
}
listView2.LargeImageList = imageList3;
foreach (string hometitle in searchtitle)
{
ListViewItem list = listView2.FindItemWithText(hometitle);
if (list == null)
{
c2++;
listView2.Items.Add(hometitle, c2);
}
}
}
con.Close();
}
catch (SqlException)
{
MessageBox.Show("masla");
con.Close();
//continue;
}
The problematic code:
int ccc = -1;
hometitles.Clear();
homepaths.Clear();
homerecipe.Clear();
imageList2.Images.Clear();
try
{
cmd = new SqlCommand("select Title, Thumbnail,RecipeName from RecipeInfo order by newid()", con); //generating random from sql
con.Open();
SqlDataReader reader1 = cmd.ExecuteReader();
if (reader1.HasRows)
{
while (reader1.Read())
{
hometitles.Add(reader1[0].ToString());
homepaths.Add($#"{reader1[1].ToString()}");
homerecipe.Add(reader1[2].ToString());
}
}
reader1.Close();
//con.Close();
foreach (string imagepath in homepaths)
{
ListViewItem img = listView2.FindItemWithText(imagepath);
if (img == null)
{
imageList2.Images.Add(Image.FromFile(imagepath));
}
}
listView2.LargeImageList = imageList2;
foreach (string hometitle in hometitles)
{
ListViewItem list = listView2.FindItemWithText(hometitle);
if (list == null)
{
ccc++;
listView2.Items.Add(hometitle,ccc);
}
}
con.Close();
}
catch(SqlException)
{
MessageBox.Show("error");
}
I have tried using the homerecipe elements as image key as they are primary key but I don't know how to give a condition in foreach that if one name entered then the same name don't come twice.
for this, i was trying this
foreach (string imagepath in homepaths)
{
foreach(string name in homerecipe) //name a primary key
{
ListViewItem img = listView2.FindItemWithText(imagepath);
if (img == null)
{
MessageBox.Show(name);
imageList2.Images.Add(name,Image.FromFile(imagepath));
}
}
}
listView2.LargeImageList = imageList2;
foreach (string hometitle in hometitles)
{
foreach (string name in homerecipe)
{
ListViewItem list = listView2.FindItemWithText(hometitle);
if (list == null)
{
ccc++;
listView2.Items.Add(hometitle, name);
}
}
}
I am trying this for the last 3 days, please help me correct it. please I am in the deadline for my project but this issue is not resolving. I am new to programming please resolve this issue.
Sometimes, it happens that only images shuffle, sometimes both text and image but not correct positon
After reading the data from the database, in
while (reader.Read()){}
fills the ListView directly, which can make the code more concise and clear.
I wrote a similar example, you can refer to it.
Pictures fill ListView
Related
I'm new to C# and i'm trying to check whether a guest has checked in on a hotel app. I'm trying to get all bookings in a text file pass them in to a list then read through the list looking for the booking in reference.
The problem i'm having is that it only seems to put the first line of the text file into the list. Could anyone help me solve this?
One way i've tried:
public void CheckBookingReference()
{
List<string> BookingList = File.ReadAllLines(BookingFilePath).ToList();
foreach (var BookingLine in BookingList.ToList())
{
string[] bookings = BookingLine.Split(',');
int _BookingReferenceNumber = int.Parse(bookings[5]);
if (_BookingReferenceNumber == BookingReferenceNumber)
{
Console.WriteLine("Booking found, check in complete.");
break;
}
else
{
throw new Exception("BookingNotFoundException");
}
}
}
Another way i've also tried:
public void CheckBookingReference()
{
List<string> BookingList = new List<string>();
using (var sr = new StreamReader(BookingFilePath))
{
while (sr.Peek() >= 0)
BookingList.Add(sr.ReadLine());
foreach (var BookingLine in BookingList.ToList())
{
string[] bookings = BookingLine.Split(',');
int _BookingReferenceNumber = int.Parse(bookings[5]);
if (_BookingReferenceNumber == BookingReferenceNumber)
{
//throw new Exception("GuestAlreadyCheckedInException");
Console.WriteLine("booking found");
break;
}
else if (_BookingReferenceNumber != BookingReferenceNumber)
{
Console.WriteLine("not found");
break;
}
}
}
}
With the code you have, if the first line doesn't match, you throw the exception.
Try this:
public void CheckBookingReference()
{
List<string> BookingList = File.ReadAllLines(BookingFilePath).ToList();
foreach (var BookingLine in BookingList.ToList())
{
string[] bookings = BookingLine.Split(',');
int _BookingReferenceNumber = int.Parse(bookings[5]);
if (_BookingReferenceNumber == BookingReferenceNumber)
{
Console.WriteLine("Booking found, check in complete.");
return;
}
}
throw new Exception("BookingNotFoundException");
}
I'm accessing a list of calendar items on a SharePoint2013 site like so:
public ListItemCollection GetListByTitle(string title)
{
ClientContext context = new ClientContext(_site);
List list = context.Web.Lists.GetByTitle(title);
ListItemCollection listItems = list.GetItems(new CamlQuery()); // Empty CamlQuery to return all items in list
context.Load(listItems);
context.ExecuteQuery();
return listItems;
}
Then I'm passing that ListItemCollection to another method which will map some of the item's properties to a custom model
public List<CustomModel>GetListOfCustomModel(ListItemCollection listItems)
{
List<CustomModel> customModelList = new List<CustomModel>();
foreach(ListItem i in listItems)
{
FieldUserValue contact = (FieldUserValue)i.FieldValues["Contact"];
string s = (string)(contact.LookupValue);
string t = (string)i.FieldValues["Title"];
DateTime start = (DateTime)i.FieldValues["EventDate"];
// etc.
}
}
All of the "in-built" properties are easy to get, but I can't figure out how to access the resources the company has created and attached to these items.
E.g. each calendar item has a "Room" resource attached. I understand this is "meta data" but surely I should be able to access it somehow? It must be linked to the item I just don't know where to look. When I do a SharePoint list view for every column in the list I can see the "room" resource is generated as a link with reference to the resource.
Or am I going to end up viewing the text response from viewing my LISTALL page in a web request and parse the room out using good old fashioned string manipulation?!
I'd been looking at this for a couple of days, and I found a piece of code that translates a ListItemCollection to a DataTable
This code handled Microsoft.SharePoint.Client.FieldLookupValue, Microsoft.SharePoint.Client.FieldUserValue and Microsoft.SharePoint.Client.FieldUserValue[] but when I was looking at my Excel output I saw a Microsoft.SharePoint.Client.FieldLookupValue[]
Debugged the code again and drilled down into this instance of a FieldLookupValue[] called Facilities which, lo and behold, has the room and all other "Resources" in there.
SHORT ANSWER: Don't look for resources, look for FACILITIES
Here's some code I lifted from another answer site that cycles through ListItemCollection and transposes info to a DataTable but amended to show Id as well as value for FieldUserValue arrays and, more importantly, do the same for FieldLookupValue arrays:
public DataTable GetDataTableFromListItemCollection(ListItemCollection listItems)
{
DataTable dt = new DataTable();
foreach (var field in listItems[0].FieldValues.Keys)
{
dt.Columns.Add(field);
}
foreach (var item in listItems)
{
DataRow dr = dt.NewRow();
foreach (var obj in item.FieldValues)
{
if (obj.Value != null)
{
string key = obj.Key;
string type = obj.Value.GetType().FullName;
if (type == "Microsoft.SharePoint.Client.FieldLookupValue")
{
dr[obj.Key] = ((FieldLookupValue)obj.Value).LookupValue;
}
else if (type == "Microsoft.SharePoint.Client.FieldUserValue")
{
dr[obj.Key] = ((FieldUserValue)obj.Value).LookupValue;
}
else if (type == "Microsoft.SharePoint.Client.FieldUserValue[]")
{
FieldUserValue[] multValue = (FieldUserValue[])obj.Value;
foreach (FieldUserValue fieldUserValue in multValue)
{
dr[obj.Key] += "&" + fieldUserValue.LookupId + "=" + fieldUserValue.LookupValue;
}
}
else if (type == "Microsoft.SharePoint.Client.FieldLookupValue[]")
{
FieldLookupValue[] multValue = (FieldLookupValue[])obj.Value;
foreach (FieldLookupValue fieldLookupValue in multValue)
{
dr[obj.Key] += "&" + fieldLookupValue.LookupId + "=" + fieldLookupValue.LookupValue;
}
}
else if (type == "System.DateTime")
{
if (obj.Value.ToString().Length > 0)
{
var date = obj.Value.ToString().Split(' ');
if (date[0].Length > 0)
{
dr[obj.Key] = date[0];
}
}
}
else
{
dr[obj.Key] = obj.Value;
}
}
else
{
dr[obj.Key] = null;
}
}
dt.Rows.Add(dr);
}
return dt;
}
https://social.technet.microsoft.com/Forums/en-US/4bf89ee1-50a1-4c21-9ef9-51bd4d2ae155/convert-listitemcollection-to-datatable-without-looping-through-all-list-items-using-csom?forum=SP2016
My WPF application contains a form which when loaded, obtains two variables which contain a PID (procid) and a processname (procname) of a certain process currently running on the local computer.
I have a data table which contains netstat -ano data outputs in each column. Now i will need to compare either (procid) or (procname) with the associated data contained in the datatable, if both variable matches, store the current index/row number and use that index to get the remote ip address (remoteIp) of the associated datarow to be stored as variables.
But for some reason when i try to test the variable remoteIp the messagebox does not show up or just displays nothing. Is there something wrong with my code?
Pageone.xaml.cs
public partial class Pageone : Page
{
public Pageone(MainWindow mainWindow)
{
InitializeComponent();
}
private string remoteIp;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//instantiate the MainWindow and assign it to the 'window' variable
var window = (MainWindow)Application.Current.MainWindow;
string procName = window.proc1;
int subprocPid = window.proc2;
string procPID = subprocPid.ToString();
MessageBox.Show(procPID);
using (Process ns = new Process())
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] {
new DataColumn("Protocol"),
new DataColumn("Local Address"),
new DataColumn("Foreign Address"),
new DataColumn("State"),
new DataColumn("PID"),
new DataColumn("Process Name"),
});
ProcessStartInfo psi = new ProcessStartInfo("netstat.exe", "-ano");
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
ns.StartInfo = psi;
// Run it, and read the results
ns.Start();
using (StreamReader r = ns.StandardOutput)
{
string output = r.ReadToEnd();
ns.WaitForExit();
//Parse those results into a DataTable, polling the Process info
string[] lines = output.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
foreach (string line in lines)
{
string[] elements = line.Split(' ');
if (elements.Length < 5) continue;
if (elements.Contains("Proto")) continue;
DataRow dr = dt.NewRow();
List<string> validElements = new List<string>();
//Weed out empty elements.
foreach (string element in elements)
{
//skip blanks
if (element.Trim() == "") continue;
validElements.Add(element);
}
foreach (string element in validElements)
{
foreach (DataColumn dc in dt.Columns)
{
// fill in the buckets. Note that UDP doesn't have a state
if (dr["Protocol"].ToString() == "UDP" && dc.ColumnName == "State") continue;
if (dr[dc] == DBNull.Value)
{
dr[dc] = element;
break;
}
}
}
dr["Process Name"] = Process.GetProcessById(int.Parse(dr["PID"].ToString())).ProcessName;
dt.Rows.Add(dr);
}
foreach (DataRow row in dt.Rows)
{
int index = dt.Rows.IndexOf(row);
object cellprocPid = row["PID"];
object cellprocName = row["Process Name"];
object cellprocremoteIp = row["Foreign Address"];
if(cellprocPid.ToString() == procPID)
{
//MessageBox.Show(dt.Rows[index]["Process Name"].ToString());
//MessageBox.Show(index.ToString());
remoteIp = dt.Rows[index]["Foreign Address"].ToString();
}
}
}
}
MessageBox.Show(remoteIp);
}
}
It seems like the if statement condition did not match due to both of the variable having different process Id's, which resulting in the messagebox displaying nothing.
I have asked this question yesterday and i didn't get good response. i am working on a resx file. I have read the file and load it on data-gridview. now i wanted to be able to edit from the file and save.I have tried many ways but i didn't come with the solution. yesterday i tried this code below. I don't know how i can edit. please help me.
private void btnSave_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow _row in Gridview_Output.Rows)
{
DataRow dt1 = oDataTable.NewRow();
for (int i = 0; i < Gridview_Output.ColumnCount; i++)
{
Gridview_Input.SelectedRows[0].Cells[1].Value = oDataSet.Tables["data"].Rows[0][1].ToString();
Gridview_Input.SelectedRows[0].Cells[2].Value = oDataSet.Tables["data"].Rows[0][2].ToString();
Gridview_Input.SelectedRows[0].Cells[3].Value = oDataSet.Tables["data"].Rows[0][3].ToString();
Gridview_Input.SelectedRows[0].Cells[4].Value = oDataSet.Tables["data"].Rows[0][4].ToString();
oDataTable.Rows.Add(dt1);
}
oDataSet.Tables.Add(oDataTable);
oDataSet.WriteXml(PathSelection);
}
This will help you almost the way you want it.
Code snippet from Modifying .resx file in c#
public static void UpdateResourceFile(Hashtable data, String path)
{
Hashtable resourceEntries = new Hashtable();
//Get existing resources
ResXResourceReader reader = new ResXResourceReader(path);
if (reader != null)
{
IDictionaryEnumerator id = reader.GetEnumerator();
foreach (DictionaryEntry d in reader)
{
if (d.Value == null)
resourceEntries.Add(d.Key.ToString(), "");
else
resourceEntries.Add(d.Key.ToString(), d.Value.ToString());
}
reader.Close();
}
//Modify resources here...
foreach (String key in data.Keys)
{
if (!resourceEntries.ContainsKey(key))
{
String value = data[key].ToString();
if (value == null) value = "";
resourceEntries.Add(key, value);
}
}
//Write the combined resource file
ResXResourceWriter resourceWriter = new ResXResourceWriter(path);
foreach (String key in resourceEntries.Keys)
{
resourceWriter.AddResource(key, resourceEntries[key]);
}
resourceWriter.Generate();
resourceWriter.Close();
}
I have my code as below
string[] keys = { "myCustomUserControl.ascx", "myCustomUserControl.ascx.cs", "myCustomUserControl.ascx.designer.cs" };
string customUserControlName = CommonDataCalls.GetCustomUserControlName(keys);
UserControl objUserControl = (UserControl)this.LoadControl("~/UserControls/" + userControlName);
userControlPlaceHolder.Controls.Add(objUserControl);
The definition of GetCustomUserControlName is as below
public string GetCustomUserControlName(string[] keys)
{
try
{
string userConrolsPhysicalPtah = System.Web.HttpContext.Current.Server.MapPath("~/UserControls/");
DataTable objDataTable = new DataTable();
foreach (string key in keys)
{
objRequestVO.addObject("ACA_KEY", key);
CResponseVO objResponseVO = (CResponseVO)objGateway.ExecuteBusinessService(CConstant.ADMIN, CConstant.ASSEMBLY_INFO, CConstant.SELECT, objRequestVO);
DataSet objDataSet = (DataSet)objResponseVO.getObject("RES_DS");
cUserTrce objGeneral = new cUserTrce();
if (!objGeneral.IsNullOrEmptyDataset(objDataSet))
{
if (objDataTable.Rows.Count == 0)
{
objDataTable = objDataSet.Tables[0].Clone();
}
objDataTable.Rows.Add(objDataSet.Tables[0].Rows[0].ItemArray);
}
}
if (objDataTable != null && objDataTable.Rows.Count == 3)
{
string containerName = "usercontrols";
foreach (DataRow dr in objDataTable.Rows)
{
string userControlFileBlobUrl = dr["ACA_ASSEMBLY_PATH"].ToString();
string userControlFileName = dr["ACA_CLASS_NAME"].ToString();
Storage.Blob blobHandler = new Storage.Blob();
Stream blobstream = blobHandler.GetBlob(userControlFileBlobUrl, containerName);
if (!(File.Exists(userConrolsPhysicalPtah + userControlFileName)))
{
MemoryStream ms = (MemoryStream)blobstream;
FileStream outStream = File.OpenWrite(userConrolsPhysicalPtah + userControlFileName);
ms.WriteTo(outStream);
outStream.Flush();
outStream.Close();
}
}
string customUserControlName = (from DataRow row in objDataTable.Rows
where row["ACA_KEY"].ToString() == keys[0]
select row["ACA_CLASS_NAME"].ToString()).First();
return customUserControlName;
}
else
{
return null;
}
}
catch
{
return null;
}
}
The mithod basically copies the user controls to the virtual path at run time .
In aspx.cs page I try to load it dynamically .
But I can see the file is getting copied to the virtual path but this. Load control gives me exception saying Could not load type 'myCustomUserControl'.
I am using azure web role
What is wrong here ?
I solved the bug . I am just putting here for anyone to refer .
It's a one word change -
http://blog.kjeldby.dk/2008/11/dynamic-compilation-in-a-web-application/
Change
CodeBehind="myCustomUserControl.ascx.cs"
to
CodeFile="myCustomUserControl.ascx.cs"
Thanks to #Roopesh & #Kristoffer Brinch Kjeldby
and it will start working.