how to make this better code and more optimized - asp.net

so i am displaying first letter of the each Name starting from A and all the way to Z
some thing like this:
A
Anthony
Allan
...
B
Bob
Builder
....
C
Charyl
Carl
...
Z
Zoah
....
how can i make this code more optimized and use less line?
int _a = 0;
int _b = 0;
int _c = 0;
...
...
..
int _z = 0;
protected void ListItem(List<Customer>.Enumerator cust)
{
if (cust.MoveNext())
{
Customer t = cust.Current;
string[] list = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "v", "z" };
var output = list.Aggregate("", (current, listitem) => current + (Environment.NewLine + "<h1 id='" + listitem.ToUpper() + "'><span>" + listitem.ToUpper() + "</span></h1>"));
string _name = t.Name.Substring(0, 1).ToUpper();
if (_name == list[0].ToUpper())
{
if (_a == 0)
{
l = new Literal();
l.Text = "<h1 id='A'><span>A</span></h1>" + Environment.NewLine;
.....
_a = 1;
}
if (_name == list[1].ToUpper())
{
if (_b == 0)
{
l = new Literal();
l.Text = "<h1 id='B'><span>A</span></h1>" + Environment.NewLine;
.....
_b = 1;
}
}
...
....
....
...
doing through Z
}

List<Customer> myList;
//produces a sequence of strings with the format:
//<h1 id="A"><span>A</span></h1>
//Anthony<br />
//...
var stringValues =
myList
.GroupBy(c => c.Name[0].ToUpper())
.OrderBy(g => g.Key)
.Select(g => string.Format(
"<h1 id=\"{0}\"><span>{0}</span></h1>{1}\n",
g.Key,
g.Aggregate("", (a,i) => string.Format(
"{0}<br />\n",
i.Name))));
foreach(var stringValue in stringValues)
{
var l = new Literal();
li.Text = stringValue;
//not sure what you're doing with the literal from here...
}

I will change the repeated code with this idea.
List<char> HeaderOf = new List<char>();
protected void ListItem(List<Customer>.Enumerator cust)
{
if (cust.MoveNext())
{
Customer t = cust.Current;
string[] list = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "v", "z" };
var output = list.Aggregate("", (current, listitem) => current + (Environment.NewLine + "<h1 id='" + listitem.ToUpper() + "'><span>" + listitem.ToUpper() + "</span></h1>"));
char CheckMe = t.Name.Substring(0, 1).ToUpper()[0];
if (!HeaderOf.Contains(CheckMe))
{
HeaderOf.Add(CheckMe);
l = new Literal();
l.Text = "<h1 id='" + CheckMe + "'><span>" + CheckMe + "</span></h1>" + Environment.NewLine;
}
}
}

Related

asp .Net Drop Down list returning first value the first time

