Ports name and description in combo box - serial-port

I'm trying to display on a combo box all the ports that are available with their description.
I did a code where I can just display the ports that have the description, but I can't view all the other ports that don't have the description.
Can you please help me?
using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_SerialPort"))
{
string[] portnames = SerialPort.GetPortNames();
var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();
var tList = (from n in portnames
join p in ports on n equals p["DeviceID"].ToString()
select n + " - " + p["Caption"]).ToList();
foreach (String A in tList)
{
ArduinoComCmbBox.Items.Add(A);
}

Related

Add values to existing cookie in ASP.NET

I am facing the following task:
As the user navigates the site logs onto the website, write the
following information
Current Date
Current Time
Name of up to 5 Products the user viewed or Ordered during the visit
As I don't really have a product list site, I was going to do on the order screen. When user inputs the quantity to order I have a TextChanged event. So I can get details of a single product with the required information, but I am not sure how to keep adding to it?
This is what I am doing atm:
foreach (GridViewRow row in this.GridView1.Rows)
{
// string pName1 = GridView1.DataKeys[test].Values["ProductName"].ToString();
testCookie.Values.Add("CurrentDate", currentDate);
testCookie.Values.Add("CurrentTime", currentTime);
testCookie.Values.Add("ProductName", pName);
Label lblPartStatus = ((Label)row.Cells[4].FindControl("Label8"));
double testprice = Convert.ToDouble(lblPartStatus.Text);
grandTotal = grandTotal + testprice;
}
And also, how do I limit/check the amount of products that have been saved in the cookie and replace the oldest one with a newer ones?
Thanks for any advise!
I will recommend to create Dictionary object and add key value pair to it then store dictionary into Session.
Dictionary<string, string> dic = new Dictionary<string, string>();
int i = 0;
foreach (GridViewRow row in this.GridView1.Rows)
{
dic.Add("CurrentDate" + i, currentDate);
dic.Add("CurrentTime" + i, currentTime);
dic.Add("ProductName" + i, pName);
i++;
// your code
}
Session["dic"] = dic;
For retrieving those values.
Dictionary<string, string> dic = (Dictionary<string, string>)Session["dic"];
int i = 0;
foreach(KeyValuePair<string, string> entry in dic)
{
string date = entry.Value.ToString();
}

Allowing the attacker to access unathorized records finding

I have a scan finding and hope someone can provide any ideas as to best ways to resolve the issue. First I will show the scan Finding then my code and finally what the scanner's recommended solution is.
Finding
Without proper access control, the method GetAttributeKey() in Provider.cs can execute a SQL statement on line 163 that contains an attacker-controlled primary key, thereby allowing the attacker to access unauthorized records.
Rather than relying on the presentation layer to restrict values submitted by the user, access control should be handled by the application and database layers. Under no circumstances should a user be allowed to retrieve or modify a row in the database without the appropriate permissions. Every query that accesses the database should enforce this policy, which can often be accomplished by simply including the current authenticated username as part of the query.
My Code:
Offending line:
myParam.SqlParam.Value = attribute;
Method:
public string GetAttributeKey(string attribute)
{
string qry = "SELECT ws_attribute_key FROM webservice_attributes WHERE ws_attribute = #attribute";
QueryContainer Instance = new QueryContainer(qry);
MyParam myParam = new MyParam();
myParam.SqlParam = new SqlParameter("#attribute", Instance.AddParameterType(_DbTypes._string));
myParam.SqlParam.Value = attribute;
Instance.parameterList.Add(myParam);
object key = ExecuteScaler(Instance);
return Convert.ToString(key);
}
Scanner's Recommend fix:
string user = ctx.getAuthenticatedUserName();
int16 id = System.Convert.ToInt16(invoiceID.Text);
SqlCommand query = new SqlCommand(
"SELECT * FROM invoices WHERE id = #id AND user = #user", conn);
query.Parameters.AddWithValue("#id", id);
query.Parameters.AddWithValue("#user", user);
SqlDataReader objReader = query.ExecuteReader();
I think the problem is dealing with the code calling the GetAttributeKey. The method is called only if the user has no access to to the Attribute. I think I need some type of checking. Here is the calling code:
if (result.Rows.Count > 0)
{
// get the attribute
DataRow[] rows = result.Select("ws_attribute = '" + attribute + "'");
if (rows.Length > 0)
{
// check time range
string hr = DateTime.Now.Hour.ToString();
DataRow[] valid = result.Select("ws_attribute = '" + attribute + "' AND start_time <= " + hr + " AND end_time >= " + hr);
if (valid.Length > 0)
{
ws_user_attribute_key = Convert.ToInt32(valid[0]["ws_user_attribute_key"].ToString());
ret = true;
// generate salt
TextEncryptor te = new TextEncryptor();
salt = te.CreateSalt(8);
// save to the log, return false if failed to log
if (!LogTransfer(ipAddress, accessDate, fileName, ws_user_attribute_key, salt, out logKey))
return false;
}
else
{
ret = false;
LogInvalidAccess(username, rows[0]["ws_attribute_key"].ToString(), ipAddress, accessDate, WSInvalidAccessReason.OutsideValidTimeRange);
}
}
else
{
// if user has no access to attribute
ret = false;
LogInvalidAccess(username, GetAttributeKey(attribute), ipAddress, accessDate, WSInvalidAccessReason.AttributeNotAccessible);
}
}
else
{
ret = false;
LogInvalidAccess(username, GetAttributeKey(attribute), ipAddress, accessDate, WSInvalidAccessReason.InvalidAccount);
}

Listing orders and passing ISO 8601 date to Amazon MWS

What would be the best way to retrieve orders from Amazon MWS?
My current code is as follows...
MarketplaceWebServiceOrdersConfig config = new MarketplaceWebServiceOrdersConfig();
config.ServiceURL = productsURL;
MarketplaceWebServiceOrders.MarketplaceWebServiceOrdersClient service = new MarketplaceWebServiceOrdersClient(appname, version, accesskeyID, secretkey, config);
ListOrdersRequest request = new ListOrdersRequest();
request.MarketplaceId = new MarketplaceIdList();
request.MarketplaceId.Id = new List<string>(new string[] { marketids[0] });
request.SellerId = merchantID;
request.OrderStatus = new OrderStatusList() { Status = new List<OrderStatusEnum>() { OrderStatusEnum.Unshipped, OrderStatusEnum.PartiallyShipped } };
request.CreatedAfter = Convert.ToDateTime(dc.Settings.SingleOrDefault().lastOrdersRetrieved);
ListOrdersResponse response = service.ListOrders(request);
I am having issues passing the ISO Date across, also if you see any other issues with the code please feel free to let me know.
If your looking for something created after the immediate second you make the request, it wont find anything at all as with Amazon you can only grab up to the last 2 minutes of data for orders.
I had an issue with trying to set time from Now - 5 minutes. After speaking to Amazon support they provided the following nugget: "
In Orders API, if you don't specify an end time (CreatedBefore or
LastUpdatedBefore), it will assume now (actually, now minus 2
minutes). And in its response, it will tell you exactly what time it
used as the cutoff time."
In your case you will want to remove the CreatedAfter request and let Amazon choose for you.
If you are then looking for the created after, you can grab the response time Amazon gave and pass that in to your created after param.
The method I have right now to list orders is as follows, mind you this will just list the orders to console, but the data gets returned all the same:
public List<string> ListOrders(MarketplaceWebServiceOrders.MarketplaceWebServiceOrders service, string merchantId, List<OrderStatusEnum> orderStatus)
{
List<string> salesOrderIds = new List<string>();
ListOrdersRequest listOrdersRequest = new ListOrdersRequest();
DateTime createdAfter = DateTime.Now.Add(new TimeSpan(-1, 0, 0));
DateTime createdbefore = DateTime.Now.Add(new TimeSpan(0, -15, 0));
listOrdersRequest.CreatedAfter = createdAfter;
listOrdersRequest.CreatedBefore = createdbefore;
listOrdersRequest.SellerId = merchantId;
listOrdersRequest.OrderStatus = new OrderStatusList();
foreach (OrderStatusEnum status in orderStatus)
{
listOrdersRequest.OrderStatus.Status.Add(status);
}
listOrdersRequest.FulfillmentChannel = new FulfillmentChannelList();
listOrdersRequest.FulfillmentChannel.Channel = new List<FulfillmentChannelEnum>();
listOrdersRequest.FulfillmentChannel.Channel.Add(FulfillmentChannelEnum.MFN);
listOrdersRequest.MarketplaceId = new MarketplaceIdList();
listOrdersRequest.MarketplaceId.Id = new List<string>();
listOrdersRequest.MarketplaceId.Id.Add("yourID");
ListOrdersResponse listOrdersResponse = service.ListOrders(listOrdersRequest);
int i = 0;
foreach (Order order in listOrdersResponse.ListOrdersResult.Orders.Order)
{
i++;
Console.WriteLine("Amazon Order ID: \t" + order.AmazonOrderId);
Console.WriteLine("Buyer Name: \t" + order.BuyerName);
Console.WriteLine("Buyer Email: \t" + order.BuyerEmail);
Console.WriteLine("Fulfillment Channel: \t" + order.FulfillmentChannel);
Console.WriteLine("Order Status: \t" + order.OrderStatus);
Console.WriteLine("Order Total: \t" + order.OrderTotal);
Console.WriteLine("Number of Items Shipped: \t" + order.NumberOfItemsShipped);
Console.WriteLine("Number of Items Unshipped: \t" + order.NumberOfItemsUnshipped);
Console.WriteLine("Purchase Date: \t" + order.PurchaseDate);
Console.WriteLine("===========================================================");
salesOrderIds.Add(order.AmazonOrderId);
}
Console.WriteLine("We returned a total of {0} records. ", i);
return salesOrderIds;
}

