iterate through menustrip dropdownitem - c#

How to iterate through all ToolStripMenuItem in a MenuStrip
con.connection3.Open();
string query = "SELECT * FROM tblrole WHERE role = ?role";
using (MySqlCommand cmd3 = new MySqlCommand(query,con.connection3))
{
cmd3.Parameters.AddWithValue("?role", roled);
using (MySqlDataReader mdr = cmd3.ExecuteReader())
{
while (mdr.Read())
{
for (int o = 0, i = 2; o < fileMaintenanceToolStripMenuItem.DropDownItems.Count; o++, i++)
{
fileMaintenanceToolStripMenuItem.DropDownItems[o].Visible = mdr.GetBoolean(i);
}
for (int o = 0, i = 19; o < transactionToolStripMenuItem.DropDownItems.Count; o++, i++)
{
transactionToolStripMenuItem.DropDownItems[o].Visible = mdr.GetBoolean(i);
}
for (int o = 0, i = 45; o < reportsToolStripMenuItem.DropDownItems.Count; o++, i++)
{
reportsToolStripMenuItem.DropDownItems[o].Visible = mdr.GetBoolean(i);
}
for (int o = 0, i = 55; o < utilitiesToolStripMenuItem.DropDownItems.Count; o++, i++)
{
utilitiesToolStripMenuItem.DropDownItems[o].Visible = mdr.GetBoolean(i);
}
if (!fileMaintenanceToolStripMenuItem.HasDropDownItems)fileMaintenanceToolStripMenuItem.Visible = false;
else fileMaintenanceToolStripMenuItem.Visible = true;
if (!transactionToolStripMenuItem.HasDropDownItems)transactionToolStripMenuItem.Visible = false;
else transactionToolStripMenuItem.Visible = true;
if (!reportsToolStripMenuItem.HasDropDownItems)reportsToolStripMenuItem.Visible = false;
else reportsToolStripMenuItem.Visible = true;
if (!utilitiesToolStripMenuItem.HasDropDownItems) utilitiesToolStripMenuItem.Visible = false;
else utilitiesToolStripMenuItem.Visible = true;
}
}
}
con.connection3.Close();
Works fine if the ToolStripMenuItem has no subitems but I need to iterate through them also

You can use a recursive method as a good option for traversing a tree structure. Here is an extension method that you can use for listing ToolStripMenuItem descendants of a given ToolStripMenuItem:
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
public static class ToolStripMenuItemExtensions
{
public static List<ToolStripMenuItem> Descendants(this ToolStripMenuItem item)
{
var items = item.DropDownItems.OfType<ToolStripMenuItem>().ToList();
return items.SelectMany(x => Descendants(x)).Concat(items).ToList();
}
}
It will add Descendants to ToolStripMenuItem elements, so you can use it this way:
var allMenuItems = fileMaintenanceToolStripMenuItem.Descendants();

Related

How to insert to database in bulk instead of inserting it 1 by 1

How do you make the list receives more than 1 value based on the quantity of the SelectedList.Count.
Code:
for (int i = 0; i < SelectedList.Count; i++)
{
lastSeriesNo++;
string assetcodegen = string.Format("{0}-{1}-{2}", List[i].AssetCategoryID, CurrentApplication.Now.Year, lastSeriesNo.ToString().PadLeft(5, '0'));
AssetCodeOfficial[i] = assetcodegen;
var list = (from x in ctx.DataContext.AssetRegistryEntities
where x.AssetCode == SelectedList[i].AssetCode
select x
).AsEnumerable();
foreach (var asset in list)
{
asset.SeriesNumber = (short)lastSeriesNo;
asset.Status = 'A';
asset.IsTemp = false;
asset.UpdatedBy = CurrentApplication.CurrentUserId;
asset.UpdatedDate = asset.AssetCreatedDate = CurrentApplication.Now;
AssetCodetemp[i] = asset.AssetCode;
depreciationInMonths = asset.DepnInMonths;
ctx.DataContext.SubmitChanges();
}
}
Thank you all guys for the help, I manage to fix my problem. It already saves the data to the database as bulk not 1 by 1 saving.
So I use lambda expression for my list and use the .addRange to add item to the list.
list.AddRange(ctx.DataContext.AssetRegistryEntities.Where(x=>x.AssetCode.Trim() == SelectedList[i].AssetCode.Trim()));
Code:
List<NXpert.FixedAsset.DataAccess.AssetRegistryEntity> list = new List<NXpert.FixedAsset.DataAccess.AssetRegistryEntity>();
for (int i = 0; i < SelectedList.Count; i++)
{
lastSeriesNo++;
string assetcodegen = string.Format("{0}-{1}-{2}", List[i].AssetCategoryID, CurrentApplication.Now.Year, lastSeriesNo.ToString().PadLeft(5, '0'));
AssetCodeOfficial[i] = assetcodegen;
list.AddRange(ctx.DataContext.AssetRegistryEntities.Where(x=>x.AssetCode.Trim() == SelectedList[i].AssetCode.Trim()));
AssetCodetemp[i] = list[i].AssetCode;
}
foreach (var asset in list)
{
asset.SeriesNumber = (short)lastSeriesNo;
asset.Status = 'A';
asset.IsTemp = false;
asset.UpdatedBy = CurrentApplication.CurrentUserId;
asset.UpdatedDate = asset.AssetCreatedDate = CurrentApplication.Now;
depreciationInMonths = asset.DepnInMonths;
}
ctx.DataContext.SubmitChanges();