Hello Im trying to remove a value from a List when it is selected in a Drop Down list but the first time i call Button1_Click1 it always removes the first index(in this case a) i have no idea what is going on
List<String> Alph = new List<String>();
protected void Page_Load(object sender, EventArgs e)
{
if ((List<String>)Session["Alpha"] != null)
{
Alph = (List<String>)Session["Alpha"];
}
else
{
fillAlpha();
}
}
public void fillAlpha()
{
Alph = new List<String>() { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
Alph.Sort();
DropDownList1.DataSource = Alph;
DropDownList1.DataBind();
}
protected void Button1_Click1(object sender, EventArgs e)
{
Label1.Text = DropDownList1.Text;
Alph.RemoveAt(DropDownList1.SelectedIndex);
DropDownList1.DataSource = Alph;
DropDownList1.DataBind();
Session["Alpha"] = Alph;
}
Page_Load is invoked on every post-back, and it's invoked before the click handler. So when you do this:
DropDownList1.DataSource = Alph;
DropDownList1.DataBind();
You're clobbering DropDownList1 and re-populating it. Then when you examine it:
Label1.Text = DropDownList1.Text;
Alph.RemoveAt(DropDownList1.SelectedIndex);
It's going to show you the default values, which means whatever is the first value in the data source to which it's bound.
You can prevent this by using a conditional to only populate it on an initial page load instead of post-back:
if (!IsPostBack)
{
DropDownList1.DataSource = Alph;
DropDownList1.DataBind();
}

LINQ query using Group By and Let

I have the below table,
Name Consumed
A Flavour 1
B Flavour 2
C Flavour 1
C Flavour 3
A Flavour 3
B Flavour 1
C Flavour 3
A Flavour 2
A Flavour 1
C Flavour 1
A Flavour 1
B Flavour 2
Where in the first column I have the name of the persons and in the second column the Flavour preferred by them. I want to generate the below table, with Flavours as columns and find the sum of the Flavours preferred by each person. I know the solution to these using SQL, however I'm looking for a solution using LINQ VB.Net.
Name Flavour 1 Flavour 2 Flavour 3
A 3 1 1
B 1 2 0
C 2 0 2
SQL Query for achieving the above result,
SELECT Name,
SUM(CASE WHEN Consumed='Flavour 1' THEN 1 ELSE 0) AS Flavour 1,
SUM(CASE WHEN Consumed='Flavour 2' THEN 1 ELSE 0) AS Flavour 2,
SUM(CASE WHEN Consumed='Flavour 3' THEN 1 ELSE 0) AS Flavour 3
GROUP BY Name
Below is the LINQ query,
Dim query = (From row In dtMain.AsEnumerable
Let Flavour_1 = IIf(row.Field(Of String)("Consumed") = "1", 1, 0)
Let Flavour_2 = IIf(row.Field(Of String)("Consumed") = "2", 1, 0)
Let Flavour_3 = IIf(row.Field(Of String)("Consumed") = "3", 1, 0)
Group row By Code = row.Field(Of String)("Name")
Into freq = Group Select .Code = Code, .Count = freq.Count()).ToList
My difficulty is in how to aggregate the temporary variables Flavour_1, Flavour_2 and Flavour_3 using SUM function and group it by Name.
Given the following data:
Dim table = {
New With { .Name = "A", .Consumed = "Flavor 1" },
New With { .Name = "B", .Consumed = "Flavor 2" },
New With { .Name = "C", .Consumed = "Flavor 1" },
New With { .Name = "C", .Consumed = "Flavor 3" },
New With { .Name = "A", .Consumed = "Flavor 3" },
New With { .Name = "B", .Consumed = "Flavor 1" },
New With { .Name = "C", .Consumed = "Flavor 3" },
New With { .Name = "A", .Consumed = "Flavor 2" },
New With { .Name = "A", .Consumed = "Flavor 1" },
New With { .Name = "C", .Consumed = "Flavor 1" },
New With { .Name = "A", .Consumed = "Flavor 1" },
New With { .Name = "B", .Consumed = "Flavor 2" }
}
the query you're looking for is:
Dim result = From e In table
Group e By Name = e.Name Into g = group
Select New With
{
.Name = Name,
.Flavour1 = g.Count(Function(x) x.Consumed = "Flavor 1"),
.Flavour2 = g.Count(Function(x) x.Consumed = "Flavor 2"),
.Flavour3 = g.Count(Function(x) x.Consumed = "Flavor 3")
}
It's quite similar to your SQL (group, then aggregate), but you use Count instead of SUM.
You don't need a Let.

Embedding rCharts graph into slidify slide deck

I am still trying to get a graph that I have produced using rCharts into a slidify slide deck. I have tried copying the script that rCharts produces into slidify's .Rmd file but all I get is an empty slide.
Here is the .Rmd file:
---
title : Test Sankey
subtitle :
author : Matthew
job :
framework : io2012 # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js # {highlight.js, prettify, highlight}
hitheme : tomorrow #
widgets : [d3_sankey] # {mathjax, quiz, bootstrap}
mode : selfcontained # {standalone, draft}
---
Slide 1
---
The graph should be on the next slide.
---
<div id='sankey1' class='rChart d3_sankey'></div>
<script>
(function(){
var params = {
"dom": "sankey1",
"width": 960,
"height": 500,
"data": {
"source": [ "a", "b", "c", "d", "e", "a", "d", "f", "e", "g", "h", "j", "j", "k", "l", "q" ],
"target": [ "j", "d", "a", "q", "f", "k", "e", "g", "j", "e", "l", "c", "h", "b", "d", "a" ],
"value": [ 8, 1, 4, 6, 2, 1, 1, 1, 6, 9, 2, 2, 4, 6, 9, 1 ]
},
"nodeWidth": 15,
"nodePadding": 10,
"layout": 32,
"id": "sankey1"
};
params.units ? units = " " + params.units : units = "";
//hard code these now but eventually make available
var formatNumber = d3.format("0,.0f"), // zero decimal places
format = function(d) { return formatNumber(d) + units; },
color = d3.scale.category20();
if(params.labelFormat){
formatNumber = d3.format(".2%");
}
var svg = d3.select('#' + params.id).append("svg")
.attr("width", params.width)
.attr("height", params.height);
var sankey = d3.sankey()
.nodeWidth(params.nodeWidth)
.nodePadding(params.nodePadding)
.layout(params.layout)
.size([params.width,params.height]);
var path = sankey.link();
var data = params.data,
links = [],
nodes = [];
//get all source and target into nodes
//will reduce to unique in the next step
//also get links in object form
data.source.forEach(function (d, i) {
nodes.push({ "name": data.source[i] });
nodes.push({ "name": data.target[i] });
links.push({ "source": data.source[i], "target": data.target[i], "value": +data.value[i] });
});
//now get nodes based on links data
//thanks Mike Bostock https://groups.google.com/d/msg/d3-js/pl297cFtIQk/Eso4q_eBu1IJ
//this handy little function returns only the distinct / unique nodes
nodes = d3.keys(d3.nest()
.key(function (d) { return d.name; })
.map(nodes));
//it appears d3 with force layout wants a numeric source and target
//so loop through each link replacing the text with its index from node
links.forEach(function (d, i) {
links[i].source = nodes.indexOf(links[i].source);
links[i].target = nodes.indexOf(links[i].target);
});
//now loop through each nodes to make nodes an array of objects rather than an array of strings
nodes.forEach(function (d, i) {
nodes[i] = { "name": d };
});
sankey
.nodes(nodes)
.links(links)
.layout(params.layout);
var link = svg.append("g").selectAll(".link")
.data(links)
.enter().append("path")
.attr("class", "link")
.attr("d", path)
.style("stroke-width", function (d) { return Math.max(1, d.dy); })
.sort(function (a, b) { return b.dy - a.dy; });
link.append("title")
.text(function (d) { return d.source.name + " → " + d.target.name + "\n" + format(d.value); });
var node = svg.append("g").selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; })
.call(d3.behavior.drag()
.origin(function (d) { return d; })
.on("dragstart", function () { this.parentNode.appendChild(this); })
.on("drag", dragmove));
node.append("rect")
.attr("height", function (d) { return d.dy; })
.attr("width", sankey.nodeWidth())
.style("fill", function (d) { return d.color = color(d.name.replace(/ .*/, "")); })
.style("stroke", function (d) { return d3.rgb(d.color).darker(2); })
.append("title")
.text(function (d) { return d.name + "\n" + format(d.value); });
node.append("text")
.attr("x", -6)
.attr("y", function (d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "end")
.attr("transform", null)
.text(function (d) { return d.name; })
.filter(function (d) { return d.x < params.width / 2; })
.attr("x", 6 + sankey.nodeWidth())
.attr("text-anchor", "start");
// the function for moving the nodes
function dragmove(d) {
d3.select(this).attr("transform",
"translate(" + (
d.x = Math.max(0, Math.min(params.width - d.dx, d3.event.x))
) + "," + (
d.y = Math.max(0, Math.min(params.height - d.dy, d3.event.y))
) + ")");
sankey.relayout();
link.attr("d", path);
}
})();
</script>
When I compile the .Rmd file in R I get the following output:
slidify("index.Rmd")
processing file: index.Rmd
|.................................................................| 100%
ordinary text without R code
output file: index.md
Copying files to libraries/frameworks/io2012...
Copying files to libraries/highlighters/highlight.js...
Copying files to libraries/widgets/d3_sankey...
[1] "index.html"
Any idea on what I am doing wrong here? Thank you very much!

