How to remove undefined array in asp.net? - c#

I am trying to select folder content
In that folder contain images when I am select that folder it will select all content.
plus it is taking img src undefind
so I need to remove that how can I remove if src is undefined using asp.net c#
<div id="cell" class="box2">
<a href="undefined">
<img width="260px" height="135px" src="undefined"
alt=""
style="box-shadow: 1px 2px 2px #BDBDBD;
border: 1px solid #D1D1D1;">
</img>
</a>
</div>
Code behind file:
protected void chbindustry_SelectedIndexChanged(object sender, EventArgs e)
{
if (result == false)
{
string[] subdirectoryEntries = Directory.GetDirectories(Server.MapPath("BusinessCards"));
string f;
string[] ss;
string side = chklist.SelectedValue;// RadioButtonList1.SelectedValue;
foreach (ListItem li in chbindustry.Items)
{
if (li.Selected)
{
ss = li.Text.Split('(');
f = Server.MapPath("BusinessCards").ToString() + "\\" + ss[0];
int c = f.Count();
DirectoryInfo d = new DirectoryInfo(f);
int len = d.GetFiles().Length;
for (int i = 1; i <= d.GetFiles().Length / 3; i++)
{
Page.ClientScript.RegisterArrayDeclaration("ImgPaths", "'" + "BusinessCards/" + f.Remove(0, f.LastIndexOf('\\') + 1) + "/" + i + ".jpg'");
Page.ClientScript.RegisterArrayDeclaration("refs", "'" + "DesignBCs.aspx?img=BusinessCards/" + f.Remove(0, f.LastIndexOf('\\') + 1) + "/" + i + "&Side=" + side + "'");
}
}
}
}
result = true;
}

