Assigning Dynamic Variables from an Input Model C# - c#

I am having some issues understanding how I can assign dynamic values from another class into other variables - I have tried using the correct namespaces, correct syntax and reading up on the documentation that the error provides - however no luck even when trying to implement examples shown. I have very little knowledge in regards to C# as I am mainly doing front end, however have to step up and start picking up some Back end oriented things at the company I work at
The current code I have is as follows:
BrazeConnectionInputs.cs
namespace Workflow.Connector.Braze.Models
{
public class BrazeConnectionInputs
{
public string Username { get; set; }
public string Password { get; set; }
}
}
CreateCampaign.cs
public class CreateCampaignRunner
{
private const string Username = BrazeConnectionInputs.Username; // BrazeConnectionInputs.Username errors
private const string Password = BrazeConnectionInputs.Password; // BrazeConnectionInputs.Username errors
}

You need to learn about objects vs classes. You should have an instance of the source class (BrazeConnectionInputs) that might be called something like model.
You can then explicitly assign across by creating a new instance of CreateCampaignRunner like var runner = new CreateCampaignRunner() and then assign the values in a number of ways:
Explicitly like runner.UserName = model.UserName
By using an explicit constructor var runner = new CreateCampaignRunner(model)
Object initializer syntax
Other ways are available
Highly recommend you do a basic C# course

Related

Fixing the deserializing of untrusted data using C#

I have the following relevant C# code:
json = File.ReadAllText(path);
isStudentObject= JsonConvert.DeserializeObject<List<XXStudentCode>>(json).Any(sv => sv.SCODE.Equals(code));
My security software (static code analysis) scans our apps and it does not like the above code, namely ReadAllText part. It says that this is a "high risk deserialization of untrusted data."
So my question is this: how can I refactor this code to make the data "trusted?" I tried different validation methods and it did not work. Any help is appreciated.
Basically search for a way of turn off the warning (through annotation or configuration file). But, before you do this, consider the implications: you should make sure that the data that you read is treated as unsecure. In other words: if, in your "XXStudentCode" object, exists some kind of flag or attribute/property that unlock things like give permission to execute some critical code or access to private things you should make sure that you do not trust the object after serialization.
Ex:
class Person
{
public bool IsAdmin { get; set; }
public string Name { get; set ; }
}
In the example above if the input comes with the attribute 'IsAdmin' with value true and your system treat all "Person's" with this attribute as a admin so you will have a security flaw. To overcome this you should create classes that only contains attributes and properties that you really need to read.
Fixed Ex:
class PersonModel
{
public string Name { get; set ; }
public Person ToPerson()
{
new Person { Name = Name };
}
}
class Person
{
public bool IsAdmin { get; set; }
public string Name { get; set ; }
}
Now, using the PersonModel in the deserialization, the only properties that you really want will be loaded, the rest you be ignored by the serialization library. But, this will not make you free to security flaws. If the deserialization library have some kind of security issue you will be affected too.
Hope this help.

DotLiquid, some beginner questions/observations