Row Group Issue in Row Background Color

I have a Devexpress Xtragrid, with in which I grouped rows based on a particular column. I have given Dark blue back color to the Group and set ShowGroupExpandCollpaseButton as false as well. In the left most part of each child rows in the grid is displaying the color I set to the Group back color. Is there any way to remove this color?
To accomplish this task, please remove the BackColor from the GroupRow appearance.
Then use the CustomDrawGroupRow event to highlight the group row content as you need:
// 1) remove GroupRow style
//gridView1.Appearance.GroupRow.BackColor = Color.Blue;
gridView1.OptionsView.ShowGroupExpandCollapseButtons = false;
// 2) use the CusomDrawGroupRow
gridView1.CustomDrawGroupRow += gridView1_CustomDrawGroupRow;
}
void gridView1_CustomDrawGroupRow(object sender, RowObjectCustomDrawEventArgs e) {
GridView gridView = sender as GridView;
GridGroupRowInfo groupRowInfo = e.Info as GridGroupRowInfo;
string groupRowText = gridView.GetGroupRowDisplayText(e.RowHandle);
int textStart = groupRowInfo.DataBounds.Left + 4;
Rectangle groupRowTextBounds = new Rectangle(
textStart,
groupRowInfo.Bounds.Top,
groupRowInfo.Bounds.Right - textStart,
groupRowInfo.Bounds.Height
);
e.Cache.FillRectangle(Brushes.Blue, e.Bounds); // draw blue backgrownd
e.Appearance.DrawString(e.Cache, groupRowText, groupRowTextBounds);
e.Handled = true;
}
You should be able to hide the group from the view by setting as follows:
this.gridView1.OptionsView.ShowGroupedColumns = false;
Download the [project][1](https://drive.google.com/file/d/13XkT9qsqwFP-f2sPID70T2y2fSrs4Gp0/view?usp=sharing) or follow the below steps.
Grid:
Excel Download
Getdata
private DataTable getTestData()
{
///Step 1: Getdata from Db
DataTable dt = new DataTable();
dt.Columns.Add("GROUPCOLUMN");
dt.Columns.Add("PRODUCTGROUPID");
dt.Columns.Add("SIZEID");
dt.Columns.Add("SHAPEID");
dt.Columns.Add("COLORID");
dt.Columns.Add("CLARITYID");
dt.Columns.Add("CARAT", typeof(decimal));
dt.Columns.Add("QTY", typeof(Int32));
dt.Columns.Add("GROUPLEVEL", typeof(Int32));
dt.Columns.Add("AVGCARAT", typeof(decimal));
dt.Rows.Add("", "POLISH", "0.30-0.39", "BR", "D", "IF", 0.30, 1, 0, 0.30);
dt.Rows.Add("", "POLISH", "0.40-0.49", "BR", "D", "IF", 0.40, 1, 0, 0.30);
dt.Rows.Add("", "POLISH", "0.40-0.49", "BR", "D", "VVS1", 0.40, 1, 0, 0.30);
dt.Rows.Add("", "POLISH", "0.30-0.39", "BR", "D", "VVS2", 0.30, 1, 0, 0.30);
dt.Rows.Add("", "S.PRECIOUS", "0.30-0.39", "BR", "D", "IF", 0.30, 1, 0, 0.30);
dt.Rows.Add("", "S.PRECIOUS", "0.30-0.39", "BR", "D", "IF", 0.30, 1, 0, 0.30);
dt.Rows.Add("", "COLOR", "0.30-0.39", "BR", "D", "IF", 0.30, 1, 0, 0.30);
dt.Rows.Add("", "COLOR", "0.30-0.39", "BR", "D", "IF", 0.30, 1, 0, 0.30);
return dt;
}
Create GridView Event (gridView1_GroupLevelStyle) for displaying grid data color
private void gridView1_GroupLevelStyle(object sender, GroupLevelStyleEventArgs e)
{
///Step 2: Create GridView Event (gridView1_GroupLevelStyle) for displaying grid data color
e.LevelAppearance.ForeColor = getForeGroupColor(e.Level);
e.LevelAppearance.BackColor = getBackGroupColor(e.Level);
}
Create method getBackGroupColor(Group Index), getForeGroupColor(GroupIndex) in C# Code
public Color getBackGroupColor(Int32 groupLevel)
{
Color groupColor = Color.White;
if (groupLevel == 0)
{
groupColor = Color.Salmon;
}
else if (groupLevel == 1)
{
groupColor = Color.Green;
}}
Most Important Create Gridview Event (gridView1_CustomSummaryCalculate) and set group level into the GroupLevel Column SummaryItem(Follow the instruction as given the comment on to the method)
///Step 4: Most Important Create Gridview Event (gridView1_CustomSummaryCalculate) and set group level into the GroupLevel Column SummaryItem(Follow the instruction as given the comment on to the method)
private void gridView1_CustomSummaryCalculate(object sender, DevExpress.Data.CustomSummaryEventArgs e)
{
if (e.IsGroupSummary)
{
switch (e.SummaryProcess)
{
case CustomSummaryProcess.Start:
break;
case CustomSummaryProcess.Calculate:
break;
case CustomSummaryProcess.Finalize:
if (((DevExpress.XtraGrid.GridSummaryItem)e.Item).FieldName == "GROUPLEVEL")
{
///set Group level into the grouplevel summary
e.TotalValue = e.GroupLevel;
}
break;
}
}
}
Create button for export grid data and write code as writen into the method
Like
try
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel Workbook|*.xlsx|Excel 97-2003 Workbook|*.xls";
saveFileDialog1.Title = "Save an Excel File";
saveFileDialog1.FileName = String.Format("Test_{0}.xlsx", DateTime.Now.ToString("ddMMMyyyyhhmmss"));
DialogResult res = saveFileDialog1.ShowDialog();
if (res == DialogResult.Cancel)
return;
XlsxExportOptionsEx exportOptions = new XlsxExportOptionsEx();
exportOptions.CustomizeCell += exportOptions_CustomizeCell;
this.gridView1.ExportToXlsx(saveFileDialog1.FileName, exportOptions);
System.Diagnostics.Process.Start(saveFileDialog1.FileName);
}
catch (Exception ex)
{ }
Create Method(Event) exportOptions_CustomizeCell
private void exportOptions_CustomizeCell(CustomizeCellEventArgs e)
{
if (e.RowHandle < 0)
{
///Export excel set Group color
DevExpress.XtraGrid.GridGroupSummaryItem SummaryItem = this.gridView1.GroupSummary.Where(x => x.FieldName == "GROUPLEVEL").ToList()[0] as DevExpress.XtraGrid.GridGroupSummaryItem;
Int32 groupLevel = Convert.ToInt32(this.gridView1.GetGroupSummaryValue(e.RowHandle, SummaryItem));
e.Formatting.BackColor = getBackGroupColor(groupLevel);
}
///Set Header Column setting(BackColor, ForeColor, Font Style)
else if (e.DataSourceRowIndex == -1)
{
e.Formatting.BackColor = Color.Black;
e.Formatting.Font.Color = Color.White;
e.Formatting.Font.Italic = true;
}
e.Handled = true;
}