Search in Fusion Tables and Zoom to results

Hi all here's my situation: http://www.tamrielma.ps/skyrim/
I've added a search based on this well know example: https://developers.google.com/fusiontables/docs/samples/autocomplete
But it's not enough :D and I want that the map zooms and centers on the basis of the search results (that's a single markers not a group of, so I imagine that's not a "bound related" solution).
Thanks in advance for any suggestion
Interesting map. :-) I see you are already using the Google.visualization library for your autocompplete set up. I think that the same library (which uses FT JSONP API I believe) could be used to get the location values via a a callback, similar to your getData() callback.
E.g.
function changeQuery(value) {
value = value.replace("'", "\\'");
layerMarkers.setQuery("SELECT Location FROM "+ fusione +" WHERE Name = '" + value + "'");
// ADDED, using same query as above
var queryText = encodeURIComponent( "SELECT Location FROM "+ fusione +" WHERE Name = '" + value + "'");
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
query.send(getLocationData);
}
// location may need parsing into LatLng object
function getLocationData(response) {
numRows = response.getDataTable().getNumberOfRows();
if(numRows == 1){
var loc_str = response.getDataTable().getValue(0, 0));
var tmp = loc_str.split(" ");
var lat = parseFloat(tmp[0]);
var lng = parseFloat(tmp[1]);
var zoom_level = 10;
var location = new google.maps.LatLng(lat,lng);
map.setCenter(location);
map.setZoom(zoom_level);
}
}

