How To add another constructor with parameter in linq class(Table) - c#

I am using LINQ to SQL in an ASP.NET project. While inserting the table I need to convert the values to the particular table object and I need to insert.
For that I created a new constructor in that table with parameter so that I can assign my value to that table object , the assign the functionality is working but while inserting (obj.TS_Questions.InsertOnSubmit(mytableobject);) I get null exception.
my code::
default constructor for my table
public TS_Question()
{
this._TS_Options = new EntitySet<TS_Option>(new Action<TS_Option>(this.attach_TS_Options), new Action<TS_Option>(this.detach_TS_Options));
this._TS_QuestGroups = new EntitySet<TS_QuestGroup>(new Action<TS_QuestGroup>(this.attach_TS_QuestGroups), new Action<TS_QuestGroup>(this.detach_TS_QuestGroups));
this._TS_QuestRecords = new EntitySet<TS_QuestRecord>(new Action<TS_QuestRecord>(this.attach_TS_QuestRecords), new Action<TS_QuestRecord>(this.detach_TS_QuestRecords));
this._TS_Admin = default(EntityRef<TS_Admin>);
this._TS_LevelType = default(EntityRef<TS_LevelType>);
this._TS_OptionTypeLT = default(EntityRef<TS_OptionTypeLT>);
OnCreated();
}
constructor created by me
public TS_Question(Guid Quest_QuestIDBL, string Quest_NameBL, Nullable<Guid> Quest_OptionTypeIDBL, Guid Quest_AdminIDBL, Guid Ques_LevelIDBL, int Quest_TimeBL, int Quest_MarkBL, string Qest_ExplanationBL, Nullable<bool> Qest_IsMultipleAnswerBL)
{
this._TS_Options = new EntitySet<TS_Option>(new Action<TS_Option>(this.attach_TS_Options), new Action<TS_Option>(this.detach_TS_Options));
this._TS_QuestGroups = new EntitySet<TS_QuestGroup>(new Action<TS_QuestGroup>(this.attach_TS_QuestGroups), new Action<TS_QuestGroup>(this.detach_TS_QuestGroups));
this._TS_QuestRecords = new EntitySet<TS_QuestRecord>(new Action<TS_QuestRecord>(this.attach_TS_QuestRecords), new Action<TS_QuestRecord>(this.detach_TS_QuestRecords));
this._TS_Admin = default(EntityRef<TS_Admin>);
this._TS_LevelType = default(EntityRef<TS_LevelType>);
this._TS_OptionTypeLT = default(EntityRef<TS_OptionTypeLT>);
OnCreated();
this._Quest_QuestID = Quest_QuestIDBL;
this._Quest_Name = Quest_NameBL;
if (Quest_OptionTypeIDBL != null)
{
this._Quest_OptionTypeID = Quest_OptionTypeIDBL;
}
this._Quest_AdminID = Quest_AdminIDBL;
this._Ques_LevelID = Ques_LevelIDBL;
this._Quest_Time = Quest_TimeBL;
this._Quest_Mark = Quest_MarkBL;
this._Qest_Explanation = Qest_ExplanationBL;
this._Qest_IsMultipleAnswer = Qest_IsMultipleAnswerBL;
}
Please help me out from this problem

Honestly, I haven't looked too deep, but it looks like that OnCreated is sitting a little far north... You probably want to call it after you're done setting up your variables. Other than that i'd say make sure you're properly initializing everything in the method calling the constructor.

You can call default constructor like this, it works fine for me:
public partial class MyClass
{
public MyClass(string fieldValue1,int fieldValue2)
: this()
{
this.field1= fieldValue1;
this.field2 = fieldValue2;
}
}
If this do the trick, you can read more about using contructors in C# here.

Related

I'm trying to bulk add a csv file to my local DB