Make Code Fast Execute - replace For loops

It takes lot of time to execute these loops due to for loop implementation
How can I replace it to be more fast, the under laying table do not have much records too, plus I have made the primary keys too , but still the for loops are slow
public List<BusinessLayer.Transactions.CDANumberTracking> GetPOUnusedCDANumberTrackingItems(string code)
{
List<BusinessLayer.Transactions.CDANumberTracking> results = new List<BusinessLayer.Transactions.CDANumberTracking>();
List<Entity.Transactions.CDANumberTracking> SoUsedBagList = new List<Entity.Transactions.CDANumberTracking>();
List<Entity.Transactions.POCDANumberTracking> rejects = new List<SalesOrderModule.Entity.Transactions.POCDANumberTracking>();
List<Entity.Transactions.POCDANumberTracking> returns = new List<SalesOrderModule.Entity.Transactions.POCDANumberTracking>();
List<Entity.Transactions.POCDANumberTracking> rejectList = new List<SalesOrderModule.Entity.Transactions.POCDANumberTracking>();
List<Entity.Transactions.POCDANumberTracking> returnRejectList = new List<SalesOrderModule.Entity.Transactions.POCDANumberTracking>();
List<Entity.Transactions.POCDANumberTracking> SearchList = new List<SalesOrderModule.Entity.Transactions.POCDANumberTracking>();
try
{
if (!InOpenLookup)
(Connection as SQL).BeginTransaction();
DataLayer.Tables.PLSPOCDANumberTrackingDNew sampleTable = new SalesOrderModule.DataLayer.Tables.PLSPOCDANumberTrackingDNew(this.Connection);
sampleTable.SearchCriteria[0].Value = code.Trim();
sampleTable.SearchCriteria[1].Value = (int)0;
List<Entity.Transactions.POCDANumberTracking> results1 = sampleTable.Reads(false);
if (results1.Count > 0)
{
rejectList.AddRange(results1);
}
DataLayer.Tables.PLSPOCDANumberTrackingReturnD sampleTable2 = new SalesOrderModule.DataLayer.Tables.PLSPOCDANumberTrackingReturnD(this.Connection);
sampleTable2.SearchCriteria[0].Value = code.Trim();
List<Entity.Transactions.POCDANumberTracking> results2 = sampleTable2.Reads(false);
if (results2.Count > 0)
{
returnRejectList.AddRange(results2);
}
DataLayer.Tables.PLSPOCDANumberTrackingD sampleTable3 = new SalesOrderModule.DataLayer.Tables.PLSPOCDANumberTrackingD(this.Connection);
sampleTable3.SearchCriteria[0].Value = code.Trim();
SearchList = sampleTable3.Reads(false);
DataLayer.Tables.PSOMCDANumberTrackingD sampleTable4 = new SalesOrderModule.DataLayer.Tables.PSOMCDANumberTrackingD(this.Connection, null);
sampleTable4.SearchCriteria[3].Value = code.Trim();
sampleTable4.SearchCriteria[6].Value = false;
SoUsedBagList = sampleTable4.Read(false);
//process data...
Entity.Transactions.POCDANumberTracking temp;
foreach (Entity.Transactions.POCDANumberTracking rejectItem in rejectList)
{
for (int i = rejectItem.From; i <= rejectItem.To; i++)
{
temp = new SalesOrderModule.Entity.Transactions.POCDANumberTracking();
temp.From = i;
temp.To = i;
temp.Code = rejectItem.Code.Trim();
temp.GrnNo = rejectItem.GrnNo.Trim();
temp.WbcNo = rejectItem.WbcNo.Trim();
rejects.Add(temp);
}
}
//returns
foreach (Entity.Transactions.POCDANumberTracking returnItem in returnRejectList)
{
for (int i = returnItem.From; i <= returnItem.To; i++)
{
temp = new SalesOrderModule.Entity.Transactions.POCDANumberTracking();
temp.From = i;
temp.To = i;
temp.Code = returnItem.Code.Trim();
temp.GrnNo = returnItem.GrnNo.Trim();
temp.WbcNo = returnItem.WbcNo.Trim();
returns.Add(temp);
}
}
Entity.Transactions.CDANumberTracking temp2;
Entity.Transactions.CDANumberTracking temp3;
Entity.Transactions.POCDANumberTracking temp4;
foreach (Entity.Transactions.POCDANumberTracking searchItem in SearchList)
{
for (int i = searchItem.From; i <= searchItem.To; i++)
{
temp = null;
temp3 = null;
temp4 = null;
//check if the bag is on reject list
temp = rejects.Find(delegate(Entity.Transactions.POCDANumberTracking tc) { return (tc.From == i && tc.WbcNo.Trim().ToUpper() == searchItem.WbcNo.Trim().ToUpper() && tc.GrnNo.Trim().ToUpper() == searchItem.GrnNo.Trim().ToUpper()); });
if (temp != null)
continue;
//check if the bag is on return list
temp4 = returns.Find(delegate(Entity.Transactions.POCDANumberTracking tcc) { return (tcc.From == i && tcc.GrnNo.Trim().ToUpper() == searchItem.GrnNo.Trim().ToUpper()); });
if (temp4 != null)
continue;
//check if the bag is alredy used in So module...
temp3 = SoUsedBagList.Find(delegate(Entity.Transactions.CDANumberTracking cda) { return (cda.Code.Trim().ToUpper() == searchItem.Code.Trim().ToUpper() && cda.BagNo == searchItem.From); });
if (temp3 != null)
continue;
temp2 = new SalesOrderModule.Entity.Transactions.CDANumberTracking();
temp2.BagNo = i;
temp2.Code = searchItem.Code.Trim();
temp2.LineNo = 0;
temp2.Location = string.Empty;
temp2.WbcNo = string.Empty;
temp2.ID = null;
temp2.IsReturned = false;
temp2.IsSelected = false;
temp2.ItemNo = string.Empty;
temp2.Status = SalesOrderModule.Entity.ModifyStatus.New;
results.Add(BusinessLayer.Transactions.CDANumberTracking.GetCDANumberTracking(this, temp2, null));
}
}
if (!InOpenLookup)
(Connection as SQL).EndTransaction();
}
catch (Exception er)
{
if (!InOpenLookup)
(Connection as SQL).Rollback();
throw er;
}
return results;
}
the for loop under second for each need to placed ... need some help
You should factor out of the inner loop everything you can. As the code stands right now, you are unecessarily repeating the following operations:
returnItem.Code.Trim();
returnItem.GrnNo.Trim();
returnItem.WbcNo.Trim();
I have nowhere near enough information to judge if this will have any performance impact.
Other suspects are new SalesOrderModule.Entity.Transactions.POCDANumberTracking() and returns.Add(temp). If returns is somekind of ordered list, then this could have a considerable performance hit. If its a simple List then it shouldn't and there isn't much you could do to improve it anyways.
Concerning the constructor, only you know how expensive it is but there is not much you can do to avoid it either.
All that said, your code would look something like this:
Entity.Transactions.POCDANumberTracking temp;
foreach (Entity.Transactions.POCDANumberTracking returnItem in returnRejectList)
{
var code = returnItem.Code.Trim();
var grnNo = returnItem.GrnNo.Trim();
var wbcNo = returnItem.WbcNo.Trim();
for (int i = returnItem.From; i <= returnItem.To; i++)
{
temp = new SalesOrderModule.Entity.Transactions.POCDANumberTracking();
temp.From = i;
temp.To = i;
temp.Code = code;
temp.GrnNo = grnNo;
temp.WbcNo = wbcNo;
returns.Add(temp);
}
}
I have to limit the entries coming under the foreach loops, that is best way by debugging the code
so the data layer codes referring in the
sampleTable.Reads(false);
sampleTable2.Reads(false);
sampleTable3.Reads(false);
sampleTable4.Reads(false);
need to modified by including the Item for search (I mean the SQL STATEMENTS)

