VS 2012 - C# question on configuration files

  • I have a VS 2012 C# webpage project that pulls SQL Server job names into the webpage and prints the next scheduled date they are running. The problem I'm running into is if one of the job names changes, then the entire webpage fails. The code I'm using is like this:

    public partial class JobDates : System.Web.UI.Page

    {

    public string[] JobNames = new string[] {

    "Job1","Job2","Job3"

    };

    <!-- Skip some other code -->

    private void getjobdates()

    {

    using (var sqlC = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["MyProd"].ConnectionString))

    {

    var cmd = new SqlCommand

    {

    CommandText = "Database.dbo.spFindNextScheduledJobRunDate",

    CommandType = CommandType.StoredProcedure,

    Connection = sqlC

    };

    cmd.Parameters.Add("@JobName", SqlDbType.VarChar, 200);

    sqlC.Open();

    foreach (string jobschedule in JobNames)

    {

    cmd.Parameters[0].Value = jobschedule;

    object returnValue = cmd.ExecuteScalar();

    string returnjobschedule = (string)returnValue;

    string jobresponse;

    DateTime curdate = Convert.ToDateTime(returnjobschedule);

    string monthname = "";

    monthname = curdate.ToString("MMMM").Substring(0, 3);

    switch (returnjobschedule)

    {

    case "01/01/1900": jobresponse = "NOT SCHEDULED";

    break;

    default: jobresponse = monthname + " " + returnjobschedule;

    break;

    }

    switch (jobschedule)

    {

    case "Job1": this.J1.Text = Page.ResolveClientUrl(jobresponse);

    break;

    case "Job2": this.J2.Text = Page.ResolveClientUrl(jobresponse);

    break;

    case "Job3": this.J3.Text = Page.ResolveClientUrl(jobresponse);

    break;

    }

    }

    }

    }

    What I want to do is similar to what we can do in SSIS. Put the variable / string data into a config file so if a job name changes, I only have to change the config file. Not open up the code, fix it, and push it through SDLC all over again. The thing is, I can find out how to get the connection strings into a config file (we've already got that set up). What I can't find is anything on how to get the variable data into a config file.

    Thoughts? Web links?

    Brandie Tarvin, MCITP Database AdministratorLiveJournal Blog: http://brandietarvin.livejournal.com/[/url]On LinkedIn!, Google+, and Twitter.Freelance Writer: ShadowrunLatchkeys: Nevermore, Latchkeys: The Bootleg War, and Latchkeys: Roscoes in the Night are now available on Nook and Kindle.

  • Nevermind. One of our developers finally responded to my request for assistance and is sending me an example of what I need.

    Brandie Tarvin, MCITP Database AdministratorLiveJournal Blog: http://brandietarvin.livejournal.com/[/url]On LinkedIn!, Google+, and Twitter.Freelance Writer: ShadowrunLatchkeys: Nevermore, Latchkeys: The Bootleg War, and Latchkeys: Roscoes in the Night are now available on Nook and Kindle.

  • Hrm. Okay. Solution is PARTIALLY working. For using single valued app keys, I have no problem. Example:

    In the config file

    <appSettings>

    <add key="JobNamesServerA" value="Job1A" />

    </appSettings>

    In the webpage

    public partial class JobDates : System.Web.UI.Page

    {

    public static string SvrAJobNames= ConfigurationManager.AppSettings["JobNamesServerA"];

    private void getServerAjobdates()

    //<!-- Skip some other code -->

    {

    using (var sqlC = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ExceptionSearchAppPROD"].ConnectionString))

    { var cmd = new SqlCommand

    {

    CommandText = "Database.dbo.spFindNextScheduledJobRunDate",

    CommandType = CommandType.StoredProcedure,

    Connection = sqlC

    };

    cmd.Parameters.Add("@JobName", SqlDbType.VarChar, 200);

    sqlC.Open();

    object returnValue = SvrAJobNames;

    string returnjobschedule = (string)returnValue;

    string jobresponse;

    DateTime curdate = Convert.ToDateTime(returnjobschedule);

    string monthname = "";

    monthname = curdate.ToString("MMMM").Substring(0, 3);

    switch (returnjobschedule)

    {

    case "01/01/1900": jobresponse = "NOT SCHEDULED";

    break;

    default: jobresponse = monthname + " " + returnjobschedule;

    break;

    }

    this.SvrA.Text = Page.ResolveClientUrl(jobresponse);

    }

    }

    // more code follows

    The above has no errors showing. But when I try and use my multiple job names (like in the first post), the config file won't let me set the value= to multiple strings. Now I don't know if I can use an array with an app key setting and the Dev told me to put the job names as one single value delimited by commas. So I did that.

    //Config File

    <appSettings>

    <add key="JobNamesServerB" value="Job1B,Job2B,Job3B, Job 4B" />

    </appSettings>

    //Webpage code

    public partial class JobDates : System.Web.UI.Page

    {

    public static string SvrBJobNames = ConfigurationManager.AppSettings["JobNamesServerB"];

    public string[] MyJobs = SvrBJobNames .Split(new char[15]), {",", StringSplitOptions.RemoveEmptyEntries);

    Here's where I'm running into the issue.

    If I try and use new string[15] after the Split, I get an error saying "The best overloaded method match for 'string.Split(params char[])' has some invalid arguments and the whole SvrBJobNames .Split(new char[15]) is underlined in red.

    If I try it with the above with [] (blank) for either string or char, I get "Wrong number of indices inside []; expected 1".

    If I try it with the char[15], it complains at the start of the curly brackets with a "Identifier expected" and then underlines RemoveEmptyEntries and tells me that "'System.StringSplitOptions.RemoveEmptyEntries' is a 'field' by is used like a 'type'".

    And if I try this whole thing without the comma between the Split definition and the curly brackets, I get "; expected" at the first curly bracket and the RemoveEmptyEntries error remains the same.

    This is a wee bit frustrating as I'm following instructions I got from MSDN to try and split the string.

    Thoughts?

    Brandie Tarvin, MCITP Database AdministratorLiveJournal Blog: http://brandietarvin.livejournal.com/[/url]On LinkedIn!, Google+, and Twitter.Freelance Writer: ShadowrunLatchkeys: Nevermore, Latchkeys: The Bootleg War, and Latchkeys: Roscoes in the Night are now available on Nook and Kindle.

  • Oh you are going to be super frustrated.

    public string[] MyJobs = SvrBJobNames .Split(new char[15]), {",", StringSplitOptions.RemoveEmptyEntries);

    You are missing your closing } in your array declaration. Not sure how you managed to get this to compile to be honest.

    This code worked perfectly for me.

    string SvrBJobNames = ConfigurationManager.AppSettings["JobNamesServerB"];

    string[] MyJobs = SvrBJobNames.Split( new string[]{","}, StringSplitOptions.RemoveEmptyEntries);

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/

  • Or

    string[] MyJobs = SvrBJobNames.Split(',');

    if there are no empty entries 😉

    Far away is close at hand in the images of elsewhere.
    Anon.

  • Sean Lange (10/30/2015)


    Oh you are going to be super frustrated.

    public string[] MyJobs = SvrBJobNames .Split(new char[15]), {",", StringSplitOptions.RemoveEmptyEntries);

    You are missing your closing } in your array declaration. Not sure how you managed to get this to compile to be honest.

    Umm, it's not compiling. That's the problem. @=) Lots of red in my coding screen.

    Sean Lange (10/30/2015)


    This code worked perfectly for me.

    string SvrBJobNames = ConfigurationManager.AppSettings["JobNamesServerB"];

    string[] MyJobs = SvrBJobNames.Split( new string[]{","}, StringSplitOptions.RemoveEmptyEntries);

    And my comma was in the wrong place too. After the ] instead of after the }.

    I knew it had to be simple, but I just couldn't get it to work! Thanks, Sean. I appreciate it.

    Brandie Tarvin, MCITP Database AdministratorLiveJournal Blog: http://brandietarvin.livejournal.com/[/url]On LinkedIn!, Google+, and Twitter.Freelance Writer: ShadowrunLatchkeys: Nevermore, Latchkeys: The Bootleg War, and Latchkeys: Roscoes in the Night are now available on Nook and Kindle.

  • David Burrows (10/30/2015)


    Or

    string[] MyJobs = SvrBJobNames.Split(',');

    if there are no empty entries 😉

    Hrmm. You have a point. I think I was misinterpreting what the RemoveEmptyEntries meant. Thank you for commenting on that.

    Brandie Tarvin, MCITP Database AdministratorLiveJournal Blog: http://brandietarvin.livejournal.com/[/url]On LinkedIn!, Google+, and Twitter.Freelance Writer: ShadowrunLatchkeys: Nevermore, Latchkeys: The Bootleg War, and Latchkeys: Roscoes in the Night are now available on Nook and Kindle.

  • #HEADDESK

    I just realized. Here I am passing in my job names through the config file so that I can change just the config instead of the webpage code when someone changes a job name, but I still have job names hardcoded in a freaking CASE statement so I know where to put the schedule information.

    Fixing one hardcode issue won't resolve the other. sigh.

    switch (jobschedule)

    {

    case "Job1 Name": this.J1A.Text = Page.ResolveClientUrl(jobresponse);

    break;

    case "Job2 Name": this.J2A.Text = Page.ResolveClientUrl(jobresponse);

    break;

    }

    Any suggestions on this one? They resolve to objects within the webpage.

    Brandie Tarvin, MCITP Database AdministratorLiveJournal Blog: http://brandietarvin.livejournal.com/[/url]On LinkedIn!, Google+, and Twitter.Freelance Writer: ShadowrunLatchkeys: Nevermore, Latchkeys: The Bootleg War, and Latchkeys: Roscoes in the Night are now available on Nook and Kindle.

  • Brandie Tarvin (10/30/2015)


    #HEADDESK

    I just realized. Here I am passing in my job names through the config file so that I can change just the config instead of the webpage code when someone changes a job name, but I still have job names hardcoded in a freaking CASE statement so I know where to put the schedule information.

    Fixing one hardcode issue won't resolve the other. sigh.

    switch (jobschedule)

    {

    case "Job1 Name": this.J1A.Text = Page.ResolveClientUrl(jobresponse);

    break;

    case "Job2 Name": this.J2A.Text = Page.ResolveClientUrl(jobresponse);

    break;

    }

    Any suggestions on this one? They resolve to objects within the webpage.

    A number of possibilities come to mind but they all require a little bit more info. Can you post more of the code so we can get an idea of what you are doing here?

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/

  • Just a guess but if you had pairs of labels (ie J1,J1a,J2,J2a etc) to hold job name and response respectively then

    string[] MyJobs = SvrBJobNames.Split(',');

    Label[] JobNameLabels = {J1,J2,J3,J4,J5};

    Label[] JobResponseLabels = {J1A,J2A,J3A,J4A,J5A};

    for (int Index = 0; Index <= MyJobs.Count - 1; Index++) {

    JobNameLabels(Index).Text = MyJobs(Index);

    //get jobresponse here

    JobResponseLabels(Index).Text = Page.ResolveClientUrl(jobresponse);

    }

    As an alternative you could define a DataTable to contain JobName and Response columns, add rows using a loop (similar to above) and output to a Grid, this would be fully dynamic without any hardcoded or numeric limiting control references

    p.s. If you did not want to use data table then you could create a class for Job details and a List to hold entries and use the List as a datasource

    Far away is close at hand in the images of elsewhere.
    Anon.

  • David Burrows (10/30/2015)


    As an alternative you could define a DataTable to contain JobName and Response columns, add rows using a loop (similar to above) and output to a Grid, this would be fully dynamic without any hardcoded or numeric limiting control references

    Wait... You want me to use SQL Server to solve a SQL problem?

    😀

    Sean, what I'm doing is I have a webpage that lists certain month end jobs and the date they will next run. The code above the case statement is the C# code calling the T-SQL proc that I listed in my OP. The result then pushes down to the case.

    Of course, after I took a break for lunch, it occurred to me that I needed to make the text's label as dynamic as the actual job names passing into the job. Once I do that, then everything should be fixed. My major problem is the way I'm learning C# (as I need it instead of from scratch). So my knowledge is very spotty.

    Brandie Tarvin, MCITP Database AdministratorLiveJournal Blog: http://brandietarvin.livejournal.com/[/url]On LinkedIn!, Google+, and Twitter.Freelance Writer: ShadowrunLatchkeys: Nevermore, Latchkeys: The Bootleg War, and Latchkeys: Roscoes in the Night are now available on Nook and Kindle.

  • Brandie Tarvin (10/30/2015)


    David Burrows (10/30/2015)


    As an alternative you could define a DataTable to contain JobName and Response columns, add rows using a loop (similar to above) and output to a Grid, this would be fully dynamic without any hardcoded or numeric limiting control references

    Wait... You want me to use SQL Server to solve a SQL problem?

    😀

    Sean, what I'm doing is I have a webpage that lists certain month end jobs and the date they will next run. The code above the case statement is the C# code calling the T-SQL proc that I listed in my OP. The result then pushes down to the case.

    Of course, after I took a break for lunch, it occurred to me that I needed to make the text's label as dynamic as the actual job names passing into the job. Once I do that, then everything should be fixed. My major problem is the way I'm learning C# (as I need it instead of from scratch). So my knowledge is very spotty.

    Well if you want to be pedantic then DataTables in .NET are not SQL Server, they are tables containing data and they may be populated from any data source or even created from scratch if required 😛

    If the data is all on SQL Server why not use a single query to return all job names and dates, populate a DataView and filter it using your job names in the config 😀

    Far away is close at hand in the images of elsewhere.
    Anon.

  • David Burrows (10/30/2015)


    Brandie Tarvin (10/30/2015)


    David Burrows (10/30/2015)


    As an alternative you could define a DataTable to contain JobName and Response columns, add rows using a loop (similar to above) and output to a Grid, this would be fully dynamic without any hardcoded or numeric limiting control references

    Wait... You want me to use SQL Server to solve a SQL problem?

    😀

    Sean, what I'm doing is I have a webpage that lists certain month end jobs and the date they will next run. The code above the case statement is the C# code calling the T-SQL proc that I listed in my OP. The result then pushes down to the case.

    Of course, after I took a break for lunch, it occurred to me that I needed to make the text's label as dynamic as the actual job names passing into the job. Once I do that, then everything should be fixed. My major problem is the way I'm learning C# (as I need it instead of from scratch). So my knowledge is very spotty.

    Well if you want to be pedantic then DataTables in .NET are not SQL Server, they are tables containing data and they may be populated from any data source or even created from scratch if required 😛

    If the data is all on SQL Server why not use a single query to return all job names and dates, populate a DataView and filter it using your job names in the config 😀

    Wait... Okay DataTables are a C# thing? I honestly did think you were talking SQL Server. And now DataViews?

    Oh, new things to learn. YAY.

    Brandie Tarvin, MCITP Database AdministratorLiveJournal Blog: http://brandietarvin.livejournal.com/[/url]On LinkedIn!, Google+, and Twitter.Freelance Writer: ShadowrunLatchkeys: Nevermore, Latchkeys: The Bootleg War, and Latchkeys: Roscoes in the Night are now available on Nook and Kindle.

  • Brandie Tarvin (10/30/2015)


    Okay DataTables are a C# thing? I honestly did think you were talking SQL Server. And now DataViews?

    In this context, yes C# as in .NET

    Look up DataSets, DataTable and DataViews as they all have different uses, methods and can be filtered or even have LINQ queries applied to them.

    The only reason I suggested using a local table was that you was executing a query once per job to retrieve data. Using a local table and grid would alleviate any hard coding between each job and the controls used to display the results.

    My suggestion would be to write one query to return all jobs details/results, filter the data using your config list and put the results in a GridView.

    Far away is close at hand in the images of elsewhere.
    Anon.

Viewing 14 posts - 1 through 13 (of 13 total)

You must be logged in to reply to this topic. Login to reply