I'm investigating using dotliquid to replace a home grown piece of templating code and I'm wondering about the best way to achieve my goal.
The old code used to use sigils in the template and, together with a Dictionary, used regexes to search and replace. So you did something like this in the template file:
Specific error: {#ErrorId#}
Error description: {#Description#}
Additional information:{#AdditionalInformation#}
And in the C# code:
Dictionary<string, string> tokensAndValues = new Dictionary<string, string>
{
{#"ErrorId", errorId},
{#"Description", description},
{#"AdditionalInformation", additionalInformation}
};
I came across dotnetliquid and it appears quite powerful (possibly overkill for my needs?). I've got it working but I want to ask if I'm going about this in the correct fashion?
It appears I'm forced to declare a class viz.
public class EmailTemplateInfo : Drop
{
public string ErrorId { get; set; }
public string Description { get; set; }
public string AdditionalInformation { get; set; }
}
And then use that as follows:
Template.NamingConvention = new CSharpNamingConvention();
Template template = Template.Parse(templateText);
EmailTemplateInfo emailTemplateInfo = new EmailTemplateInfo
{
AdditionalInformation = additionalInformation,
Description = description,
ErrorId = errorId
};
string htmlText = template.Render(Hash.FromAnonymousObject(new {emailTemplateInfo = emailTemplateInfo }));
A few questions:
Is this the correct way to do this? If it is then I'll propose doing an addition to the docs that demonstrates this functionality.
Secondly in the template that I use do I need to qualify the placeholders with the name of the variable like this?
Specific error: {{emailTemplateInfo.ErrorId}}
Error description: {{emailTemplateInfo.Description}}
Additional information:{{emailTemplateInfo.AdditionalInformation}}
I can't see how the naming convention declaration [Template.NamingConvention = new CSharpNamingConvention();] ties in with the template variable declaration below it. Is there some sort of global caching going on?
Yes, inheriting from Drop is one way to do it. The other mechanism that DotLiquid provides is Template.RegisterSimpleType(...) - see the unit tests for examples.
Yes, you do need to qualify property names with the name of the variable, as in your example. The alternative would be to create a Hash containing top-level keys for AdditionalInformation, Description, ErrorId, and pass that to template.Render(...). You can do that using Hash.FromDictionary(...), as shown here.
The naming convention doesn't have a connection to the variable declaration. The naming convention is only used when resolving property names. For example, if you used RubyNamingConvention, then you'd need to write {{ emailTemplateInfo.additional_information }} in your template.

I can't get a MongoDB "find" query to work using C#

I am trying to make a frontend for a MongoDB database using C#.
So far I have managed to get the connection and the insert method to work.
But I'm stuck with the find method as I am new to C# and .net in general.
public void FindDocument(string query) {
BsonDocument QueryDoc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(query);
MongoCursor result = Collection.FindAs(QueryDoc);
The last line is giving me a really long error:
the type arguments for the method 'MongoDB.Driver.MongoCollection.FindAs<TDocument>'(MongoDB.Driver.IMongoQuery) can't be inferrred from usage. Try to specify the type arguments explicitly)
I'm completely lost here. If it is necessary, I can post the entire class here. Let me know. I'm using this driver by the way: CSharpDriver-1.10.0 from https://github.com/mongodb/mongo-csharp-driver/releases
FindAs expects you tell what type (class) you're expecting, so you'd have to call something like Collection.FindAs<MyClass>(query).
However, your code seems a little more complex than necessary. It's usually easier to work with your classes directly and use QueryBuilders to create the query (they can also be passed to other methods as IMongoQuery).
class MyClass {
public ObjectId Id { get; set; }
public ObjectId UserId { get; set; }
public string Description { get; set; }
// ...
}
var coll = mongoDb.GetCollection<MyClass>("MyClass");
var result = coll.Find(Query<MyClass>.EQ(p => p.UserId == someId));
// result is now a MongoCursor<MyClass>
Also, please note that a completely new, async-aware version of the C# driver, is already in beta (currently 2.0.0-beta4). The interface has changed completely, so if you're starting now, it's probably easier to (only) learn the new interface.

C# - snippet or template to assign all fields/properties quickly?

Quick points for someone who might know the answer - is there a snippet or tool that can quickly generate template code to assign all public fields and/or properties of an object?
Example:
public class SomeBloatedClass
{
public string SomeField1 { get; set; }
public int SomeField2 { get; set; }
// etc...
public string SomeField99 { get; set; }
}
public class TestHarness
{
public SomeBloatedClass CreateTestObject()
{
// Is there a snippet/macro/template that can generate the code to assign
// all public fields/properties so they can be manually assigned quickly?
// Something like this...?
// *Begin auto-generated code
SomeBloatedClass s = new SomeBloatedClass();
s.SomeField1 = ;
s.SomeField2 = ;
// etc..
s.SomeField99 = ;
// *End auto-generated code
return s;
}
}
Third-party tools are fine as long as they integrate into Visual Studio.
Edit: I'm just looking to have the tool create empty assignment statements that I could quickly hand-edit with the appropriate values. Ideally, the solution would use the built-in snippet mechanism to navigate from statement to statement via the TAB key - I couldn't represent that clearly using StackOverflow's editor, but if you've used snippets you should know what I mean).
There is small snippet or tool that can quickly generate template code to assign all public fields and/or properties of an object?
c# property assigner tool.
and behalf of it we can also generate properties of c# ex.( get set )
c# property generator

Custom organized data accessing via classes and constructors

struggling To achieve a solution for a basic Task:
working with more than one Sql Data table, as a source, for a WebSite application...
that's what leads me here once again... seeking for an Experienced C# .net Developers Help.
i was just trying to add some basic logic for a proper implementation,Like using
a dedicated namespace & classes, To Hold reference for All DATABASE tables,
(before i try working / learning about Entities Framework approach.)
i would like to try implement same of basic features of EF ...by my self, and that way... i will also learn how to properly work with classes.
as it is so far ... structured : with my little knowledge
a 'helper'.. namespace , say the company name is: HT technologies
so I've named the namespace HT_DbSchema ...that contains :
tables names
public sealed class HTDB_Tables
{
public const string Customers= "Customers";
public const string Times= "Times";
}
tables IDs
public sealed class HT_tblIDs
{
public const int tblCustomersID = 1, tblTimesID = 2;
}
tables Columns Lists ...(just one example)
public class HTDB_Cols
{
public class tblCustomers
{
public const string CustId = "custId",
CustName = "custName",
CellPhone = "cellPhone" .... etc'
}
}
and as all those 3 classes are serving all projects ..
there's another helper class for constructor Per Table For the Current Project
public class DBMetaDetails
{
public struct DbTable
{
public string TableName { get; set; }
public int TableID { get; set; }
}
}
so still these are all construction / helpers Classes and are separated from the project,
now for current project
What is The Appropriate way to get it done, using above Classes and constructor within a project
(i could name those templates)
what i was doing so far to implement some order is :
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
.... some other App inits here
}
else
{
}
// this method should be the one that instanciates the DbTable struct
//and set the values of tables name and "ID"
setTablesReferences();
}
And Here's where the confusion starts :
in a day by day usage i want to try implement it in a WebSite application :
public void setTableReferences()
{
DBMetaDetails.DbTable CustMeta = new DBMetaDetails.DbTable();
DBMetaDetails.DbTable TimesMeta = new DBMetaDetails.DbTable();
}
so now i need to set CustMeta & TimesMeta details(ids & names)
the struct has a kind of a template structure a kind'a systematic technique to initialize and assign values, so it brings some decent order to my logic with it's existence .
so what is the confusing part ?
from one point of view(safety), i need those tables detailes to be readonly
so DbTable.TableID, and DbTable.TableName would not get overWriten by mistake.
having said that, there should be only one place it could be SET ... a dedicated section of the application, like setTableReferences() above,... there i might add :
CustMeta.TableID = HT_tblIDs.tblCustomersID
CustMeta.TableName = HTDB_Tables.Customers;
on the other hand, i need the information of the tables to be Accessible,
so if let's say i would like to add those DataTables into a DataSet
DataSet ALLTablesSet = new DataSet();
// assuming the SQL actions already been taken in another method previosly...
// so DataTable is already retrived from DB
//...but only as a short usage example:
AllTablesSet.Tables.Add(new DataTable(CustMeta.TableName));
My Question is What is the Correct Way to work with structs ... as in My Scenario,
So in one section of app: you would initialize - assign it with a value privately.
and from other sections of the app you could use its value (Only For Readings)
so that way, the application will not be able to access it's value for writing,
only by reading values, i think it should be trough another (Public ReadOnly) Variable.
so that variable was meant to be exposed ...and it's value could not be "harmed"
If I understand the question correctly, the way I would prevent other code from modifying it is by removing the setters on the properties. However, you still need to set them at some point, so rather than removing the setters completely, you can just make them private. For example:
public string TableName { get; private set; }
If you do this, the only place you can set this data is within the struct itself, so you would need to create a constructor that took the initial values you wanted. So something like:
public struct DbTable
{
public DbTable(string tableName, int tableId)
{
this.TableName = tableName;
this.TableID = tableId;
}
public string TableName { get; private set; }
public int TableID { get; private set; }
}

Categories

Resources