Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
H

hpjchobbes

@hpjchobbes
About
Posts
44
Topics
22
Shares
0
Groups
0
Followers
0
Following
0

Posts

Recent Best Controversial

  • Is there a need for separate SignInManager<TUser> and UserManager<TUser>?
    H hpjchobbes

    I have been looking at the code that gets generated when you add new scaffold items for Identity into an web application. I notice that often a UserManager<TUser> gets injected along with a SignInManager<TUser>. It seems that the SignInManager has a property for UserManager. Is there a reason to have them injected separately instead of just injecting and using the SignInManager? Can there be situations where the UserManager property is null in the SignInManager but would have been injected into the constructor?

    // Should we always have a separate _userManager injected?
    var userId = await _userManager.GetUserIdAsync(user);

    // Or would this also work, but some may not like the multiple chaining?
    var userId = await _signInManager.UserManager.GetUserIdAsync(user);

    .NET (Core and Framework) question

  • Updating properties in a IEnumerable
    H hpjchobbes

    Could you explain a bit more what you mean by 'data driven with a proper query'? Almost every tutorial/example I've found only seems to be basic "Can Access/Can Not Access", but my needs are more granular. I'm currently using CQRS to have my Controller send an EmployeeQuery request. I've added a pipeline to the request handler which has my security logic and updates the results from the query as I need to apply information not just to the records themselves, but also potentially individual properties of the record. I didn't want to mix my security logic in with my query as I thought that could get hard to expand in the future. Here's an example of the current rules/permissions: - Admin : Full Create, Read, Update, (Soft/Hard) Delete. - HR : Full Create, Read, Update, Soft Delete. - Manager : Full Read (of specific columns), Update of their own record (excluding some columns). - User : Full Read (of specific columns different than Manager), Update of their own record (excluding some columns). I'm using EFCore and LINQ for the query and I had first thought about trying to have the security logic in the pipeline 'build' the IQueryable that will get executed by the query handler, but I haven't found a good resource on how to do that, so I am updating the results of the handled query before sending it back to the Controller.

    C# security performance help announcement

  • Updating properties in a IEnumerable
    H hpjchobbes

    I have an IEnumerable that I need to update some fields based on the user's security permissions. If a user is in the Admin or HR roles, the CanEdit and CanDelete properties should be set to true. If the user is not Admin or HR, but is their own record, CanEdit should be true. I have come up with two options, and wanted to know which would be considered the better method (or a different way) for speed, readability, and maintainability. Method 1 first checks if the user is Admin or HR, then loops through the entire collection and updates the values. If the user is not Admin/HR, then it checks each record to see if it is the users and updates. Currently, a user can only have one record, so I quit once I update the matching employee record.

    // Admin and HR are allowed to edit and delete all records
    if(_userManager.User.IsInRole("Admin") || _userManager.User.IsInRole("HR"))
    {
    foreach(var employeeRecord in employeeList)
    {
    employeeRecord.CanEdit = employeeRecord.CanDelete = true;
    }
    return employeeList;
    }

    // Users are allowed to edit their own record.
    foreach(var employeeRecord in employeeList)
    {
    if(employeeRecord.WorkEmail.Equals(_userManager.User.Identity.Name, StringComparison.OrdinalIgnoreCase))
    {
    employeeRecord.CanEdit = true;
    return employeeList;
    }
    }

    // This return is needed in case there is no user record found.
    return employeeList;

    Method 2 stores a boolean if the user is an Admin/HR, and just sets that as the permission, then checks if the current employeeRecord belongs to the user and sets the permission.

    bool hasEditDeletePermission = _userManager.User.IsInRole("Admin") || _userManager.User.IsInRole("HR");

    foreach(var employeeRecord in employeeList)
    {
    employeeRecord.CanEdit = employeeRecord.CanDelete = hasEditDeletePermission;

    if(\_userManager.User.Identity.Name.Equals(employeeRecord.WorkEmail, StringComparison.OrdinalIgnoreCase))
    {
        // Users can edit their own record
        employeeRecord.CanEdit = true;
    }
    

    }

    return employeeList;

    Method 2 seems shorter and easier to understand, but Method 1 can be faster when the user isn't Admin or HR, which would happen more often. There's also the issue that Method 1 leaves the CanEdit/CanDelete values to whatever they were originally supplied as (currently defaults to false), where as Method 2 will always override any preexisting values which might cause unexpected behav

    C# security performance help announcement

  • Serialize class with multiple different schemas
    H hpjchobbes

    The error is from the API. If I include a field in a request the entire request will be rejected. For example, in a Delete request I can ONLY pass the saved ID of this record. If I include any other information besides the ID (like the name of the customer) the entire request is rejected. If I include a blank tag in an Add request it gets rejected instead of ignored. If I don't include the ID in a Modification request, the request gets rejected. In this API, a Customer for example can be Added which has one XML Schema, if it already exists then I need to use the Mod XML schema which is slightly different. If I want to delete this Customer, then I have to use the Del XML Schema. All of the data for these schema are coming from my single customer instance.

    C# xml json database sales help

  • Serialize class with multiple different schemas
    H hpjchobbes

    The API that I am using takes an XML string. The XML string is based on what request I am trying to do. So, if I have an instance of a customer in my application that does not yet exist in the API software, I create an AddRq XML string, which has all of the fields for the customer:

    John Smith
    1
    ...
    

    Once I process this Add request, I get the ID associated with it, which I save in my custom object. If I then decide I want to update the customer record, I need to pass an slightly different XML string:

    456
    John H. Smith
    1
    ...
    

    In my application, I still have just the one instance of this customer. Also, if I am wanting to delete this customer from the API software, I would pass this request:

    456
    

    In each of these cases I have to be specific about which fields get included in the request or it will be rejected. If I were to include any other fields besides the ID in the delete request, the entire request is rejected and ignored. There's also some other factors based on the version of the API that might be in use. For example, they added a feature for tracking Currency in version 12, but if my customer is still using version 11, I need to never include the Currency field in my Add or Mod request or the entire request is rejected.

    C# xml json database sales help

  • Serialize class with multiple different schemas
    H hpjchobbes

    I have an API that I am trying to use that uses XML for it's requests. Each of these objects have multiple different requests (Add, Modify, and Delete), along with different versions that may exclude some fields. Is there a way to utilize serialization with different schema to account for these differences? For example, using the following Customer object:

    public class Customer
    {
    public int ID;
    public string EditSequence;
    public string Name;
    public bool IsActive;
    public int? ParentID;
    }

    On a Delete request, I have to only supply the ID and the EditSequence fields. If I include the other fields, I get an error. For an Add I need to include all of them. Also, for null fields, they can not be included at all (i.e. no element). I don't think this is possible with regular XML serialization and I'll probably have to code this myself. If so, I was thinking of using custom attributes and reflection. Is there perhaps a better way to accomplish what I am trying?

    C# xml json database sales help

  • Attributes on fields in a DataTable/DataRow
    H hpjchobbes

    I am using a DataRow to get and set values (based on the manually typed data table from How to Manually Create a Typed DataTable[^]. The fields in the datarow can have different attributes that I would need to track, the main one being a maximum number of characters for some strings, but different versions have different lengths. I was trying to use Attributes to help with this, but I am stuck with how to be able to set/determine the 'version' when going through the attributes. I'd like to be able to set the version on the dataset as a whole and have the fields of the data row be able to use that to determine how to get values. Here's how I setup my attribute class:

    [AttributeUsage(AttributeTargets.Property, AllowMultiple =true)]
    public class MaxLengthAttribute : Attribute
    {

    public string Version;
    public int MaxLength;
    
    public MaxLengthAttribute(string version, int max)
    {
       Version= version;
       MaxLength = max;
    }
    

    }

    Here's what the data row looks like and how I am envisioning this would work.

    public CustomerRow : DataRow
    {
    [MaxLength("1.0", 40)]
    [MaxLength("2.0", 45)]
    public string Name
    {
    get
    {
    if(base["Name"] == DBNull.Value) throw new NullException("Name is null.");
    return ((TruncatedString)base["Name"]).Value;
    }
    }
    }

    I created a class called TruncatedString that has a string and bool, which i am using as the data type for the field in the data row. In the TruncatedString I am trying to get the version of the data set and the max length attribute to find out how long my field can be:

    public class TruncatedString
    {
    public bool AutoTruncate;
    private string _Value;
    public string Value
    {
    get
    {
    if(AutoTruncate)
    {
    int maxLength = ???
    // How to get the version from the DataSet
    // And the MaxLength attribute for the field in the data row
    if(maxLength >= 0 && Value.Length > maxLength) return _Value.Substring(0, maxLength);
    }
    return _Value;
    }
    set { _Value = value; }
    }
    }

    I am not sure if Attributes are the best way to go with this set

    C# help com tutorial question announcement

  • COM object that has been separated from its underlying RCW cannot be used.
    H hpjchobbes

    I am using a third party reference, which is a COM object. The COM object has an Open and Close function and I need to make sure that Close is always called whenever possible. I wrote a wrapper class that implements IDisposable and in the Dispose function, I try to call the Close function. However I get a System.Runtime.InteropServices.InvalidComObjectException when I try to call the close function with additional details of "COM object that has been separated from its underlying RCW cannot be used."

    public class MyWrapper : IDisposable
    {
    private Session _mySession = new Session(); // This is the COM object

    public void Open() { \_MySession.Open(); }
    public void Close() { \_MySession.Close(); }
    
    public void Dispose() {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    
    public void Dispose(bool disposing) {
        \_MySession.Close(); // Calling close without having called open is OK
    }
    ~MyWrapper() { Dispose(false); }    
    

    }

    From my (limited) understanding, there are two reasons why I am getting the exception. 1) The Finalizer is running and calling the destructor, but because the finalizer is on a separate thread I get the error. 2) Based on this Stack Overflow[^] post, the Runtime Callable Wrapper (RCW) has it's own finalizer which is being called before mine, and getting rid of the COM object. I don't know if either of these, or both of these are true, but what is the recommended way to implement a COM object that needs to have finalizer code run?

    C# question com data-structures help

  • Calling class function vs function getting class variables
    H hpjchobbes

    I actually never thought about it being a separate database, as I was thinking more in a video game setting. The thought came up when looking at a park simulation (Planet Coaster) and trying to decide how I would tackle the same situation. Like I said, I don't have a project that has run into this situation, but I'm curious about how I would approach this concept. In this case the function doesn't really care about the result, just the computation. Is there a word or definition for this concept of 'figuring out how best to store and manipulate data' in programming terminology? I feel as I am floundering when it comes to these thoughts. How to best approach data structure and program structure. I feel like an idiot as I have no idea what words to use when asking about this kind of situation.

    Design and Architecture workspace visual-studio design tutorial question

  • Calling class function vs function getting class variables
    H hpjchobbes

    This is more of a general design concept, but if I had a class which I intend to have a list of those objects (around 5000) and I need to perform some function on each of these, should I be designing around a function that is part of the class or a separate function that takes a collection of these objects? I know that there's always situations where one may be better than another, but when first starting to think about the design, which way would be recommend For example:

    class Person {
    float HungerLevel;
    public void AdjustHunger(float amount) { HungerLevel += amount; }
    }

    public void AdjustAllHunger(List PersonList, float amount) { foreach(Person in PersonList) { Person.AdjustHunger(amount); } }

    or

    class Person {
    float HungerLevel;
    public void AdjustHunger(float amount) { HungerLevel += amount; }
    }

    public void AdjustAllHunger(List PersonList, float amount) { foreach(Person in PersonList) { Person.HungerLevel += amount; } }

    I would imagine that the second option is more efficient if I need to change all objects in the collection by the same value, but not sure. I guess it could even depend on what language I'm using and how it would try to optimize the code? Does a call to a function have a higher cost than a call to an object's variable? Expanding on this example, what if the hunger change was based on another of the objects variables.

    class Person{
    float HungerLevel;
    float Metabolism;
    public void AdjustHunger(float amount) { HungerLevel += (amount * Metabolism); }

    public void AdjustAllHunger(List PersonList, float amount) { foreach(Person in PersonList) { Person.AdjustHunger(amount); } }

    vs.

    class Person{
    float HungerLevel;
    public void AdjustHunger(float amount) { HungerLevel += amount; }
    }

    public void AdjustAllHunger(List PersonList, float amount) { foreach(Person in PersonList) { Person.HungerLevel += (amount * Person.Metabolism); } }

    I don't have a project right now that deals with this, but the concept popped into my head and I was thinking about how I would start designing this. I could probably setup a test case and try it out with a sample, but is that what most programmers do at the designing stage, creating multiple test implementations? Is there some sort of 'design theory' that I would/should be using? I'm self taught, so I don't know if this would be something that is covered in a more structured training environment (so please excuse me if this is a dumb quest

    Design and Architecture workspace visual-studio design tutorial question

  • ColumnMapping to properties of an class object
    H hpjchobbes

    I have a class like so:

    public class BaseRef
    {
    public int id {get; set;}
    public string listID {get; set;}
    public string Name {get; set;}
    }

    And have a data column that is of type BaseRef that I added to a DataTable:

    this.Columns.Add(new DataColumn("ParentRef", typeof(BaseRef)));

    I am using OdbcDataAdapter to get a query, but in this case my query has three separate columns for the id, listID and Name fields of the Parent:

    SELECT id, listID, Name FROM ParentTable

    I tried to setup a DataAdapterTableMapping and add ColumnMappings, but it doesn't appear that I can map a source column to a property of a class column. I tried:

    mapping.ColumnMappings.Add("id", "ParentRef.id");
    mapping.ColumnMappings.Add("listID", "ParentRef.listID");
    mapping.ColumnMappings.Add("Name", "ParentRef.Name");

    Is there a way to get the mapping to map to the properties of my class?

    C# database question workspace

  • WinForms bind Combobox to DataSet Table Names
    H hpjchobbes

    Is there an easy way to bind a combobox to populate with the names of the tables in a given dataset? When I search all I am finding are questions and examples of binding to a datatable, not the names of the tables in a dataset. I was hoping for something similar to when debugging in Visual Studio and you have a watch on a dataset. When you examine the value, you get a dropdown with the table names, and switching will show you the data table in a datagrid view. I currently clear the items from the combobox, and iterate through the table names adding them to the combobox. When the combobox changes I then set my datamember of my grid view to be dataset[combobox1.SelectedItem.ToString], which works but feels clunky. My application will be using different typed datasets so I need to be able to change the combobox when the dataset changes.

    C# csharp css visual-studio wpf winforms

  • IDisposable with COM
    H hpjchobbes

    I never knew that about the debugger, thanks! But then does this mean that GC doesn't do any cleanup? Or is Visual Studio maintaining the information so it knows to release any allocated memory? Is this something to do with the VS Hosting Process? If I open a file within a using statement, it seems like stopping the debugger is still releasing the file handle (at least I think so, I'm still very new). Are there any recommendations / best practices when dealing with situations like this?

    C# com regex question

  • IDisposable with COM
    H hpjchobbes

    I have an application that uses a COM object to make a connection to an application. I need to make sure that when my application ends that I call the EndSession and CloseConnection methods of this COM object. I was reading this article: Implementing IDisposable and the Dispose Pattern Properly[^] as I think this is what I would need to do to make sure my closing code always gets called, but it doesn't seem to happen when I stop debugging. The application that I am connecting to still thinks my program is connected. It seems like when I stop debugging (or if I have a program crash, that the Dispose methods don't get called. I also tried to add a Finalizer but that causes a System.Runtime.InteropServices.InvalidComObjectException stating that the COM object that has been separated from it's underlying RCW cannot be used.

    private bool disposed;
    protected virtual void Dispose(bool disposing)
    {
    if (!disposed)
    {
    if (_Session != null) // _Session is the COM object.
    {
    _Session.EndSession(); // These are the COM functions to close and end the
    _Session.CloseConnection(); // session that must be called, but this is where I
    _Session = null; // get the InvalidComObjectException.
    }
    disposed = true;
    }
    }
    public void Dispose()
    {
    Dispose(true);
    GC.SuppressFinalize(this);

    }
    ~SessionConnection() // This was added, which seems to be the root cause of the COM exception
    {
    Dispose(false);
    }

    I'm not sure what is the best way to ensure that the EndSession and CloseConnection methods of my COM object get called even if my program crashes or I stop debugging.

    C# com regex question

  • C# creating my own class that acts like a string
    H hpjchobbes

    No, I just didn't even think about this, or even know that it was possible. I'm reading more about `implicit`, which seems very useful. It doesn't seem to be touched on in most 'beginner' reading, though.

    C# csharp com tutorial

  • C# creating my own class that acts like a string
    H hpjchobbes

    So the idea would be to include a public property, but still have the implicit operator act on that property? Would that then allow someone to either use the implicit operator or the property directly?

    C# csharp com tutorial

  • C# creating my own class that acts like a string
    H hpjchobbes

    Thanks, this seems to be just what I need, though I imagine that I need to save the actual string value and have the constructor set that value and the operator string(CustomString s) return the string instead of an empty string?

    class CustomString
    {
    private string _value;

    private CustomString(string s)
    {
        \_value = s;
    }
    
    public static implicit operator CustomString(string s)
    {
        return new CustomString(s);
    }
    
    public static implicit operator string(CustomString s)
    {
        return s.\_value;
    }
    

    }

    Would I also be able to implement INotifyPropertyChanged with this class? I don't see how as there's no public property. Would I just use "_value" even though it's private?

    C# csharp com tutorial

  • C# creating my own class that acts like a string
    H hpjchobbes

    I am trying to create some classes that act like a string, but allow me to test the type at a later date. Because string and String are sealed, I can't seem to inherit from them. I also found out you can't override the assignment operator. I found something close to what I want here on stackoverflow, but it uses structs which can't be inherited. Here's a example of what I want to do, but I can't figure out how:

    public class ORSerialLotNumber : string {}
    public class SerialNumber : ORSerialLotNumber {}
    public class LotNumber : ORSerialLotNumber {}

    // ......

    List mySLNList = new List();
    SerialNumber sNum1 = "Sd-23s-3sf";
    LotNumber nNum1 = "2342434";

    mySLNList.Add(sNum1);
    mySLNList.Add(nNum1);

    // ......

    foreach(var v in mySLNList)
    if(v.GetType() == typeof(SerialNumber))
    string serial = v;
    if(v.GetType() == typeof(LotNumber))
    string lot = v;

    C# csharp com tutorial

  • Track two types of values within one variable
    H hpjchobbes

    Thanks for the code! That would work as a temporary solution, I think! It's sounding like I should really start looking into abstract classes/properties for this type of need! I haven't gotten that far yet in my learning, but it's going to be my next topic for sure!

    C# beta-testing question code-review

  • Track two types of values within one variable
    H hpjchobbes

    Thanks for responding! I haven't really gotten to learning a lot about interfaces (or abstract classes), but I am thinking that will be the next topic I tackle. The reason for this setup is because I am interacting with another software, and that software has one value that represents either a dollar value or a percentage. For example, this is how it would show a transaction:

    Widget $12.00
    Shipping $3.95
    Subtotal $15.95
    Tax 8.875%
    Total $30.11

    When I get this information from the program, they have a rate class that contains three members, an enum for the price type (dollar or percent), a double for the Dollar value, and a double for the Percent value. Because the line can only be a dollar or value and not both, one of the doubles will always be null. I get the feeling (but I may be wrong) that they way they did their setup isn't the best. I will probably implement a Rate class that contains an enum and a double, which should work, but if there is a 'better' way to do this, I would prefer to learn about that type of implementation.

    C# beta-testing question code-review
  • Login

  • Don't have an account? Register

  • Login or register to search.
  • First post
    Last post
0
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups