Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, November 1, 2023

Coding: Design Pattern Factory: Comparing Tutorials

 I had some difficulties understanding the design pattern factory and watched a few tutorials.


The tutorial I found most helpful for understanding: Christopher Okhravi's Factory Method Pattern – Design Patterns (ep 4)
(https://www.youtube.com/watch?v=EcFVTgRHJLM&ab_channel=ChristopherOkhravi)

This tutorial was good too and for me a good supplement to Okhravi's tutorial: Code with RaiGenics' Factory Method in C# I Design Pattern (Part 3) - How and When to use Factory Method
(https://www.youtube.com/watch?v=tdMOdeewTnc&ab_channel=CodeWithRaiGenics)


This may potentially due to it being later and I have been understanding a bit more after each video. I do not think so but wanted to mention for transparency. Below is the order that I watched the videos.


Microsoft Video Studio

https://www.youtube.com/watch?v=JEk7B_GUErc&t=427s&ab_channel=MicrosoftVisualStudio

This just did not help me understand why I needed a factory. There was an example about pizza which I later learned from my recommended video by Christopher Okhravi that this is from a book called "Head First Design Patterns" which sounds like the exact same example.

PRO: Robert Greene asked a couple good questions. Otherwise, nothing obviously helpful to me. It was the first video I watched. Watching again after understanding does not seem useful. 

CON: The tech guy (Phil Japikse) is not very good at answering or describing the questions by host (Robert Greene).

IAmTimCorey

https://www.youtube.com/watch?v=2PXAfSfvRKY&t=246s&ab_channel=IAmTimCorey

I am usually a fan of IAmTimCorey videos but this video was very hard for me to follow as there were too many new terms for me to learn and understand like delegates, dependency injections, and Blazor. This may be good for those who have more experience.

PRO: This may be helpful later when I get into Blazor.

CON: Too advanced. I need to understand delegates, dependency injections, Blazor, and probably a few other things that I do not understand enough to even not understand.

Code with RaiGenics

https://www.youtube.com/watch?v=tdMOdeewTnc&ab_channel=CodeWithRaiGenics

This was a bit too technical to start off with but is also a good tutorial. This is include a good example in C# which is what I ultimately needed too.

PRO: Used most basic example and basic code to demonstrate factory design pattern.

CON: Seemed too technical at first but upon reviewing it again later, this video probably would have been fine. Although this had the best code example, it was just short of one of my biggest question. After I create the object, it is in the base class like IMobile. After I get the object, what if I want to use a specific method in the sub-class like SamsungA9? I am sure I can look this up and could be unrelated. I personally would have preferred that it added that one bit anyways.

Christopher Okhravi

https://www.youtube.com/watch?v=EcFVTgRHJLM&ab_channel=ChristopherOkhravi

PRO: I understood the example better. I agree the example about the pizza was a bit confusing to me too. The pizza example is still a bit confusing even after understanding the factory pattern. The UML diagram was also helpful in answering my question on what is the difference between interface and factory pattern. The other tutorials almost seemed like it was just explaining how to use an interface. The UML diagram helped me get over that hump. I would recommend this video as a good overview for the design pattern. For me, it was a bit better than RaiGenics'.

CON: No code example but it obviously was not meant to have one as it was a generic overview. For example, RaiGenics' code sample was the most helpful. For more advanced, Tim Corey may eventually be an ultimate code example as I do plan to eventually work with Blazor.


Summary

My recommendation is to start with Christopher Okhravi then RaiGenics and finally Tim Corey. MS Visual Studio was not helpful to me before or after understanding.

Friday, April 14, 2023

Buggish: MS VS does not display git branch names with slash properly (I was wrong-ish)

EDITED (2023-04-24): As I watched demos for other features, I noticed that people used the slash to organize their branches. So, it seems this was intentional. Below is the original post.

Original Post

Microsoft Visual Studio 2022 does not display git branch names with forward slash properly although it is allowed in git and GitHub. Does it do the same with backslash? I do not know and do not wish to test this.

Basically VS will display it with a folder name then a branch in the folder with a name with the rest of the branch name text. For example if the branch name is abc/def, then there will be a folder called abc and a branch in their named def. In GitHub, you will see branch abc/def. Thus this is a bug in Visual Studio.

You cannot delete the folder, but if you delete the branch ('def' from the example above), this will delete both the folder and the branch. Which makes this a visual bug only. Functionally, looks like everything else will work properly.

OR... maybe this is a feature where you can group branches but only in Visual Studio?

Monday, February 27, 2023

Work Life: Cannot get the value of a token type 'StartObject' as a string. (Jira and C#)

Using JSON deserializer for the response from Jira. This is caused by Jira admins updating one of the fields from a string to an object.

Is there a way to default problems to a value or null instead of failing? The field was a minor field but the entire report fails. Would like there to be a way to still get the report minus the one field.

C# provides the error on the character count. I had to use an editor to search the character count as my response is well over 10k characters.

Tuesday, August 10, 2021

Buggish: The full path must be less than 260 characters long; other restrictions apply. If the report server is in native mode, the path must start with slash.

One of those moments where I just want to pull my hair out. I had this working last night, and suddenly stopped working. I just spent the last several hours troubleshooting the error: tried different configurations, parameters, figure out how to use Fiddler, several google searches, etc.

The problem/answer was basically that I was using the wrong slashes. The path should be using forward slashes '/' not back slashes '\' and without rdl.

\Folder1\ReportName

Psychology

To give myself the tiniest of credit, I initially solved this while rushing to pick up my daughter. It's a lame excuse but I think it important to why I didn't remember what I did. It worked and I left figuring I could return to see my work.

I think I left my project running and stopped the debugging, so I didn't see what values I ended putting in. This probably wouldn't have helped because I probably wouldn't have looked at the direction of the slash. I figured I had it in the code because I got tired of entering the data so I hard-coded the initial value.

I assumed that was correct and maybe I just put in the wrong path. I tried several paths like http://SsrsServer/ReportServer, http://SsrsServer/Reports/, http://Ssrs/Reports/browse, /folder1/reportName, /folder1/reportName.rdl, and also sorts of permutations of paths and file names.

I do not know why I didn't even check the slashes as that should have been one of the first things to check. To make it worse, I do not know why I even thought of it so suddenly. After this entire ordeal, I recall how I figured it out in the first place was because I used the http path then removed the beginning part. Because it used forward slashes, this fixed my problem.

Sometimes I really find how amazing my brain is at forgetting things.

Saturday, June 12, 2021

Info: Getting network shares library with C#

Goal: to get a list of available shared folder names given a remote server name. 


1. I believe this uses the user that is logged into the site. https://www.codeproject.com/Articles/2939/Network-Shares-and-UNC-paths

This was super easy to set up.


2. This is what I wrote if logging in with a specific user:

ManagementPath path = new ManagementPath();

            ManagementClass shares = null;

            ConnectionOptions co = new ConnectionOptions();

            co.Username = "login";

            co.Password = "password";

            co.Impersonation = ImpersonationLevel.Impersonate;

            path.Server = FolderPath; //"devaappwebec01"; // use . for local server, else server name

            path.NamespacePath = "root\\CIMV2";

            path.RelativePath = @"Win32_Share";

            ManagementScope scope = new ManagementScope(path, co); // use (path) for local binds

scope.Connect();

ManagementObjectSearcher worker = new ManagementObjectSearcher(scope,

            new ObjectQuery("select Name from win32_share"));

            ManagementObjectCollection moc = worker.Get();

 



Thursday, May 20, 2021

Buggish: C# Replacing \n with
versus \r\n versus \n\n

Problem to be solved

I need to replace MS SQL break lines with HTML break lines so that it can be displayed on a web page.

Background

Our network group decided to make routers reject posts that are too big. I have a tool to compare database objects across multiple environments to validate and to promote. I used a text box to display the sql queries. If there were five environments, then there would be five textboxes. If the stored procedure was really large, then I would have it five times. So when I post back to the server, I could potentially return a lot of data.

I don't want to truncate because most new changes are at the bottom. I don't want to skim because are at the top. And fixes are typically in the middle.

So decided to use html <pre> tag. This requires me to convert new lines to html new lines. I'm usually lazy and just convert \n to <br/> but then I realized that this returned two break lines which caused a blank line in between every line. This was a pain because that means it took me twice as long to skim through the code.

For some odd reason, I felt like doing both a \n\n and \r\n replace and found this did the same... even though the string value was just \r\n. This is really odd. Although works for me, this is not what I expected.


Final decision

string.Replace("\r\n", "<br/>");

Tuesday, August 25, 2020

Code: Display Net Use default results with C#

 Win32_NetworkConnection


Summary

This was the WMI OS CIM class needed to get the results from a simple Windows command prompt "net use" command. 



Thoughts

This was somehow amazingly hard to find on google. For whatever reason, the only command I can find were for Win32_OperatingSystem or Win32_Share.

There is plenty of information on all the elements but just could not find a connection between net use and Win32_NetworkConnection. 


My Sample Code

                string serverName = @"\\serverName";
                string WMIClassName = "Win32_NetworkConnection";

                List<string> shares = new List<string>();

                ConnectionOptions connectionOptions = new ConnectionOptions();

                ManagementScope scope = new ManagementScope(serverName,
                                                            connectionOptions);
                scope.Connect();

                ManagementObjectSearcher worker = new ManagementObjectSearcher(scope,
                                   new ObjectQuery($"select Name from {WMIClassName}"));

                foreach (ManagementObject share in worker.Get())
                {
                    shares.Add(share["Name"].ToString());
                }


References

Thursday, August 6, 2020

Code: A potentially dangerous Request.Form value was detected from the client

Some notes on how to resolve this error message, as I keep need this reference:


Page
validateRequest="false"


Site
<httpRuntime requestValidationMode="2.0" /> to web.config


Sunday, July 26, 2020

Buggish: Amazon WorkSpaces Locked Shift Key (Unresolved / workaround) Update: Resolved? [2020-07]

Replicate: Unknown
Frequency: Multiple times a day, but can get half a day without it occurring
Environments: Two different machines running different versions of AWS Client. Issue seems to be similar even though different OS and different clients.

Workaround: Turn on caps lock, then turn off caps lock. Repeat if necessary. Toggling may not work if toggle too quickly. At most 3 times, but works every time.

Behavior: Basically, the shift key locks on AWS because all actions appear to be as if the shift key is down. Like highlight text between two different mouse-clicks in a text box, select multiple rows in spreadsheet, etc.

Shift is not locked on my machine. This only occurs in AWS. Pressing the shift key does not appear to do anything which kind of makes sense because it should act as if shift key is down. But release shift key does not return the state back. I found toggling caps lock will return the shift key state.

I do not use caps lock at all, so this is not caused by using caps lock. I figured this out randomly.

I cannot guarantee that this does not happen when not using the shift key as I use the shift key very often. I do also use both shift keys (not at the same time). It does seem to occur more often when I am coding C# which uses a lot of shift keys for curly braces and for sql because I cap the keywords. I want to say that it seemed like this issue still occurred once or twice when there was no shift key used, but this seems to be a very rare occurrence.

It may be possible that there is a delayed or lag response to a shift key press which would explain why it occurs more often when I am coding. Oddly, I can also go a few hours without this occurring. This could just be my mind playing tricks, but also seem to occur less often when I work off peak-hours.

There also seems to be quite a few posts dating back to 2016 with no solution so I am not expecting this to be ever resolved, so beware if you decide to use AWS.

Update 2020-09-03

Interesting, not long after this post... this problem has gone away. I cannot recall when this stopped but feels like at least a couple weeks. Has this problem been resolved? Seems like it.

Update 2022

As of 2021, we have moved from AWS to Azure so there will be no more updates on AWS.

Friday, July 24, 2020

Code: C# Accessing network folder with Username and password to system not on the domain

Summary:
I was given a web server that is on a domain but need to back up files to another server (file server) that is not on the domain and with different credentials than the one I am logged on with (or the user assigned to the web server). I was given the credentials to use on the file server. The credential is also not on the domain. The assigned user for IIS was also a local user (ie not a domain user).

The code below was very simple to implement. I tried a few other solutions before finding this one. Others required knowing the domain. The key part for me was the CredentialCache and providing parameter for the machine I am trying to access.


Sample code from social.msdn.microsoft.com:
NetworkCredential theNetworkCredential = new NetworkCredential(username, password, domain);
CredentialCache theNetcache = new CredentialCache();
theNetCache.Add(@"\\computer", theNetworkCredential, "Basic", theNetworkCredential);
//then do whatever, such as getting a list of folders:
string[] theFolders = System.IO.Directory.GetDirectories("@\\computer\share");



Friday, June 5, 2020

My Return to Visual Studio........... sigh


Microsoft Visual Studio

I know in my previous posts that I had left Visual Studio. Sadly I have returned back. In the previous post, I had left primarily through pricing. I was charged a new customer price when I have been paying for over 10 years. My credit card was canceled due to one fraudulent charge, and I did not update my new card with MS. Also shows you how often I use VS, so I just hated that I was practically donating money to MS and they won't even recognize that been blindly paying them for years. Now the company pays for it, so I grudgingly (morally) returned.

Nothing against the actual application, Visual Studio. It is by far superior IDE to the ones I have used in the meantime, including Visual Studio Code. I can only speak for developing in C#, but I have to say that my programming efficiency is noticeably better with Visual Studio. 

Is it worth the cost for a hobbyist? Not really. The main functions are there in free versions, the pain points are tolerable. Is it worth commercially? Yes, the amount of money you save or produce for the company is definitely worth the price. Is the whole Microsoft shop worth it? That is arguable as other enterprise solutions provide a much better price point. If the company is not a technology company, then it is probably worth it. It is a bit bulky, but you don't need the expertise to hire the right person nor pay the additional cost of "real" developers. Not that option is cheap, but my assumption is that non-tech companies will not have good IT and will not have the expertise to really effectively run IT for the long term. They may be able to find one person, but that person will eventually leave or retire, then it will just be downhill. If they are a rare breed with excellent IT, then I recommend that they should consider transforming into a tech company.

Tuesday, May 16, 2017

GridView with multiple columns with the same name

Microsoft ASP.NET 4.5
Visual Studio 2013

Scenario: Joining to tables that have the same column names but different uses without using alias (because sometimes you don't have access to the data or query).

Solution: The first column will be the original column name. Each additional column will have an integer counter starting at 1 appended to the end of the column name.

Exampe: If the column name is XXXXXX, then the first column will be XXXXXX, the second column will be XXXXXX1, then XXXXXX2, etc, etc.

Saturday, March 4, 2017

C# DataBinding does not contain a property with the name with custom class object and CheckBoxList

I get the error "DataBinding: class1 does not contain a property with the name prop1"

public class1 {
  public string prop1;
  public string prop2;
}


My setup was an object array of class1 which has a property prop1 and prop2:

class1[] arrClass = new class1[arraySize];

Then I set the DataTextField and DataValue:
checkboxlist1.DataSource = arrClass;
checkboxlist1.DataTextField = "prop1";
checkboxlist1.DataValueField = "prop2";
checkboxlist1.DataBind();

This throws the error above. The fix is the lack of accessors in the class, class1. The class should be corrected to the following:
public class1 {
  public string prop1 { get; set; }
  public string prop2 { get; set; }
}
 Technically, set is not needed.


Reference

https://msdn.microsoft.com/en-us/library/aa287786%28v=vs.71%29.aspx

Tuesday, February 28, 2017

Buggish: VS2013 Unable to debug and intellisense haywire

1. The breakpoint will not currently be hit. The source code is different from the original version.

I tried a bunch of different methods suggested in stackoverflow, but none seemed to have worked except to make additional changes to global.asax to force VS to recompile the code. I believe what may have caused the problem is that I was updated global.asax while I was still running the application in debug mode. Normally this is not a problem, but may be a timing of when I updated the code while the page was refreshing.


2. After the problem above, I had issues with intellisense in code-behind not recognizing objects in the aspx page. The red squiggly line comes up, but I am still able to compile and run the application with no compile errors. If I type out the object name, intellisense will not find the object.

Restarting VS fixed this problem. I do not know what caused this as I have restarted VS several times to fix the problem above. Either the problem came up after the fix above, or somehow keeping the files open when I closed VS before restarting somehow fixed the issue.


Reference

http://stackoverflow.com/questions/2468852/the-breakpoint-will-not-currently-be-hit-the-source-code-is-different-from-the

Saturday, November 21, 2015

.NET Find User Control in a Master Page, or really any control

Solution: Set the control you want to access to public or whatever accessibility is needed for your application. To do this, you will need to go into the designer.cs file (assuming you are using visual studio; if not, you should already know how to do that).

Error: (When using FindControl) An exception of type 'System.NullReferenceException' occurred in XXXXX.dll but was not handled in user code



Better solution: Create a public function within the master page to do the actions needed.


Scenario: I wanted to create a dedicated login page and had a login process in the master page. The need was to hide the master page login for the login page.

Although I have not considered during the design phase, this can also be used to manage the menus.

Monday, March 9, 2015

ASPNET Sessions and Response Redirect - Why logins do not always work after logging off

This is the first time that I got around to building a custom login user control. Typically, I build the login as part of the master page. Because of this change, there was a problem I ran into while testing the code. The issue was that I was unable to log into my application right after I log off. I can log in in the very first session or login again after it fails.

This issue is not a huge deal but can interfere with the user experience which makes it a big deal. But how often does a user log right in after logging off? This should not happen often and the user will likely naturally try again.

Any case, I found that I cannot Clear and Abandon a session in the same page transaction as I set a new session. Essentially, I found that this issue occurred only on the logoff page. I can log in twice because the page is redirected to the home page after the first attempt thus leaving the logoff page.


Summary

Not IsPostBack will prevent the issue that I ran into. Executing session's clear and abandon will trump any sessions set within the same page transaction, even if it is "executed" earlier in the code. By using Not IsPostBack will prevent the clear and abandon code to be executed when the Page_Load method is executed after clicking on the submit button.



Off-shoot issue

I had ran into a different problem earlier in my career (I think this may already have been fixed in the later .NET Framework versions), but in case the above does not help... here is an article that provides detail on using sessions and page redirects.


Reference

Sunday, January 11, 2015

C# Session.Abandon() Event Process Not So Intuitive

Unless you understand how all the events are triggered within the webserver, a casual programmer may not necessarily understand the first time they use this method/function.

I was programming the login and logoff process. I use Session.Abandon() to clear the sessions. On the master page, I have the typical welcome user and log off hyperlink which should be cleared when accessing the logoff page. But it does not and remains on the corner of the page. After stepping through the debugger, the session still exists.

This is because the session is not cleared until all transactions have been completed. This is confirmed both on the Microsoft site and Stackoverflow site. I'm sure there is a reason for this.

Abandon vs Clear

The two links do a pretty good job of explaining the differences but it was not completely clear what impact this had on coding. One interesting comment was that they used Clear and Abandon. The counter-comment was that this was redundant.

I found that this is not redundant as the third comment has pointed out. The reason actually is the way I should have executed my logoff process because Clear() will "nullify" all the session values, then Abandon will clear out the session (supposedly the session id) as I would like a different session id if a different user is on.


My Programming Experience

Although I have been programming for several years in the past, I have fallen so far behind on a lot of new practices. I have enough knowledge to probably transition between one programming language to another, but not enough to program without a reference book or revisiting a lot of less-used functionality or program once functionality (ie login and logoff). I probably just used a flag in my past career life.

I had to look up the C# page even orders. I recall this was one of my interview questions. There is a bunch of events, but I typically only had to worry about init and load so I probably just answered that question poorly (mediocre at best... I knew a couple others but not the specific names).

Reference

http://msdn.microsoft.com/en-us/library/ms524310(v=vs.90).aspx
http://stackoverflow.com/questions/1470445/what-is-the-difference-between-session-abandon-and-session-clear

Thursday, October 16, 2014

Project: No easy way to change class names using EF or MVC

I am still testing around the MVC and EF tools. What I have been trying is to change a class name. Although this probably happen very rarely, this exercise at least helped me understand how some of the pieces fit together.

It was interesting that the cshtml are not included in the global name change updates. I had to manually go through each one to update to the new class name. I also noticed that all the model parameters always have the red squiggly underline. This does not have an impact as I was able to eventually get the site running again.

Clearly, this is an example that is kind of the drawback to scaffolding (sorry, still not completely familiar with the term yet). Because a lot of the code is generated based on the class name and because they are internal variables, these variable names do not change. This is not a major problem for the code as it will still render but will be just as misleading as they would still reference the old class name. This also includes the documentation. The best way is probably use the Visual Studio's CTRL+ALT+F feature to just replace all terms. Hopefully, the term is not too simplistic to impact other variables.

Somehow my table name was updated with the new model name. I am not exactly sure how I did this or when it happened as I was not checking that while I was correcting the files. I did run an Update-Database. This is my best guess on when it possibly could have occurred. Later, I did an Add-Migration and Update-Database. But because the Up/Down methods were empty, I assumed there were no changes.

At then end of the day, it is possible. I'm not sure how complex some of these classes may become, but with simple classes, it is much easier just to recreate a new class. I'm sure there probably is a way to delete the old tables. Hopefully, you just never have to make these changes.

Project: EF6, Resetting Entity Framework (VS 2013 Express, SQL Server Express, C#)

This was my first time working with Entity Framework. Because I used it in a web application, I had to fidget with some of the instructions I found online that worked with a console application. Somewhere in the middle of the setup, I changed the database and I think this is where I must have broken something.

Basically, I followed the initial setup so I had a migration for Initial Create. In this setup, I had created a class. In this area, I am not sure exactly how to replicate what I ended up with. Somehow I ended up with the migration scripts for creating the initial ASPNET tables but not my class (MyForm).

I continued to use add-migration with no luck. It will not attempt to create the table. The up/down methods are always empty. I am not exactly sure where it stores the information that it has already attempted to generate MyForm. I looked inside the script for InitiateCreate but I do not see the class or table in there.

Next I tried to make a modification, and this did generate an add column. Because I do not have the table, this update failed. Just to test it further, I also created another class. This also generated scripts for creating a table. Of course this failed, because the other update to add column is still pending.

After several more hours of banging my head, I finally decided to start over. This posed another set of problems. I quickly found this link which gave me the command (Update-Database -TargetMigration:0).

When I tried to add-migration again, I get the error that I still had pending migrations. I tried to look everywhere on how the system knows that I still had pending migrations. I just took a risk and just deleted the migration files in the Migrations folder. Initially, I had moved them to a backup folder but of course the project would still find it since it is in the same namespace. I guess I could have just dropped them from the project. Fortunately, by running add-migration, I was able to recreate the Initial Create scripts again.

Also another problem with the tutorials were that they were all using Visual Studio 2012 or 2010, while I am using 2013 Express. Some of the layouts and forms were slightly different. Because my problem was a bit unique, these slight differences really made me question a lot more than I should have. It would be nice if there were tutorials on how to make a blanket rollback without restarting a new project.

Error Messages


  • "Unable to generate an explicit migration because the following explicit migrations are pending"
  • object does not exist

Reference

http://stackoverflow.com/questions/10282532/entity-framework-start-over-undo-rollback-all-migrations

Friday, May 2, 2014

Coding: Creating a Counter (MS SQL, C#) Samples

I probably create one of these for every one of my larger projects. I always have a need to track a counter of some sort.

My Standard Counter Table

USE [dbName]
GO

/****** Object:  Table [dbo].[__Counters]    Script Date: 05/01/2014 23:45:23 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[__Counters](
[CounterName] [varchar](50) NOT NULL,
[NextId] [int] NOT NULL,
[Notes] [varchar](max) NULL,
 CONSTRAINT [PK___Counters] PRIMARY KEY CLUSTERED
(
[CounterName] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO


My Standard Stored Procedure

USE [dbName]
GO

/****** Object:  StoredProcedure [dbo].[GetCounter]    Script Date: 05/01/2014 23:45:52 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author: Douglas Lee
-- Create date: 5/1/2014
-- Description: Get next id and update for next use
-- =============================================
CREATE PROCEDURE [dbo].[GetCounter]
-- Add the parameters for the stored procedure here
@CounterName varchar(50),
@NextId int OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

    -- Insert statements for procedure here
--DECLARE @NextId int;
SET @NextId = 1;
SELECT @NextId = NextId FROM __Counters WHERE CounterName = @CounterName;
Update __Counters SET NextId = NextId + 1 WHERE CounterName = @CounterName;
RETURN
END

GO

My Standard C# Code

        public static int GetCounter(string CounterName)
        {
            SqlConnection conn = null;
            //SqlDataReader rdr = null;

            conn = new SqlConnection(c);
            conn.Open();

            // 1.  create a command object identifying the stored procedure
            SqlCommand cmd = new SqlCommand("GetCounter", conn);

            // 2. set the command object so it knows to execute a stored procedure
            cmd.CommandType = CommandType.StoredProcedure;

            // 3. add parameter to command, which will be passed to the stored procedure
            SqlParameter output = new SqlParameter("@NextId", SqlDbType.Int);
            output.Direction = ParameterDirection.Output;
            cmd.Parameters.Add(new SqlParameter("@CounterName", CounterName));
            cmd.Parameters.Add(output);

            cmd.ExecuteNonQuery();
            int retInt = (int)cmd.Parameters["@NextId"].Value;

            conn.Close();
            
            return retInt;
        }