GDAL pct2rgb.py in C# returns monochromatic dataset

I try to rewrite pct2rgb.py script into C# (this script gets 8-bit TIFF image and changes the bit depth of it into 24-bit). It worked when its output was stored on the HDD. I want to change the script a little. It should return Dataset on-the-fly w/o storing it on the disk. It works... Almost... The problem is that the returned Dataset contains monochromatic data... I don't really know why. Maybe it's caused by the change of a driver from GTiff to MEM (Driver gTiffDriver = Gdal.GetDriverByName("MEM");). But I don't know how to use GTiff driver and not to store the data on the HDD...
Here's my class:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using OSGeo.GDAL;
using OSGeo.OGR;
using OSGeo.OSR;
using Driver = OSGeo.GDAL.Driver;
using Encoder = System.Drawing.Imaging.Encoder;
using PixelFormat = System.Drawing.Imaging.PixelFormat;
namespace RasterLoader
{
public class TiffConverter
{
private string _format = "GTiff";
private string _srcFileName = null;
private int _outBands = 3;
private int _bandNumber = 1;
private string[] _args;
public TiffConverter(string[] args)
{
_args = args;
}
public Dataset Convert8To24Bit()
{
Gdal.AllRegister();
string[] argv = Gdal.GeneralCmdLineProcessor(_args, 0);
int i = 1;
while (i < argv.Count())
{
string arg = argv.ElementAt(i);
switch (arg)
{
case "-of":
i++;
_format = argv[i];
break;
case "-b":
i++;
_bandNumber = int.Parse(argv[i]);
break;
case "-rgba":
_outBands = 4;
break;
default:
if (string.IsNullOrEmpty(_srcFileName))
{
_srcFileName = argv[i];
}
else
{
Usage();
}
break;
}
i++;
}
string tmpFileName = _srcFileName + ".bak";
// open source file
Dataset srcDS = Gdal.Open(_srcFileName, Access.GA_ReadOnly);
if (srcDS == null)
{
throw new Exception("Unable to open " + _srcFileName + ".");
}
Band srcBand = srcDS.GetRasterBand(_bandNumber);
// ensure we recognise the driver
Driver dstDriver = Gdal.GetDriverByName(_format);
if (dstDriver == null)
{
throw new Exception("\"" + _format + "\" not registered.");
}
// build color table
int[][] lookup = new int[4][];
lookup[0] = Enumerable.Range(0, 256).ToArray();
lookup[1] = Enumerable.Range(0, 256).ToArray();
lookup[2] = Enumerable.Range(0, 256).ToArray();
lookup[3] = new int[256];
for (i = 0; i < 256; i++)
{
lookup[3][i] = 255;
}
ColorTable ct = srcBand.GetRasterColorTable();
if (ct != null)
{
for (i = 0; i < Math.Min(256, ct.GetCount()); i++)
{
ColorEntry entry = ct.GetColorEntry(i);
for (int j = 0; j < 4; j++)
{
switch (j)
{
case 0:
lookup[j][i] = entry.c1;
break;
case 1:
lookup[j][i] = entry.c2;
break;
case 2:
lookup[j][i] = entry.c3;
break;
case 3:
lookup[j][i] = entry.c4;
break;
}
}
}
}
// create the working file
string tifFileName = string.Empty;
if (_format.Equals("GTiff", StringComparison.OrdinalIgnoreCase))
{
tifFileName = tmpFileName;
}
else
{
tifFileName = Path.Combine(Directory.GetParent(tmpFileName).Name, "temp.gif");
}
// Driver gTiffDriver = Gdal.GetDriverByName("GTiff");
Driver gTiffDriver = Gdal.GetDriverByName("MEM");
Dataset tifDS = gTiffDriver.Create(tifFileName, srcDS.RasterXSize, srcDS.RasterYSize, _outBands, DataType.GDT_Byte,
new string[] {});
// we should copy projection information and so forth at this point
tifDS.SetProjection(srcDS.GetProjection());
double[] geotransform = new double[6];
srcDS.GetGeoTransform(geotransform);
tifDS.SetGeoTransform(geotransform);
if (srcDS.GetGCPCount() > 0)
{
tifDS.SetGCPs(srcDS.GetGCPs(), srcDS.GetGCPProjection());
}
// do the processing one scanline at a time
for (int iY = 0; iY < srcDS.RasterYSize; iY++)
{
byte[] srcData = new byte[srcDS.RasterXSize*1];
srcBand.ReadRaster(0, iY, srcDS.RasterXSize, 1, srcData, srcDS.RasterXSize, 1, 0, 0);
for (int iBand = 0; iBand < _outBands; iBand++)
{
int[] bandLookup = lookup[iBand];
int[] dstData = new int[srcData.Count()];
for (int index = 0; index < srcData.Count(); index++)
{
byte b = srcData[index];
dstData[index] = bandLookup[b];
}
tifDS.GetRasterBand(iBand + 1).WriteRaster(0, iY, srcDS.RasterXSize, 1, dstData,
srcDS.RasterXSize, 1, 0, 0);
}
}
return tifDS;
}
private void Usage()
{
Console.WriteLine("Usage: pct2rgb.py [-of format] [-b <band>] [-rgba] source_file dest_file");
throw new Exception("Bad arguments.");
}
}
Ok. I found a solution. My problem was I tried to convert all the files (even in a good format). Then ct variable (ColorTable) was null.
Solution:
if (ct != null)
{
// same code here
}
else
{
return srcDS;
}

What C# template engine that has clean separation between HTML and control code?

What C# template engine
that uses 'pure' HTML having only text and markers
sans any control flow like if, while, loop or expressions,
separating html from control code ?
Below is the example phone book list code,
expressing how this should be done:
string html=#"
<html><head><title>#title</title></head>
<body>
<table>
<tr>
<td> id</td> <td> name</td> <td> sex</td> <td>phones</td>
</tr><!--#contacts:-->
<tr>
<td>#id</td> <td>#name</td> <td>#sex</td>
<td>
<!--#phones:-->#phone <br/>
<!--:#phones-->
</td>
</tr><!--:#contacts-->
</table>
</body>
</html>";
var contacts = from c in db.contacts select c;
Marker m = new Marker(html);
Filler t = m.Mark("title");
t.Set("Phone book");
Filler c = m.Mark("contacts", "id,name,sex");
// **foreach** expressed in code, not in html
foreach(var contact in contacts) {
int id = contact.id;
c.Add(id, contact.name, contact.sex);
Filler p = c.Mark("phones", "phone");
var phones = from ph in db.phones
where ph.id == id
select new {ph.phone};
if (phones.Any()) {
foreach(var ph in phones) {
p.Add(ph);
}
} else {
fp.Clear();
}
}
Console.Out.WriteLine(m.Get());
Use this code:
Templet.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace templaten.com.Templaten
{
public class tRange
{
public int head, toe;
public tRange(int _head, int _toe)
{
head = _head;
toe = _toe;
}
}
public enum AType
{
VALUE = 0,
NAME = 1,
OPEN = 2,
CLOSE = 3,
GROUP = 4
}
public class Atom
{
private AType kin;
private string tag;
private object data;
private List<Atom> bag;
public Atom(string _tag = "",
AType _kin = AType.VALUE,
object _data = null)
{
tag = _tag;
if (String.IsNullOrEmpty(_tag))
_kin = AType.GROUP;
kin = _kin;
if (_kin == AType.GROUP)
bag = new List<Atom>();
else
bag = null;
data = _data;
}
public AType Kin
{
get { return kin; }
}
public string Tag
{
get { return tag; }
set { tag = value; }
}
public List<Atom> Bag
{
get { return bag; }
}
public object Data
{
get { return data; }
set { data = value; }
}
public int Add(string _tag = "",
AType _kin = AType.VALUE,
object _data = null)
{
if (bag != null)
{
bag.Add(new Atom(_tag, _kin, _data));
return bag.Count - 1;
}
else
{
return -1;
}
}
}
public class Templet
{
private string content;
string namepat = "\\w+";
string justName = "(\\w+)";
string namePre = "#";
string namePost = "";
string comment0 = "\\<!--\\s*";
string comment1 = "\\s*--\\>";
private Atom tokens; // parsed contents
private Dictionary<string, int> iNames; // name index
private Dictionary<string, tRange> iGroups; // groups index
private Atom buffer; // output buffer
private Dictionary<string, int> _iname; // output name index
private Dictionary<string, tRange> _igroup; // output index
public Templet(string Content = null)
{
Init(Content);
}
private int[] mark(string[] names, string group)
{
if (names == null || names.Length < 1) return null;
tRange t = new tRange(0, buffer.Bag.Count - 1);
if (group != null)
{
if (!_igroup.ContainsKey(group)) return null;
t = _igroup[group];
}
int[] marks = new int[names.Length];
for (int i = 0; i < marks.Length; i++)
marks[i] = -1;
for (int i = t.head; i <= t.toe; i++)
{
if (buffer.Bag[i].Kin == AType.NAME)
{
for (int j = 0; j < names.Length; j++)
{
if (String.Compare(
names[j],
buffer.Bag[i].Tag,
true) == 0)
{
marks[j] = i;
break;
}
}
}
}
return marks;
}
public Filler Mark(string group, string names)
{
Filler f = new Filler(this, names);
f.di = mark(f.names, group);
f.Group = group;
tRange t = null;
if (_igroup.ContainsKey(group)) t = _igroup[group];
f.Range = t;
return f;
}
public Filler Mark(string names)
{
Filler f = new Filler(this, names);
f.di = mark(f.names, null);
f.Group = "";
f.Range = null;
return f;
}
public void Set(int[] locations, object[] x)
{
int j = Math.Min(x.Length, locations.Length);
for (int i = 0; i < j; i++)
{
int l = locations[i];
if ((l >= 0) && (buffer.Bag[l] != null))
buffer.Bag[l].Data = x[i];
}
}
public void New(string group, int seq = 0)
{
// place new group copied from old group just below it
if (!( iGroups.ContainsKey(group)
&& _igroup.ContainsKey(group)
&& seq > 0)) return;
tRange newT = null;
tRange t = iGroups[group];
int beginRange = _igroup[group].toe + 1;
for (int i = t.head; i <= t.toe; i++)
{
buffer.Bag.Insert(beginRange,
new Atom(tokens.Bag[i].Tag,
tokens.Bag[i].Kin,
tokens.Bag[i].Data));
beginRange++;
}
newT = new tRange(t.toe + 1, t.toe + (t.toe - t.head + 1));
// rename past group
string pastGroup = group + "_" + seq;
t = _igroup[group];
buffer.Bag[t.head].Tag = pastGroup;
buffer.Bag[t.toe].Tag = pastGroup;
_igroup[pastGroup] = t;
// change group indexes
_igroup[group] = newT;
}
public void ReMark(Filler f, string group)
{
if (!_igroup.ContainsKey(group)) return;
Map(buffer, _iname, _igroup);
f.di = mark(f.names, group);
f.Range = _igroup[group];
}
private static void Indexing(string aname,
AType kin,
int i,
Dictionary<string, int> dd,
Dictionary<string, tRange> gg)
{
switch (kin)
{
case AType.NAME: // index all names
dd[aname] = i;
break;
case AType.OPEN: // index all groups
if (!gg.ContainsKey(aname))
gg[aname] = new tRange(i, -1);
else
gg[aname].head = i;
break;
case AType.CLOSE:
if (!gg.ContainsKey(aname))
gg[aname] = new tRange(-1, i);
else
gg[aname].toe = i;
break;
default:
break;
}
}
private static void Map(Atom oo,
Dictionary<string, int> dd,
Dictionary<string, tRange> gg)
{
for (int i = 0; i < oo.Bag.Count; i++)
{
string aname = oo.Bag[i].Tag;
Indexing(oo.Bag[i].Tag, oo.Bag[i].Kin, i, dd, gg);
}
}
public void Init(string Content = null)
{
content = Content;
tokens = new Atom("", AType.GROUP);
iNames = new Dictionary<string, int>();
iGroups = new Dictionary<string, tRange>();
// parse content into tokens
string namePattern = namePre + namepat + namePost;
string patterns =
"(?<var>" + namePattern + ")|" +
"(?<head>" + comment0 + namePattern + ":" + comment1 + ")|" +
"(?<toe>" + comment0 + ":" + namePattern + comment1 + ")";
Regex jn = new Regex(justName, RegexOptions.Compiled);
Regex r = new Regex(patterns, RegexOptions.Compiled);
MatchCollection ms = r.Matches(content);
int pre = 0;
foreach (Match m in ms)
{
tokens.Add(content.Substring(pre, m.Index - pre));
int idx = -1;
if (m.Groups.Count >= 3)
{
string aname = "";
MatchCollection x = jn.Matches(m.Value);
if (x.Count > 0 && x[0].Groups.Count > 1)
aname = x[0].Groups[1].ToString();
AType t = AType.VALUE;
if (m.Groups[1].Length > 0) t = AType.NAME;
if (m.Groups[2].Length > 0) t = AType.OPEN;
if (m.Groups[3].Length > 0) t = AType.CLOSE;
if (aname.Length > 0)
{
tokens.Add(aname, t);
idx = tokens.Bag.Count - 1;
}
Indexing(aname, t, idx, iNames, iGroups);
}
pre = m.Index + m.Length;
}
if (pre < content.Length)
tokens.Add(content.Substring(pre, content.Length - pre));
// copy tokens into buffer
buffer = new Atom("", AType.GROUP);
for (int i = 0; i < tokens.Bag.Count; i++)
buffer.Add(tokens.Bag[i].Tag, tokens.Bag[i].Kin);
// initialize index of output names
_iname = new Dictionary<string, int>();
foreach (string k in iNames.Keys)
_iname[k] = iNames[k];
// initialize index of output groups
_igroup = new Dictionary<string, tRange>();
foreach (string k in iGroups.Keys)
{
tRange t = iGroups[k];
_igroup[k] = new tRange(t.head, t.toe);
}
}
public string Get()
{
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < buffer.Bag.Count; i++)
{
switch (buffer.Bag[i].Kin)
{
case AType.VALUE:
sb.Append(buffer.Bag[i].Tag);
break;
case AType.NAME:
sb.Append(buffer.Bag[i].Data);
break;
case AType.OPEN:
case AType.CLOSE:
break;
default: break;
}
}
return sb.ToString();
}
}
public class Filler
{
private Templet t = null;
public int[] di;
public string[] names;
public string Group { get; set; }
public tRange Range { get; set; }
private int seq = 0;
public Filler(Templet tl, string markers = null)
{
t = tl;
if (markers != null)
names = markers.Split(new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries);
else
names = null;
}
public void init(int length)
{
di = new int[length];
for (int i = 0; i < length; i++)
di[i] = -1;
seq = 0;
Group = "";
Range = null;
}
// clear contents inside marked object or group
public void Clear()
{
object[] x = new object[di.Length];
for (int i = 0; i < di.Length; i++)
x[i] = null;
t.Set(di, x);
}
// set value for marked object,
// or add row to group and set value to columns
public void Set(params object[] x)
{
t.Set(di, x);
}
public void Add(params object[] x)
{
if (Group.Length > 0)
{
t.New(Group, seq);
++seq;
t.ReMark(this, Group);
}
t.Set(di, x);
}
}
}
Testing program
Program.cs
Templet m = new Templet(html);
Filler f= m.Mark("title");
f.Set("Phone book");
Filler fcontacts = m.Mark("contacts", "id,name,sex,phone");
fcontacts.Add(1, "Akhmad", "M", "123456");
fcontacts.Add(2, "Barry", "M", "234567");
fcontacts.Add(1, "Charles", "M", "345678");
Console.Out.WriteLine(m.Get());
Still can't do nested loop- yet.
Just use ASP.NET. Whether you use webforms or MVC, it's super easy to have C# in your .cs files, and HTML in your .aspx files.
As with anything in programming, it's 99% up to you to do things right. Flexible UI engines aren't going to enforce that you follow good coding practices.
In principle most any template engine you choose can separate HTML from control logic with the proper architecture. using an MVC (Or MVVM) pattern, if you construct your model in such a way that the controller contains the if/then logic instead of the view you can eliminate it from the view.
That said, the syntax you use is very close to Razor syntax which is easily available for ASP.NET MVC through NuGet packages.
I totally hear you. I built SharpFusion, which has some other stuff in it but if you look for the template.cs file you will see the handler that parses a HTML file and simply replaces out tokens with values that you've made in c#.
Because no XML parsing is done like ASP.NET the framework loads much faster than even an MVC site.
Another alternative is ServiceStack.