Assuming you have a list of the image src values in C#, you could use LINQ to filter out any of them that are undefined:
var list = some code to get a list of img srcs from your folder;
list = list.Where(value => !string.IsNullOrWhitespace(value)).ToList();
The lambda value => !string.IsNullOrWhitespace(value) filters list such that each element is not null or whitespace (what I'm assuming you mean by undefined).
Does this help? If you can share some sample code of what you have now we can help more.

Related

Trying to Resolve error cs1010 newline in constant "string concat value is not appearing properly"

I' m trying to resolve error cs1010 newline in constant.
At this Line
if ((image1.Source==new BitmapImage(new Uri("ms-appx:///Assets/LearnColor/Object/ob_" + CI + "_" + LI + ".png", UriKind.Absolute))) &&(objNameWritten1.Text==objnamewritten[LI]))
The output is"ms-appx:///Assets/LearnColor/Object/ob_0"
but it should be
"ms-appx:///Assets/LearnColor/Object/ob_0_0"
Where is the Error Exactly
Cs code
private void common()
{
if (CI > 10)
{
CI = 0;
return;
}
if (HeaderName.Text== Headername[CI])
{
int LI = 0;
for (int i = 3*CI+LI; i < 3*(CI+1); LI++)
{
if ((image1.Source==new BitmapImage(new Uri("ms-appx:///Assets/LearnColor/Object/ob_" + CI + "_" + LI + ".png", UriKind.Absolute))) &&(objNameWritten1.Text==objnamewritten[LI]))
{
ppup.Height = Window.Current.Bounds.Height;
ppup.IsOpen = true;
CI++;
HeaderName.Text = Headername[CI];
common();
}
else if ((image2.Source == new BitmapImage(new Uri("ms-appx:///Assets/LearnColor/Object/ob_" + CI + "_" + LI + ".png"))) && (objNameWritten2.Text == objnamewritten[LI]))
{
ppup.Height = Window.Current.Bounds.Height;
ppup.IsOpen = true;
CI++;
HeaderName.Text = Headername[CI];
common();
}
else if ((image3.Source == new BitmapImage(new Uri("ms-appx:///Assets/LearnColor/Object/ob_" + CI + "_" + LI + ".png"))) && (objNameWritten3.Text == objnamewritten[LI]))
{
ppup.Height = Window.Current.Bounds.Height;
ppup.IsOpen = true;
CI++;
HeaderName.Text = Headername[CI];
common();
}
}
}
else
{
ppup1.Height = Window.Current.Bounds.Height;
ppup1.IsOpen = true;
}
I have tested your code on my side. There is nothing wrong with string concat. The uri result is ms-appx:///Assets/LearnColor/Object/ob_0_0.png which is right. Here is the screenshot of the result. You can also print out your concat result as following picture shows.
The error actually for your if condition is that you compare a BitmapImage with ImageSource in your code snippet. For judging whether the ImageSource is equal with one picture, you can use code as follows:
if((image1.Source as BitmapImage).UriSource== new Uri("ms-appx:///Assets/LearnColor/Object/ob_" + CI + "_" + LI + ".png", UriKind.Absolute))

Selenium C# - Finding div elements text by span element in it

I would like to get the text of <div> element.
The only thing I am able to use is <span> element inside this <div>.
<div>
<span id="lblName" class="fieldTitle">Name</span>
John
</div>
How can I receive John using lblName or Name?
You can use xpath
span = driver.findElement(By.id("lblName"));
div = span.findElement(By.xpath(".."));
You can try: //span[#id = 'lblName']/parent::div/text()
Something like this:
string xml = "<?xml version=\"1.0\"?>" +
"<div>" +
"<span id=\"lblName\" class=\"fieldTitle\">Name</span>" +
"</div>";
XDocument xdoc = XDocument.Parse(xml);
var parent = xdoc.Descendants().First(el => el.Name == "span" &&
el.Attribute("id") != null &&
el.Attribute("id").Value == "lblName").Parent;
You cannot get the text node by Selenium. Please try the workaround with JS below:
IWebElement span = driver.FindElement(By.Id("lblName"));
IWebElement div = span.FindElement(By.XPath(".."));
string script = "var nodes = arguments[0].childNodes;" +
"var text = '';" +
"for (var i = 0; i < nodes.length; i++) {" +
" if (nodes[i].nodeType == Node.TEXT_NODE) {" +
" text += nodes[i].textContent;" +
" }" +
"}" +
"return text;";
string text = driver.GetJavaScriptExecutor().ExecuteScript(script, div).ToString();

Update panel doesn't work in asp.net

I am trying to show online train in my page without any refresh. So I think I have to use updatepanel. My panel should be updated every second.
Let explain my code.
I put this part of code in my page:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="UpdatePanel1_Load">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
So I put an interval function to refresh my panel like this,
<script type="text/javascript">
$(function () {
setInterval("__doPostBack('<%=UpdatePanel1.ClientID%>', '');", 1000);
});
In my code behind I put all fetched data,
protected void UpdatePanel1_Load(object sender, EventArgs e)
{
foreach (var t in OnlineTrainList)
{
Response.Write("<div id='train-box' style='margin-left:" + (t.XTrainLocation - 8) + "px;margin-top:" + t.YTrainLocation + "px;background:" + t.Train.TrainColor + "'>" +
"<span>" +
t.TrainId +
"</span>" +
"</div>");
List<Sensor> PassedSensor = new List<Sensor>();
PassedSensor = SensorRepository.FindBy(i => i.CurrentTrainId == t.TrainId).ToList();
string color = TrainRepository.FindBy(i => i.Id == t.TrainId).First().TrainColor;
foreach (Sensor sensor in PassedSensor)
{
Response.Write("<div class='CurrentColor-Sensor' style='margin-left:" + (sensor.XLocation - 1) + "px;margin-top:" + (sensor.YLocation + 8) + "px;background:" + color + "'></div>");
}
}
}
So my problem is the panel doesn't refresh .And my panel UpdatePanel1_Load just call one time.
So your code is:
foreach (var t in OnlineTrainList)
{
Response.Write("<div id='train-box' style='margin-left:" + (t.XTrainLocation - 8) + "px;margin-top:" + t.YTrainLocation + "px;background:" + t.Train.TrainColor + "'>" +
"<span>" +
t.TrainId +
"</span>" +
"</div>");
List<Sensor> PassedSensor = new List<Sensor>();
PassedSensor = SensorRepository.FindBy(i => i.CurrentTrainId == t.TrainId).ToList();
string color = TrainRepository.FindBy(i => i.Id == t.TrainId).First().TrainColor;
foreach (Sensor sensor in PassedSensor)
{
Response.Write("<div class='CurrentColor-Sensor' style='margin-left:" + (sensor.XLocation - 1) + "px;margin-top:" + (sensor.YLocation + 8) + "px;background:" + color + "'></div>");
}
}
first thing i must bring your attention to the id that you assign to all those divs, it must be unique and never the same. you could use an increment variable and append it to your div's id eg: div0, div1... etc
now lets have a look at the first row inside the loop. what it basically has, is a <span> nested inside a <div> and containing some attributes with text.
the Asp.Net way of handling elements would be object oriented instead of just html string:
protected void UpdatePanel1_Load(object sender, EventArgs e)
{
//clear the update panel
UpdatePanel1.ContentTemplateContainer.Controls.Clear();
//var to generate unique div id's
int divIDIncrement = 0;
foreach (var t in OnlineTrainList)
{
//increment the id generator
divIDIncrement++;
// create a a DIV element
HtmlGenericControl _tempDIV = new HtmlGenericControl("div");
//set the attributes for the div
_tempDIV.ID = "train-box" + divIDIncrement.ToString();
_tempDIV.Style["margin-left"] = (t.XTrainLocation - 8).ToString() + "px";
_tempDIV.Style["margin-top"] = t.YTrainLocation.ToString() + "px";
_tempDIV.Style["background"] = t.Train.TrainColor.ToString();
//create the inner span
HtmlGenericControl _tempSPAN = new HtmlGenericControl("span");
//set the span's innerText
_tempSPAN.InnerText = t.TrainId.ToString();
//add the span into the Div
_tempDIV.Controls.Add(_tempSPAN);
//add the Div into your UpdatePanel
UpdatePanel1.ContentTemplateContainer.Controls.Add(_tempDIV);
List<Sensor> PassedSensor = new List<Sensor>();
PassedSensor = SensorRepository.FindBy(i => i.CurrentTrainId == t.TrainId).ToList();
string color = TrainRepository.FindBy(i => i.Id == t.TrainId).First().TrainColor;
foreach (Sensor sensor in PassedSensor)
{
// create another div for the sub stuff
HtmlGenericControl _tempSubDIV = new HtmlGenericControl("div");
_tempSubDIV.Attributes["class"] = "CurrentColor-Sensor";
_tempSubDIV.Style["margin-left"] = (sensor.XLocation - 1).ToString() + "px";
_tempSubDIV.Style["margin-top"] = (sensor.YLocation + 8).ToString() + "px";
_tempSubDIV.Style["background"] = color.ToString();
//add the sub stuff to the update panel
UpdatePanel1.ContentTemplateContainer.Controls.Add(_tempSubDIV);
}
}
}

ASP.NET How to use Counter with '<%=

I want to make a multiple upload, iam using some script from this forum.
the scripts is perfectly works, but when i merge it with my project.
javascript can't get the value of my element.
i found out the problem is because i have many ID PANEL in the page, i need to change to getElementByID('<%="FileUpdate.ClientID%>').value (the original : getElementByID("FileUpdate").value)
THE PROBLEM IS :
I have to use counter, ex: getElementByID('<%="txtFileUpdate' + counter + '%>').value but it FAIL.
the error says "too many characters in character literal" pointing to that line.
Please someone help, is there any solution for this problem ?
Here is the script
-----> Error " to many characters in character literal"
<script type="text/javascript" language="javascript">
var counter = 1;
function AddFileUpload() {
if (counter < 5) {
counter++;
var div = document.createElement('DIV');
div.innerHTML = '<input id="FileUpload' + counter + '" name = "file' + counter +
'" type="file" />' +
'<input id="Button' + counter + '" type="button" ' +
'value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainers").appendChild(div);
}
else {
alert("Cannot attach more than 5 file");
}
}
function GetFile() {
var temp;
var error = "";
var stringx = "";
var exCounter = 1 ;
for (exCounter; exCounter <= counter; exCounter++) {
-----> stringx = document.getElementById('<%=FileUpload'+exCounter+'.ClientID%>').value;
if (stringx != "")
temp += stringx + "#;";
else
error += exCounter + ", ";
}
if (error != "") {
alert("Field " + error + " Still Empty");
return;
}
document.getElementById('<%=HiddenField1.ClientID%>').value = temp;
}
Try this:
getElementByID('FileUpdate<%=counter%>').value
or
getElementByID('<%=txtFileUpdate + counter.ToString()%>').value

include button into .cs file

I'm trying to read a text file containing the name of the image, and display it opon pageload.
Let's say that the content in the text file is
Australia Picture101
Singapore Picture201
Following is the code i tried and it does not display the image.
tableString += "<table class='content_background' cellpadding='0' cellspacing='0'>";
foreach (string line in lines)
{
string[] country = line.Split(token2);
string[] image = country[1].Split(token);
string row = "<tr><td class='left_content'>" + country[0] + "</td>" +"<td><table><tr>";
tableString += row;
for (int i = 0; i < image.Length; i++)
{
---> string row2 = "<td class='right_content'> <asp:ImageButton ImageUrl='~/img/missing children pictures/" + "image[i]" + ".jpg'/>" + "</td>";
tableString += row2;
}
tableString += "</tr></table></td>";
}
tableString += "</tr></table>";
container.InnerHtml = tableString;
Is there any other way to do this ? Thanks in advance.
the screen shot is as follow
That's no button ! You're outputting non-parsed HTML - the ASP.NET engine does not parse that, it just sends the data as HTML to the client.
Instead, use
var btn = new ImageButton();
btn.ImageUrl = "~/img/missing children pictures/" + "image[i]" + ".jpg";
Panel1.Controls.Add(btn);
As an easy hack, you can use
string row2 = "<td class=\"right_content\"> <input type=\"button\" style=\"background:url('/img/missing%20children%20pictures/" + image[i] + ".jpg')\"/></td>";
If you want to generate HTML directly, then use HTML tags:
<a href="[Img_CLick Link]"><img src="[image path]"
alt="Click" border="0" /></a>
Put appropriate values in the square brackets.
Otherwise consider using asp:Table control and add rows/cells at run time.

Categories

Resources