I'm trying to read in the contents of a csv file into my DBcontext object.
Here's the declaration:
public DbSet<Wine> Wines { get; set; }
All the relevent, configurations were set. But this code just doesn't seem to be working. And I', not getting any errors either.
Wines.AddRange(from wine in File.ReadLines("C:\\Users\\cochiagha\\source\\repos\\C_sharp_Projects\\wine.csv") // Read a row
let wineVar = wine.Split(',')
select new Wine
{
Name = wineVar[0],
AlcoholContentIndex = float.Parse(wineVar[1]),
MalicAcidConentration = float.Parse(wineVar[2]),
AshIndex = float.Parse(wineVar[3]),
AlcalinityIndexofAsh = float.Parse(wineVar[4]),
MagnesiumReading = float.Parse(wineVar[5]),
TotalPhenolIndex = float.Parse(wineVar[6]),
FlavanoidIndex = float.Parse(wineVar[7]),
NonFlavanoidPhenolIndex = float.Parse(wineVar[8]),
ProanthocyaninsIndex = float.Parse(wineVar[9]),
ColorIntensityIndex = float.Parse(wineVar[10]),
HueIndex = float.Parse(wineVar[11]),
DilutionIndex = float.Parse(wineVar[12]),
ProlineIndex = float.Parse(wineVar[13]),
});
I instantiated an instance of the db context in my Controller file and called the function under a method I qualified as a 'post'. And my changes were saved after.
// bulk read
[HttpGet("[action]")]
public void BulkRead()
{
_WineApiDBContext.readCSV();
_WineApiDBContext.SaveChanges();
}
If you need more clarification, I'd be glad to provide that too.

How to change a ClassificationFormatDefinition

My Visual Studio extension (VSIX) is derived from the Ook Language Example (found here). Basically, I have the following ClassificationFormatDefinition with a function loadSavedColor that loads the color the user has configured. Everything works fine.
[Name("some_unique_name")]
internal sealed class OokE : ClassificationFormatDefinition
{
public OokE()
{
DisplayName = "ook!"; //human readable version of the name
ForegroundColor = loadSavedColor();
}
}
Question: After the user has configured a new color, I like to invalidate the existing instance of class OokE or change the existing instances and set ForegroundColor. But whatever I do the syntax color is not updated.
I've tried:
Get a reference to class OokE and update ForegroundColor.
Invalidate the corresponding ClassificationTypeDefinition:
[Export(typeof(ClassificationTypeDefinition))]
[Name("ook!")]
internal static ClassificationTypeDefinition ookExclamation = null;
After hours of sifting through code I could create something that works. The following method UpdateFont called with colorKeyName equal to "some_unique_name" does the trick. I hope it is useful for someone.
private void UpdateFont(string colorKeyName, Color c)
{
var guid2 = Guid.Parse("{A27B4E24-A735-4d1d-B8E7-9716E1E3D8E0}");
var flags = __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_PROPAGATECHANGES;
var store = GetService(typeof(SVsFontAndColorStorage)) as IVsFontAndColorStorage;
if (store.OpenCategory(ref guid2, (uint)flags) != VSConstants.S_OK) return;
store.SetItem(colorKeyName, new[]{ new ColorableItemInfo
{
bForegroundValid = 1,
crForeground = (uint)ColorTranslator.ToWin32(c)
}});
store.CloseCategory();
}
After setting the new color, you will need to clear the cache with the following code:
IVsFontAndColorCacheManager cacheManager = this.GetService(typeof(SVsFontAndColorCacheManager)) as IVsFontAndColorCacheManager;
cacheManager.ClearAllCaches();
var guid = new Guid("00000000-0000-0000-0000-000000000000");
cacheManager.RefreshCache(ref guid);
guid = new Guid("{A27B4E24-A735-4d1d-B8E7-9716E1E3D8E0}"); // Text editor category

Silverlight DataContext: Changes also being made in Cloned Object

