How can I modify a static property? - c#

I am tring to motify a static property, I don't know where I am getting wrong. Here is the code.
public static string Id
{
get { return Id; }
set
{
if (Id.Length < Idlen)
{
var zero = new string('0', Idlen - Id.Length);
Id = zero + Id;
Id = value;
}
else
{
Id = Id.Substring(Id.Length - Idlen);
Id = value;
}
}
}
public static int Idlen { get; set; }

So here is an example of what I think you are trying to achieve. (Although ReSharper is telling me not to use these field names...)
private static string _Id;
public static string Id
{
get => _Id;
set // You want to use value here (new value), not Id (old value)
{
if (value == null)
{
// Consider what you want to do if user calls Id = null
_Id = new string('0', Idlen);
}
else if (value.Length < Idlen)
{
var zero = new string('0', Idlen - value.Length);
_Id = zero + value;
}
else
{
_Id = value.Substring(value.Length - Idlen);
}
}
}
public static int Idlen { get; set; }

Related

EF6 duplicate entries on related entities

Ok, so I'm really frustrated with the duplication issues of EF6. I have searched the forum extensively and tried different things, but I can't seem to figure this one out.
My base model is a trainingprogram, that consists of many blocks, which in turn hold a list of circuits. Every circuit holds a number of exercisesets and progressions for each exercise. All the relevant parts of the model are in the minimal workin example below.
I have a controller that I use to persist training programs to the DB. Whenever I call dbcontext.SaveChanges(), my database i populated with duplicates of the related entities, although I have tried setting the state to unchanged, attaching the enities to the context and what not. Pretty much everything gets duplicated - exercises, categories and progressionschemes.
This is really a blocker, so any help is appreciated.
[HttpPost]
[Route("Add")]
public HttpResponseMessage AddProgram(TrainingProgram program)
{
int id = -1;
try
{
using (var dbcontext = new ApplicationDbContext())
{
foreach (TrainingBlock b in program.Blocks)
foreach (ExercisePairing c in b.Circuits)
{
foreach (ProgressionScheme ps in c.Progressions.Select(x => x.Progression).Distinct().ToList())
{
var ep = dbcontext.Progressions.FirstOrDefault(p => p.Name == ps.Name && p.Id == ps.Id);
if (ep is null)
dbcontext.Progressions.Attach(ps);
//dbcontext.Entry(ps).State = EntityState.Unchanged;// Attach(ps);
}
foreach (Exercise s in c.Sets.Select(x => x.Exercise).Distinct().ToList())
{
//dbcontext.Entry(s).State = EntityState.Unchanged;
//dbcontext.Entry(s.Category).State = EntityState.Unchanged;
dbcontext.ExerciseCategories.Attach(s.Category);
dbcontext.Exercises.Attach(s);
}
}
dbcontext.TrainingPrograms.AddOrUpdate(program);
dbcontext.SaveChanges();
id = program.Id;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
return Request.CreateResponse(HttpStatusCode.OK, id);
}
public class ExercisePairing:BaseClass
{
private List<ExerciseSet> sets = new List<ExerciseSet>();
private List<ProgressionForExercise> progressions = new List<ProgressionForExercise>();
private int id;
...
...
}
}
public class ProgressionForExercise:BaseClass
{
public int Id { get; set; }
private Exercise exercise;
public int ExerciseId { get; set; }
public int ProgressionId { get; set; }
[ForeignKey("ExerciseId")]
public Exercise Exercise
{
get => exercise;
set
{
exercise = value;
ExerciseId = exercise.Id;
}
}
private ProgressionScheme progression;
[ForeignKey("ProgressionId")]
public ProgressionScheme Progression
{
get =>progression ;
set
{
progression = value;
ProgressionId = progression.Id;
}
}
}
public class Exercise : BaseClass
{
private int id;
private string name;
private string description;
private string videourl;
private ExerciseCategory category;
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public ExerciseCategory Category
{
get => category;
set
{
category = value;
OnPropertyChanged();
}
}
public int Id
{
get => id;
set
{
id = value;
OnPropertyChanged();
}
}
...
...
}
public class ExerciseCategory:BaseClass
{
private string name;
private int id;
[Key]
public int Id
{
get => id;
set
{
id = value;
OnPropertyChanged();
}
}
public string Name
{
get => name;
set
{
name = value;
OnPropertyChanged();
}
}
...
...
}
public class ProgressionScheme:BaseClass
{
private int id;
private string name;
private string description;
public int Id
{
get => id;
set
{
id = value;
OnPropertyChanged();
}
}
public string Name
{
get => name;
set
{
name = value;
OnPropertyChanged();
}
}
...
...
}
EDIT
I now solved the issue by basically re-wrtiting my controller code like so:
[HttpPost]
[Route("Add")]
public HttpResponseMessage AddProgram(TrainingProgram program)
{
int id = -1;
try
{
using (var dbcontext = new ApplicationDbContext())
{
TrainingProgram tp = new TrainingProgram();
tp.Title = program.Title;
tp.Remarks = program.Remarks;
tp.CreationDate = program.CreationDate;
tp.Creator = program.Creator;
tp.Blocks = new List<TrainingBlock>();
foreach (TrainingBlock b in program.Blocks)
{
TrainingBlock tb = new TrainingBlock();
tb.Title = b.Title;
tb.Remarks = b.Remarks;
tb.Circuits = new List<ExercisePairing>();
foreach (ExercisePairing c in b.Circuits)
{
ExercisePairing ep = new ExercisePairing();
ep.Sets = new List<ExerciseSet>();
foreach(ExerciseSet s in c.Sets)
{
ExerciseSet es = new ExerciseSet();
Exercise ex = dbcontext.Exercises.Find(s.Exercise.Id);
es.Exercise = ex;
ExerciseCategory ec = dbcontext.ExerciseCategories.Find(s.Exercise.Category.Id);
es.Exercise.Category = ec;
es.Reps = s.Reps;
es.Intensity = s.Intensity;
es.Unit = s.Unit;
ep.Sets.Add(es);
}
ep.Progressions = new List<ProgressionForExercise>();
foreach (ProgressionForExercise pro in c.Progressions)
{
Exercise ex = dbcontext.Exercises.Find(pro.Exercise.Id);
ProgressionScheme ps = dbcontext.Progressions.Find(pro.Progression.Id);
ProgressionForExercise p4e = new ProgressionForExercise();
p4e.Exercise = ex;
p4e.Progression = ps;
ep.Progressions.Add(p4e);
}
tb.Circuits.Add(ep);
}
tp.Blocks.Add(tb);
}
dbcontext.TrainingPrograms.AddOrUpdate(tp);
dbcontext.SaveChanges();
id = tp.Id;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
return Request.CreateResponse(HttpStatusCode.OK, id);
}
So in essence, I am avoiding the duplicates by only using the very objects that are present in the Context. Although this works, I am not sure if I am happy with that. If a simple CRUD peration takes that much code, I fail to see the upside of using EF VS simply using an SQL insert statement, which would be much more efficient in this case IMHO. Also, why does EF ignore the primary keys and insist on using its wn instances of my enitities? All of this is very strange.

How to read null values out of a integer column in sql to C#?

i am trying to make a project for my school. I am trying to read a table where some null values are in an integer column. I've made it an integer but i can't get the null values into the integer.
I've already searched in stackoverflow but none of the answers i could make at my project. Can someone provide me some help, tell me where i have to put the code to make it work again. I just started as programmer.
This is my database conn string + reader:
public static List<Klant> GetAlleklanten()
{
var result = new List<Klant>();
using (var conn = new SqlConnection(ConnectionString))
{
conn.Open();
const string query = "select k.klantid, k.naam, k.adres, k.telefoonnummer, k.woonplaats, k.email, k.wachtwoord, kp.klantpasid from klant k left join klantpas kp on k.klantid = kp.klantid";
SqlCommand selectKamers = new SqlCommand(query, conn);
SqlDataReader reader = selectKamers.ExecuteReader();
while (reader.Read())
{
Klant klant = new Klant((int)reader["klantid"], (string)reader["naam"], (string)reader["adres"], (string)reader["telefoonnummer"], (string)reader["woonplaats"], (string)reader["email"], (string)reader["wachtwoord"], (int)reader["klantpasid"]);
result.Add(klant);
}
reader.Close();
}
return result;
}
klantpasid is the one that also can return a null value instead of an integer.
Here is the class where the klantpasid is in the construtor:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FontysHotel
{
public class Klant
{
// instantie variabelen
private int klantid;
private string naam;
private string adres;
private string telefoonnummer;
private string woonplaats;
private string email;
private string wachtwoord;
private int? klantpasid;
// properties
public int Klantid
{
get
{
return klantid;
}
set
{
klantid = value;
}
}
public string Naam
{
get
{
return naam;
}
set
{
naam = value;
}
}
public string Adres
{
get
{
return adres;
}
set
{
adres = value;
}
}
public string Telefoonnummer
{
get
{
return telefoonnummer;
}
set
{
telefoonnummer = value;
}
}
public string Woonplaats
{
get
{
return woonplaats;
}
set
{
woonplaats = value;
}
}
public string Email
{
get
{
return email;
}
set
{
email = value;
}
}
public string Wachtwoord
{
get
{
return wachtwoord;
}
set
{
wachtwoord = value;
}
}
public int? Klantpasid
{
get
{
return klantpasid;
}
set
{
klantpasid = value;
}
}
// Constructor
public Klant(int klantid, string naam, string adres, string telefoonnummer, string woonplaats, string email, string wachtwoord, int klantpasid)
{
Klantid = klantid;
Naam = naam;
Adres = adres;
Telefoonnummer = telefoonnummer;
Woonplaats = woonplaats;
Email = email;
Wachtwoord = wachtwoord;
Klantpasid = klantpasid;
}
}
}
Please provide me some help, tell me where i have to place the right code so i can continue my school project. The error i am getting now is ''' The specified conversion is invalid
'''
You can check klantid for DBNull.Value, and if it is, assign corresponding special int value; so instead of
(int)reader["klantid"]
put
reader.IsDBNull(reader.GetOrdinal("klantid")) ? -1 : Conver.ToInt32(reader["klantid"])
a better way is to declare private int klantid; as private int? klantid; (nullable int):
private int? klantid; // it can accept null now
public int? Klantid
{
get
{
return klantid;
}
set
{
klantid = value;
}
}
then while reading from reader we can use turnary operator:
KlantId = !reader.IsDBNull(reader.GetOrdinal("klantid"))
? Conver.ToInt32(reader["klantid"])
: null;
I know a fix for you,
You change Klantpasid from int? to int
If klantpasid is null in your database, we set the value to 0 instead of null
public int Klantpasid
{
get
{
return klantpasid;
}
set
{
if( value == null){
klantpasid = 0;
}else {
klantpasid = value;
}
}
}
You can declare your property as nullable
public int? Klantid
{
get
{
return klantid;
}
set
{
klantid = value;
}
}
Check out more on documentation.
When you read your data with a DataReader, it will return DBNull.Value. Whe you want to fill your Klant.Klantpasid value (which is of type Nullable<int>), you will have to convert the value to Nullable<int> yourself. When ADO.NET was first implemented, there were no nullable values, so they introduced DBNull instead. More modern approaches like Entity Framework use nullable types instead.
You can write a helper method to help converting your read value to a nullable type:
static T? AsNullable<T>(object value) where T : struct {
switch (value) {
case T converted:
return converted;
case DBNull:
return default(T?);
default:
throw new InvalidCastException();
}
}
So instead of...
(int)reader["klantpasid"]
...you write:
AsNullable<int>(reader["klantpasid"])
And of course you change the type of your constructor parameter from int to int?.

Huge List<T> processing and Pdf generate

I have a pdf file as Byte[] and I'm using iTextSharp to modify the file and embed a specific details in it.
in the List I have min. 25K objects, and I need to generate 25K pdf files.
I'm using Parallel.ForEach but it takes 16.40 mins to be done in Total.
I used ToLookUp method like this:
var valuesToLookupWith = Recipients.ToLookup(item => item.ID);
List<int> Ids = Recipients.Select(item => item.ID).ToList();
Partitioner<int> partitioner = Partitioner.Create(Ids, EnumerablePartitionerOptions.NoBuffering);
Parallel.ForEach(partitioner, new ParallelOptions { MaxDegreeOfParallelism = 6 } ,(id) =>
{
var item = valuesToLookupWith[id].ToList().FirstOrDefault();
item.Attachment = AttachmentEngine.GeneratePdfFromPdfFile((fileAsByteArray,id, "www.xyz.ca"));
...
});
and I used ForEach and also it takes approx. > 25 minutes.
foreach (int id in Ids)
{
var item = valuesToLookupWith[id].ToList().FirstOrDefault();
item.Attachment = AttachmentEngine.GeneratePdfFromPdfFile(fileAsByteArray,id, "www.xyz.ca");
...
}
any suggested way to speedup the process please?
FYI I'm not writing anything on the disk, all is done in memory as Byte[] and then I'm writing the values back to the Db.
and also all the time spent - mentioned in the question is only the time spent for Parallel.ForEach / ForEach statements.
Db calls is not an issue for me at all, I'm making only two calls to the Db , one when I load list of recipients from it and another call when writing values back to the Db
public static byte[] GeneratePdfFromPdfFile(byte[] file, int id, string landingPage)
{
try
{
using (var ms = new MemoryStream())
{
//Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
var doc = new iTextSharp.text.Document();
//Create a writer that's bound to our PDF abstraction and our stream
var writer = PdfWriter.GetInstance(doc, ms);
//Open the document for writing
doc.Open();
PdfContentByte cb = writer.DirectContent;
// doc.NewPage();
//var srHtml = new StringReader(source);
////parse html code to xml
//iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
PdfReader reader = new PdfReader(file);
for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++)
{
doc.SetPageSize(reader.GetPageSizeWithRotation(1));
doc.NewPage();
//Insert to Destination on the first page
PdfImportedPage page = writer.GetImportedPage(reader, pageNumber);
int rotation = reader.GetPageRotation(pageNumber);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pageNumber).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
// Add a new page to the pdf file
doc.NewPage();
// set pdf open action to open the link embedded in the file.
string _embeddedURL = "http://" + landingPage + "/Default.aspx?code=" + GetCampaignRecipientCode(id) + "&m=" + eventCode18;
PdfAction act = new PdfAction(_embeddedURL);
writer.SetOpenAction(act);
doc.Close();
return ms.ToArray();
}
}
catch { return null; }
}
Recipient Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CampaignLauncherLibrary
{
public class CampaignRecipientLib
{
private int _id;
private int _crid;
private string _crcode;
private int _cmpId;
private string _cmpStatus;
private string _email;
private string _firstName;
private string _lastName;
private string _language;
private string _cmpDefaultlanguage;
private bool _isdoubleBarrle;
private DateTime? _scheduled;
private string _offset;
private string _emailTo;
private string _emailFrom;
private string _emailBody;
private string _emailSubject;
private byte[] _emailAttachment;
private string _emailReplyTo;
private string _attachmentName;
private bool _readytobesent;
private bool _pickupready;
private TimeSpan _Toffset;
private int? _cmprIDnextRecipient;
private string _CampaignGroupCode;
private bool _Reschedule;
private List<int> _Campaigns;
private List<int> _SentCampaigns;
private bool _restrictToWorkHours;
private TimeSpan? _whStart;
private TimeSpan? _whEnd;
private string _emailName;
public CampaignRecipientLib()
{
}
public CampaignRecipientLib(CampaignRecipientLib _recipient)
{
ID = _recipient.ID;
CampaignId = _recipient.CampaignId;
CampaignStatus = _recipient.CampaignStatus;
CMPRID = _recipient.CMPRID;
CMPRCode = Guid.NewGuid().ToString("N");
Email = _recipient.Email;
FirstName = _recipient.FirstName;
LastName = _recipient.LastName;
Language = _recipient.Language;
DefaultLanguage = _recipient.DefaultLanguage;
IsdoubleBarrle = _recipient.IsdoubleBarrle;
Scheduled = _recipient.Scheduled;
Offset = _recipient.Offset;
EmailTo = _recipient.EmailTo;
EmailFrom = _recipient.EmailFrom;
EmailBody = _recipient.EmailBody;
EmailSubject = _recipient.EmailSubject;
EmailAttachment = _recipient.EmailAttachment;
EmailReplyTo = _recipient.EmailReplyTo;
AttachmentName = _recipient.AttachmentName;
ReadyTobeSent = _recipient.ReadyTobeSent;
PickupReady = _recipient.PickupReady;
IDnextRecipient = _recipient.IDnextRecipient;
CampaignGroupCode = _recipient.CampaignGroupCode;
Reschedule = _recipient.Reschedule;
Campaigns = _recipient.Campaigns;
SentCampaigns = _recipient.SentCampaigns;
EmailName = _recipient.EmailName;
Toffset = _recipient.Toffset;
}
public void AssingRandomCampaign()
{
int result = 0;
List<int> cmp = _Campaigns;
List<int> sentcmp = _SentCampaigns;
if (cmp.Where(x => !sentcmp.Distinct().Contains(x)).ToList().Count > 0)
{
cmp = cmp.Where(x => !sentcmp.Distinct().Contains(x)).ToList();
result = cmp.Shuffle().Take(1).ToList()[0];
}
else
{
int N = 0;
if (sentcmp.Count == 2) N = 1;
else if (sentcmp.Count == 3) N = 2;
else N = sentcmp.Count % 2 == 0 ? 2 : 3;
List<int> lastN = sentcmp.Skip(Math.Max(0, sentcmp.Count) - N).ToList();
cmp = cmp.Where(predicate: x => !lastN.Contains(x)).ToList();
sentcmp = sentcmp.Where(predicate: x => cmp.Contains(x)).ToList();
List<int> grpOccurrences = sentcmp.GroupBy(i => i).OrderByDescending(item => item.Count()).SelectMany(i => i).Distinct().ToList();
result = grpOccurrences.Shuffle().PickRandom(1).ToList()[0];
}
if (result > 0)
{
_SentCampaigns.Add(result);
CampaignId = result;
}
}
public bool reAdjustScheduleDate()
{
try
{
Scheduled = Utilities.FixDate(Scheduled.Value, RestrictToWorkHours, Offset, WhStart, WhEnd);
}
catch (Exception ex)
{
return false;
}
return true;
}
public TimeSpan Toffset
{
get { return _Toffset; }
set { _Toffset = value; }
}
public string EmailName
{
get { return _emailName; }
set { _emailName = value; }
}
public int? IDnextRecipient
{
get { return _cmprIDnextRecipient; }
set { _cmprIDnextRecipient = value; }
}
public string CampaignGroupCode
{
get { return _CampaignGroupCode; }
set { _CampaignGroupCode = value; }
}
public bool RestrictToWorkHours
{
get { return _restrictToWorkHours; }
set { _restrictToWorkHours = value; }
}
public TimeSpan? WhStart
{
get { return _whStart; }
set { _whStart = value; }
}
public TimeSpan? WhEnd
{
get { return _whEnd; }
set { _whEnd = value; }
}
public bool Reschedule
{
get { return _Reschedule; }
set { _Reschedule = value; }
}
public List<int> Campaigns
{
get { return _Campaigns; }
set { _Campaigns = value; }
}
public List<int> SentCampaigns
{
get { return _SentCampaigns; }
set { _SentCampaigns = value; }
}
public int ID
{
get { return _id; }
set { _id = value; }
}
public int CMPRID
{
get { return _crid; }
set { _crid = value; }
}
public string CMPRCode
{
get { return _crcode; }
set { _crcode = value; }
}
public int CampaignId
{
get { return _cmpId; }
set { _cmpId = value; }
}
public string CampaignStatus
{
get { return _cmpStatus; }
set { _cmpStatus = value; }
}
public string Email
{
get { return _email; }
set { _email = value; }
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public string Language
{
get { return _language; }
set { _language = value; }
}
public string DefaultLanguage
{
get { return _cmpDefaultlanguage; }
set { _cmpDefaultlanguage = value; }
}
public bool IsdoubleBarrle
{
get { return _isdoubleBarrle; }
set { _isdoubleBarrle = value; }
}
public DateTime? Scheduled
{
get { return _scheduled; }
set { _scheduled = value; }
}
public string EmailTo
{
get { return _emailTo; }
set { _emailTo = value; }
}
public string Offset
{
get { return _offset; }
set { _offset = value; }
}
public string EmailFrom
{
get { return _emailFrom; }
set { _emailFrom = value; }
}
public string EmailBody
{
get { return _emailBody; }
set { _emailBody = value; }
}
public string EmailSubject
{
get { return _emailSubject; }
set { _emailSubject = value; }
}
public byte[] EmailAttachment
{
get { return _emailAttachment; }
set { _emailAttachment = value; }
}
public string EmailReplyTo
{
get { return _emailReplyTo; }
set { _emailReplyTo = value; }
}
public string AttachmentName
{
get { return _attachmentName; }
set { _attachmentName = value; }
}
public bool ReadyTobeSent
{
get { return _readytobesent; }
set { _readytobesent = value; }
}
public bool PickupReady
{
get { return _pickupready; }
set { _pickupready = value; }
}
}
}

Encounter Nullpointer error [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I am having problem with nullpointer. I cant seem to understand why my code is wrong. Any help will be greatly appreciated. This is my code:
protected void Page_Load(object sender, EventArgs e)
{
Product aProd = new Product();
// Get Product ID from querystring
string prodID = Request.QueryString["ProdID"].ToString(); (null pointer occurs at this line. )
prod = aProd.getProduct(prodID);
//Display product details on web form
lbl_ProdName.Text = prod.Product_Name;
lbl_ProdDesc.Text = prod.Product_Desc;
lbl_Price.Text = prod.Unit_Price.ToString("c");
img_Product.ImageUrl = "~\\Images\\" + prod.Product_Image;
//Store the value in invisible fields
lbl_Price.Text = prod.Unit_Price.ToString();
lbl_ProdID.Text = prodID.ToString();
}
These are the code for Product.cs. I still have no idea where my codes went wrong
public class Product
{
string _connStr = ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString;
private string _prodID = null;
private string _prodName = string.Empty;
private string _prodDesc = ""; // this is another way to specify empty string
private decimal _unitPrice = 0;
private string _prodImage = "";
private int _stockLevel = 0;
// Default constructor
public Product()
{
}
// Constructor that take in all data required to build a Product object
public Product(string prodID, string prodName, string prodDesc,
decimal unitPrice, string prodImage, int stockLevel)
{
_prodID = prodID;
_prodName = prodName;
_prodDesc = prodDesc;
_unitPrice = unitPrice;
_prodImage = prodImage;
_stockLevel = stockLevel;
}
// Constructor that take in all except product ID
public Product(string prodName, string prodDesc,
decimal unitPrice, string prodImage, int stockLevel)
: this(null, prodName, prodDesc, unitPrice, prodImage, stockLevel)
{
}
// Constructor that take in only Product ID. The other attributes will be set to 0 or empty.
public Product(string prodID)
: this(prodID, "", "", 0, "", 0)
{
}
// Get/Set the attributes of the Product object.
// Note the attribute name (e.g. Product_ID) is same as the actual database field name.
// This is for ease of referencing.
public string Product_ID
{
get { return _prodID; }
set { _prodID = value; }
}
public string Product_Name
{
get { return _prodName; }
set { _prodName = value; }
}
public string Product_Desc
{
get { return _prodDesc; }
set { _prodDesc = value; }
}
public decimal Unit_Price
{
get { return _unitPrice; }
set { _unitPrice = value; }
}
public string Product_Image
{
get { return _prodImage; }
set { _prodImage = value; }
}
public int Stock_Level
{
get { return _stockLevel; }
set { _stockLevel = value; }
}
Request.QueryString["ProdID"] is returning null.
So your ToString() call cause a System.NullPointerException
Solution : ensure that your Request.QueryString["ProdID"] call sends you back the correct object, or test the result yourself:
var obj = Request.QueryString["ProdID"];
string prodID = obj == null ? String.Empty : obj.ToString();

GetIpForwardTable returns garbage on WIndows CE with PInvoke

I have a following problem. I created a PInvoke in a Windows CE .NET managed project for GetIpForwardTable function. When I call the function in returns the result, but the results are different from the result returned by the route command. There are more entries in the table, Mask and Destination changed places and NextHop is always set to 0.0.0.0
Here is the class (one needs to call IPForwardEntry.GetIpForwardTable()).
public class IPForwardEntry
{
public enum ForwardType
{
Other = 1,
Invalid = 2,
Direct = 3,
Indirect = 4
}
public enum ForwardProtocol
{
Other = 1,
Local = 2,
NetMGMT = 3,
ICMP = 4,
EGP = 5,
GGP = 6,
Hello = 7,
RIP = 8,
IS_IS = 9,
ES_IS = 10,
CISCO = 11,
BBN = 12,
OSPF = 13,
BGP = 14,
NT_AUTOSTATIC = 10002,
NT_STATIC = 10006,
NT_STATIC_NON_DOD = 10007
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_IPFORWARDROW
{
public uint dwForwardDest;
public uint dwForwardMask;
public int dwForwardPolicy;
public uint dwForwardNextHop;
public int dwForwardIfIndex;
public ForwardType dwForwardType;
public ForwardProtocol dwForwardProto;
public int dwForwardAge;
public int dwForwardNextHopAS;
public int dwForwardMetric1;
public int dwForwardMetric2;
public int dwForwardMetric3;
public int dwForwardMetric4;
public int dwForwardMetric5;
}
private IPForwardEntry(MIB_IPFORWARDROW forwardRow)
{
myForwardRow = forwardRow;
}
private MIB_IPFORWARDROW myForwardRow;
private const int NO_ERROR = 0;
[DllImport("Iphlpapi.dll")]
private static extern int CreateIpForwardEntry(MIB_IPFORWARDROW[] pRoute);
[DllImport("Iphlpapi.dll")]
private static extern int GetIpForwardTable(MIB_IPFORWARDROW[] pIpForwardTable, ref long pdwSize, bool bOrder);
public static IPForwardEntry[] GetIpForwardTable()
{
long tableSize = 0;
GetIpForwardTable(null, ref tableSize, true);
MIB_IPFORWARDROW[] forwardTable = new MIB_IPFORWARDROW[tableSize / Marshal.SizeOf(typeof(MIB_IPFORWARDROW)) + 1];
long tableSizeOld = tableSize;
if (GetIpForwardTable(forwardTable, ref tableSize, false) != NO_ERROR)
throw new SystemException();
if (tableSizeOld != tableSize)
throw new SystemException();
IPForwardEntry[] result = new IPForwardEntry[forwardTable.Length];
for (int i = 0; i < forwardTable.Length; i++)
result[i] = new IPForwardEntry(forwardTable[i]);
return result;
}
#region members
public IPAddress FordwardDestination
{
get
{
return new IPAddress(myForwardRow.dwForwardDest);
}
set
{
myForwardRow.dwForwardDest = (uint) value.Address;
}
}
public IPAddress ForwardMask
{
get
{
return new IPAddress(myForwardRow.dwForwardMask);
}
set
{
myForwardRow.dwForwardMask = (uint) value.Address;
}
}
public int ForwardPolicy
{
get
{
return myForwardRow.dwForwardPolicy;
}
set
{
myForwardRow.dwForwardPolicy = value;
}
}
public IPAddress ForwardNextHop
{
get
{
return new IPAddress(myForwardRow.dwForwardNextHop);
}
set
{
myForwardRow.dwForwardNextHop = (uint) value.Address;
}
}
public int ForwardInterfaceIndex
{
get
{
return myForwardRow.dwForwardIfIndex;
}
set
{
myForwardRow.dwForwardIfIndex = value;
}
}
public ForwardType ForwrdType
{
get
{
return myForwardRow.dwForwardType;
}
set
{
myForwardRow.dwForwardType = value;
}
}
public ForwardProtocol Protocol
{
get
{
return myForwardRow.dwForwardProto;
}
set
{
myForwardRow.dwForwardProto = value;
}
}
public int ForwardAge
{
get
{
return myForwardRow.dwForwardAge;
}
set
{
myForwardRow.dwForwardAge = value;
}
}
public int ForwardNextHopAS
{
get
{
return myForwardRow.dwForwardNextHopAS;
}
set
{
myForwardRow.dwForwardNextHopAS = value;
}
}
public int ForwardMetric1
{
get
{
return myForwardRow.dwForwardMetric1;
}
set
{
myForwardRow.dwForwardMetric1 = value;
}
}
public int ForwardMetric2
{
get
{
return myForwardRow.dwForwardMetric2;
}
set
{
myForwardRow.dwForwardMetric2 = value;
}
}
public int ForwardMetric3
{
get
{
return myForwardRow.dwForwardMetric3;
}
set
{
myForwardRow.dwForwardMetric3 = value;
}
}
public int ForwardMetric4
{
get
{
return myForwardRow.dwForwardMetric4;
}
set
{
myForwardRow.dwForwardMetric4 = value;
}
}
public int ForwardMetric5
{
get
{
return myForwardRow.dwForwardMetric5;
}
set
{
myForwardRow.dwForwardMetric5 = value;
}
}
#endregion
}
GetIpForwardTable doesn't return an array of MIB_IPFORWARDROW objects, it returns a MIB_IPFORWARDTABLE, that contains an array of rows and the number. So that's at least one issue. There are likely others as this is not a straightforward P/Invoke set for marshaling.
For what it's worth, I've already implemented all of this code in the Smart Device Framework, specifically in the OpenNETCF.Net.NetworkInformation.IPRoutingTable class
I dont know how the function works, but the following looks very suspicious.
new MIB_IPFORWARDROW[tableSize / Marshal.SizeOf(typeof(MIB_IPFORWARDROW)) + 1]
Why are you dividing by the sizeof?

Categories