Aggregating one side of a many-to-many and bind to gridview in Entity Framework

I have a many-to-many structure in place in my database / Entity Framework model.
CompanyNotice (M-M) CompanyNoticesLocations (M-M) Locations
I am trying to aggregate the Locations for one CompanyNotice and return a comma-separated LocationName for the Locations. I have tried using the following code to aggregate the LocationName:
if (!IsPostBack)
{
using (var context = new ALEntities())
{
var query = from c in context.CompanyNotices.Include("Locations")
select new
{
c.CompanyNoticeHeading,
c.CompanyNoticeText,
c.IsHR,
locations = (from l in c.Locations select l.LocationName).Aggregate((current, next) => string.Format("{0}, {1}", current, next))
};
ASPxGridView1.DataSource = query;
ASPxGridView1.DataBind();
}
}
I get the following error when I try the above code:
LINQ to Entities does not recognize the method 'System.String
Aggregate[String](System.Collections.Generic.IEnumerable1[System.String],
System.Func3[System.String,System.String,System.String])' method, and
this method cannot be translated into a store expression.
When I try:
if (!IsPostBack)
{
using (var context = new ALEntities())
{
var query = from c in context.CompanyNotices.Include("Locations")
select new
{
c.CompanyNoticeHeading,
c.CompanyNoticeText,
c.IsHR,
locations = (from l in c.Locations select l.LocationName)
};
ASPxGridView1.DataSource = query;
ASPxGridView1.DataBind();
}
}
The data within the locations column on the gridview appears as:
System.Collections.Generic.List`1[System.String]
Does anyone know how do I aggregate the LocationName to appear for one CompanyNotice?
Thanks in advance.
you could this ...
using (var context = new ALEntities())
{
var query = from c in context.CompanyNotices.Include("Locations")
select new
{
c.CompanyNoticeHeading,
c.CompanyNoticeText,
c.IsHR,
locations = (from l in c.Locations select l.LocationName)
};
var listed = query.ToList();
var commaListed = listed.Select ( a=> new { a.CompanyNoticeHeading, a.CompanyNoticeText,
commaLines = a.locations.Aggregate((s1, s2) => s1 + "," + s2)});
then bind commaListed to your datagrid

Resources