Consider follwing method of copying/cloning an object (all fields are copied into a new object)
public AangepastWerk CloneAdjustedWork(AangepastWerk pAdjustedWork)
{
return new AangepastWerk()
{
AangepastWerkID = pAdjustedWork.AangepastWerkID,
ArbeidsOngeval = pAdjustedWork.ArbeidsOngeval,
DatumCreatie = pAdjustedWork.DatumCreatie,
DatumLaatsteWijziging = pAdjustedWork.DatumLaatsteWijziging,
DatumOngeval = pAdjustedWork.DatumOngeval,
GewijzigdDoor = pAdjustedWork.GewijzigdDoor,
NietErkend = pAdjustedWork.NietErkend,
Stamnummer = pAdjustedWork.Stamnummer,
Verzorging = pAdjustedWork.Verzorging,
VerzorgingId = pAdjustedWork.VerzorgingId
};
}
I have a form that opens up a childform where two objects (2 times the same object of the type mentioned above) is being passed. I open up the form like this:
//my selected Record
Record rec = DateGridAdjustedWorks.ActiveRecord;
AangepastWerk AWorkObject = (AangepastWerk)((DataRecord)rec).DataItem;
AangepastWerk AWorkObjectBackup = _Vm.CloneAdjustedWork(AWorkObject);
WindowModifyAdjustedWork windowForModify = new WindowModifyAdjustedWork(AWorkObject,AWorkObjectBackup, true);
windowForModify.Closing += new CancelEventHandler(OnModifyAWClosing);
windowForModify.ShowDialog();
In that childform I set the first object as DataContext. _adjustedWork and _adjustedWorkCopy are properties of the form
_adjustedWork = pAdjustedWork;
GridAdjustedWork.DataContext = AdjustedWork;
_adjustedWorkCopy = pAdjustedWorkCopy;
The Issue:
In the form i have the ability to alter the object while retaining the original object. the user can see the originalobject, so he has the possibilities to keep track of the changes (request by the user) BUT if i change something in my _adjustedWork (the object that is my datacontext) then my _adjustedWorkCopy (without any actions performed upon it in my code-behind) is changed aswell. My question to you bright minds is: Why does this happen and how do i work around it? What am i missing here (probably something very basic)?
I always do deep cloning with serializing to json.
In example with Servicestack you can:
var json = myObject.ToJson();
var clonedObject = json.FromJson<MyObject>();
return clonedObject;
Maybe this can help.
Found the reason why the Cloned Object recieved the changes as well
public AangepastWerk CloneAdjustedWork(AangepastWerk pAdjustedWork)
{
return new AangepastWerk()
{
AangepastWerkID = pAdjustedWork.AangepastWerkID,
ArbeidsOngeval = pAdjustedWork.ArbeidsOngeval,
DatumCreatie = pAdjustedWork.DatumCreatie,
DatumLaatsteWijziging = pAdjustedWork.DatumLaatsteWijziging,
DatumOngeval = pAdjustedWork.DatumOngeval,
GewijzigdDoor = pAdjustedWork.GewijzigdDoor,
NietErkend = pAdjustedWork.NietErkend,
Stamnummer = pAdjustedWork.Stamnummer,
Verzorging = pAdjustedWork.Verzorging, <------------ Issue lies here
VerzorgingId = pAdjustedWork.VerzorgingId
};
}
pAdjustedWork.Verzorging is an object in this case. I needed to clone this object aswell.I assumed (incorrectly) that cloning as above mentionned would create a new separate 'VerzorgingsObject'.
The solution to my problem is:
MedicalCare_VM mcare_VM = new MedicalCare_VM();
return new AangepastWerk()
{
AangepastWerkID = pAdjustedWork.AangepastWerkID,
ArbeidsOngeval = pAdjustedWork.ArbeidsOngeval,
DatumCreatie = pAdjustedWork.DatumCreatie,
DatumLaatsteWijziging = pAdjustedWork.DatumLaatsteWijziging,
DatumOngeval = pAdjustedWork.DatumOngeval,
GewijzigdDoor = pAdjustedWork.GewijzigdDoor,
NietErkend = pAdjustedWork.NietErkend,
Stamnummer = pAdjustedWork.Stamnummer,
Verzorging = mcare_VM.CloneMedicalCare(pAdjustedWork.Verzorging),
VerzorgingId = pAdjustedWork.VerzorgingId
};
Cloning in:
Verzorging = mcare_VM.CloneMedicalCare(pAdjustedWork.Verzorging)
uses the same logic as mentioned before (copying every field).