ASP.NET MVC URL routing and paging with HTMLHelper

I have a route
routes.MapRoute(
"AlphaPagedContacts", // Route name
"Contact/Alpha{alpha}", // URL with parameters
new { controller = "Contact", action = "AlphaList", alpha = UrlParameter.Optional },
new { alpha = #"\A-Z" } // Parameter defaults
);
I'm trying to make the URL's display like
/Contact/AlphaA
/Contact/AlphaB
for contacts based on username. However, the URL's are showing up as: http://localhost:54568/Contact/AlphaList?alpha=H
My HTMLHelper is
#Html.AlphaLinks(new PagingModel { MaxPages = Model.MaxPages, CurrentLetter = Model.CurrentLetter, UrlGeneratorFunctionAlpha = i => Url.Action("AlphaList", new { alpha = i }) })
and my implementation is
public static MvcHtmlString AlphaLinks(this HtmlHelper helper, PagingModel model)
{
string[] letters = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
var stringBuilder = new StringBuilder("<ul class='pager'>");
foreach (string letter in letters)
{
stringBuilder.Append(String.Format("<li {2}><a href='{1}'>{0}<a></li>", letter, model.UrlGeneratorFunctionAlpha(letter), letter == model.CurrentLetter ? "class=Selected" : String.Empty));
}
stringBuilder.Append("</ul>");
return MvcHtmlString.Create(stringBuilder.ToString());
}
My controller code for the actionresult is:
public ActionResult AlphaList(string alpha = "A")
{
var logic = new ContactBUS();
var pageSize = 10;
var usernames = from c in XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Contacts.xml")).Elements("Contact")
select new
{
Username = (string)c.Element("Username"),
Lastname = (string)c.Element("LastName"),
Firstname = (string)c.Element("FirstName"),
Email = (string)c.Element("Email"),
};
var model = new AlphaListContactViewModel
{
Contacts = logic.GetContacts().Skip(0).Take(20).ToList(),
CurrentLetter = alpha,
MaxPages = (int)Math.Ceiling(logic.GetContactsCount() / (double)pageSize)
};
return View(model);
}
Any idea why this is happening?
Also, I need to make it so that when the user clicks on a letter, it shows the contacts' usernames for that letter.
Any help would be greatly appreciated.
Do you have any other routes that come before the one we see here? The first route that matches wins.

Resources