Assignment issue with bitwise operations

I am attempting to write a C# serial interface for a FPGA design I've implemented.
As part of the interface program I need to calculate a CRC-8 checksum.
I've attempted to do this on a low level(as that's the level I am more familiar with) but I am having issues.
The problem I am having is that assignments such as the ones on lines 91-95 (e.g. line 91: TempChecksumBits[7] = ChecksumBits[6];) are not only assigning the TempChecksumBits[] but is also changing the ChecksumBits[] value.
Any Ideas? Your help would be very much appreciated as I am less than familiar with high level languages.
Regards,
Mike
using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
byte[] ReadBuffer = new byte[20];
ReadBuffer[0] = Convert.ToByte("10000001", 2);
ReadBuffer[1] = Convert.ToByte("00000000", 2);
ReadBuffer[2] = Convert.ToByte("11000011", 2);
ReadBuffer[3] = Convert.ToByte("00001111", 2);
ReadBuffer[4] = Convert.ToByte("01010101", 2);
ReadBuffer[5] = Convert.ToByte("00001111", 2);
ReadBuffer[6] = Convert.ToByte("01010101", 2);
ReadBuffer[7] = Convert.ToByte("00001111", 2);
ReadBuffer[8] = Convert.ToByte("01010101", 2);
ReadBuffer[9] = Convert.ToByte("00001111", 2);
ReadBuffer[10] = Convert.ToByte("01010101", 2);
ReadBuffer[11] = Convert.ToByte("00001111", 2);
ReadBuffer[12] = Convert.ToByte("01010101", 2);
ReadBuffer[13] = Convert.ToByte("00001111", 2);
ReadBuffer[14] = Convert.ToByte("01010101", 2);
ReadBuffer[15] = Convert.ToByte("00001111", 2);
ReadBuffer[16] = Convert.ToByte("01010101", 2);
ReadBuffer[17] = Convert.ToByte("00001111", 2);
ReadBuffer[18] = Convert.ToByte("01010101", 2);
ReadBuffer[19] = Convert.ToByte("11100111", 2);
CheckDataPacket(ReadBuffer);
}
private void CheckDataPacket(byte[] ReadBuffer)
{
byte[] Checksum = new byte[1];
Checksum[0] = Convert.ToByte("00000000", 2);
byte[] DataBytes = new byte[18];
DataBytes[0] = ReadBuffer[2];
DataBytes[1] = ReadBuffer[3];
DataBytes[2] = ReadBuffer[4];
DataBytes[3] = ReadBuffer[5];
DataBytes[4] = ReadBuffer[6];
DataBytes[5] = ReadBuffer[7];
DataBytes[6] = ReadBuffer[8];
DataBytes[7] = ReadBuffer[9];
DataBytes[8] = ReadBuffer[10];
DataBytes[9] = ReadBuffer[11];
DataBytes[10] = ReadBuffer[12];
DataBytes[11] = ReadBuffer[13];
DataBytes[12] = ReadBuffer[14];
DataBytes[13] = ReadBuffer[15];
DataBytes[14] = ReadBuffer[16];
DataBytes[15] = ReadBuffer[17];
DataBytes[16] = ReadBuffer[18];
DataBytes[17] = ReadBuffer[1];
CalculateChecksum(DataBytes, ref Checksum);
textBox1.Text = (Convert.ToString(Checksum[0]));
}
private void CalculateChecksum(byte[] DataBytes, ref byte[] Checksum)
{
BitArray ChecksumBits = new BitArray(Checksum);
BitArray TempChecksumBits = new BitArray(Checksum);
for (int i = 0; i < 18; i++)
{
byte[] CurrentByte = new byte[1];
CurrentByte[0] = DataBytes[i];
BitArray DataBits = new BitArray(CurrentByte);
for (int k = 0; k < 8; k++)
{
TempChecksumBits[7] = ChecksumBits[6];
TempChecksumBits[6] = ChecksumBits[5];
TempChecksumBits[5] = ChecksumBits[4];
TempChecksumBits[4] = ChecksumBits[3];
TempChecksumBits[3] = ChecksumBits[2];
if ((ChecksumBits[7]) == (ChecksumBits[1]))
{
TempChecksumBits[2] = false;
}
else
{
TempChecksumBits[2] = true;
}
if ((ChecksumBits[7]) == (ChecksumBits[0]))
{
TempChecksumBits[1] = false;
}
else
{
TempChecksumBits[1] = true;
}
if ((DataBits[7-k]) == (ChecksumBits[7]))
{
TempChecksumBits[0] = false;
}
else
{
TempChecksumBits[0] = true;
}
ChecksumBits = TempChecksumBits;
}
}
/////////////// re-form checksum Byte/////////////////////
for (int j = 0; j < 8; j++)
{
if (ChecksumBits[j] == true)
{
double Value = Math.Pow(2, j);
Checksum[0] += (byte)(Value);
}
}
}
}
}
This line is the problem, just at the end of all your if/else blocks:
ChecksumBits = TempChecksumBits;
After that, the two variables refer to the same instance of BitArray. It's not clear why you're doing that or what you were trying to achieve, but it's clearly not doing what you really wanted.
Note that all the blocks like this:
if ((ChecksumBits[7]) == (ChecksumBits[1]))
{
TempChecksumBits[2] = false;
}
else
{
TempChecksumBits[2] = true;
}
can be simplified to:
TempChecksumBits[2] = ChecksumBits[7] != ChecksumBits[1];
... which will make your code much simpler.
(I'd also strongly advise you to name your local variables using camelCase rather than PascalCase.)
To be honest, I'd be tempted to use just a byte and bit-shifting/swapping techniques rather than all the BitArray objects...

Categories

Resources