Get data from an object and put it in a textbox

I have an object which contains 2 pieces of information in objData[0]. The information is System_ID and Network_ID. The data is coming from a query to a database.
I want to get the data out of the object and display it in two separate text boxes, one for system_ID and one for Network_ID. Right now I am putting them into a combo box.
See below my code:
//get network ID and systenm name
private void cmbAddItem_SelectedIndexChanged(object sender, EventArgs e)
{
FASystems fSys = new FASystems(sConn);
object objData = fSys.getSystemNetworkIDFriendlyName(cmbAddItem.Text.ToString());
cmbNetworkID.DataSource = objData;
cmbNetworkID.DisplayMember = "Network_ID";
cmbSysName.DataSource = objData;
cmbSysName.DisplayMember = "System_Name";
// txtNetworkID.Text = objData[0].Network_ID;
}
Assuming your C# compiler is 3.0 or up use the var keyword on the api call
var objData = fSys.getSystemNetworkIDFriendlyName(cmbAddItem.Text.ToString());
Let's assume you're correct that there is an array now in objData with a type in it that has at least Network_ID as a member...
txtNetworkID.Text = objData[0].Network_ID;
should work then.
Can you post the function declaration for getSystemNetworkIDFriendlyName and show how you are populating the return type?
I recommend creating a new class to store the NetworkID and SystemID
class SystemInfo
{
public string NetworkID { get; set; }
public string SystemId { get; set; }
}
Rewrite the function getSystemNetworkIDFriendlyName to return an instance of SystemInfo. Then populating your textbox becomes:
FASystems fSys = new FASystems(sConn);
SystemInfo inf o= fSys.getSystemNetworkIDFriendlyName(cmbAddItem.Text.ToString());
txtNetworkID.Text = info.NetworkID;
Hope this helps,
KenC

Problem Creating Instances of ASP.NET User Controls Programmatically

I am able to create controls pro grammatically using the code below without issue:
FileListReader fReader = (FileListReader)LoadControl("~/Controls/FileListReader.ascx");
phFileLists.Controls.Add(fReader);
However, I would like to change the control so that I can give it a constructor like this:
public FileListReader(Int32 itemGroupId, Int32 documentType, String HeaderString, String FooterString, bool isAdminUser)
{
base.Construct();
this.itemGroupId = itemGroupId;
this.documentType = documentType;
this.HeaderString = HeaderString;
this.FooterString = FooterString;
this.isAdminUser = isAdminUser;
}
and then I should be able to call the control like this:
FileListReader fReader = (FileListReader)LoadControl(typeof(FileListReader), new Object[] { itemGroupId, 6, "Sell Sheets", "<br /><br />", isAdminUser });
However, when I do this I always get an error that my in page controls within my FileListReader Control have not been instantiated and I get a null reference error. So for example I have an <asp:Label></asp:label> control that errors out when I try to set it's text on the Page_Load method. What is causing this? I figured the base.Construct() would have solved this issue but it obviously has not.
The proper way to inherit a constructor is like this:
class FileListReader : WebControl
{
public FileListReader(Int32 itemGroupId,
Int32 documentType,
String HeaderString,
String FooterString,
bool isAdminUser) : base() // <-- notice the inherit
{
this.itemGroupId = itemGroupId;
this.documentType = documentType;
this.HeaderString = HeaderString;
this.FooterString = FooterString;
this.isAdminUser = isAdminUser;
}
// ... other code here ... //
}
Does changing your constructor like that fix the issue?
I am not sure that calling base.Contruct() is what you should be doing, try calling the default contructor of the base class example below:
public FileListReader(Int32 itemGroupId, Int32 documentType, String HeaderString, String FooterString, bool isAdminUser) :base()
{
base.Construct();
this.itemGroupId = itemGroupId;
this.documentType = documentType;
this.HeaderString = HeaderString;
this.FooterString = FooterString;
this.isAdminUser = isAdminUser;
}

Categories