asp.net - public static functions using globally - asp.net

I am new to ASP.NET C#. I try to follow this tutorial page to make a function using globally, but no luck.
https://web.archive.org/web/20210612122420/http://aspnet.4guysfromrolla.com/articles/122403-1.aspx
What I try to do is use a function global any where in my code. I have a function called "FormatDateNoTime". I have create a Class file under App_Code folder. But when I call that function in one of my code behind page (example Page1.aspx.cs), it gives me the error:
Error: The name 'MyClass' does not exist in the current context
MyClass.cs file under the App_Code folder.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for Class1
/// </summary>
public class MyClass
{
//
// TODO: Add constructor logic here
//
public static string FormatDateNoTime(string input) {
string thedate;
DateTime strDate = DateTime.Parse(input);
thedate = strDate.ToString("MM/dd/yyyy");
return thedate;
}
}
The code in my Page1.aspx.cs calling the FormateNoTime function
TextBox BeginDate = (TextBox)FormView1.FindControl("BeginDate");
BeginDate.Text = MyClass.FormatDateNoTime(objDs.Tables[0].Rows[0]["BeginDate"].ToString());
It seems like other pages don't recognize this class.function().
Please help. Thanks in advance.

Right click the source file in App_Code and set its "Build Action" property to "Compile". Click on the .cs file in App_Code and hit F4 key (or right click -> Properties), and you should see an option for "Build Action"
That way, it will build the code in your App_Code folder, and you should be able to access your static method in your class. If the above doesn't help, remove the class from the app_code and drop it in the root folder and try compiling it.

The code you have doesn't compile. I'm pretty sure Visual Studio is throwing an error when you try to run it; pay attention to what it's saying.
Also, change the following:
public static string FormatDateNoTime(object sender, EventArgs e)
{
string thedate;
DateTime strDate = DateTime.Parse(input);
thedate = strDate.ToString("MM/dd/yyyy");
return thedate;
}
To
public static string FormatDateNoTime(String input)
{
string thedate;
DateTime strDate = DateTime.Parse(input);
thedate = strDate.ToString("MM/dd/yyyy");
return thedate;
}
I'd go further and validate that the input is parseable into a DateTime, but that's for you to explore.

Related

How do I get ShellSettingsManager in an async extension to VS2019?

I wanted to create a small extension to add a list of External Tools to VS2019. A quick search brought up what appeared to be perfect example code at https://learn.microsoft.com/en-us/visualstudio/extensibility/writing-to-the-user-settings-store?view=vs-2019. This adds a command to invoke Notepad, so I thought with a few edits, my work was done.
However, this example is written as a synchronous extension, which is deprecated, so I tried putting the code intended for MenuItemCallBack into the Execute method of the extension, but the line
SettingsManager settingsManager = new ShellSettingsManager(ServiceProvider);
fails to compile, because ServiceProvider is now type IAsyncServiceProvider and the ShellSettingsManager constructor wants an argument of type IServiceProvider.
As far as I can tell, ShellSettingsManager is still the way to access the Settings Store, but all the examples I could find all refer to putting code in MenuItemCallback (as well as being several years old) so are for synchronous extensions.
So, can someone point me to the recommended way to get access to the settings store in an asynchronous extension?
The ShellSettingsManager constructor takes either an IServiceProvider interface or an IVsSettings interface. Given your AsyncPackage derived object implements IServiceProvider, you should be able to just pass it in as the argument to your constructor. The following quick demo package worked for me:
using System;
using System.ComponentModel.Design;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft;
using Microsoft.VisualStudio.Settings;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell.Settings;
using Task = System.Threading.Tasks.Task;
namespace UserSettingsDemo
{
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(UserSettingsDemoPackage.PackageGuidString)]
[ProvideMenuResource("Menus.ctmenu", 1)]
public sealed class UserSettingsDemoPackage : AsyncPackage
{
public const string PackageGuidString = "cff6cdea-21d1-4736-b5ea-6736624e718f";
public static readonly Guid CommandSet = new Guid("dde1417d-ae0d-46c4-8c84-31883dc1a835");
public const int ListExternalToolsCommand = 0x0100;
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
OleMenuCommandService commandService = await GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;
Assumes.Present(commandService);
var menuItem = new MenuCommand(OnListExternalTools, new CommandID(CommandSet, ListExternalToolsCommand));
commandService.AddCommand(menuItem);
}
private void OnListExternalTools(object sender, EventArgs e)
{
ShellSettingsManager settingsManager = new ShellSettingsManager(this);
WritableSettingsStore userSettingsStore = settingsManager.GetWritableSettingsStore(SettingsScope.UserSettings);
int toolCount = userSettingsStore.GetInt32("External Tools", "ToolNumKeys");
for (int i = 0; i < toolCount; i++)
{
string tool = userSettingsStore.GetString("External Tools", "ToolCmd" + i);
VsShellUtilities.ShowMessageBox(this, tool, "External Tools", OLEMSGICON.OLEMSGICON_INFO,
OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
}
}
}
}
Sincerely

Ambiguous call using extension methods in asp.net

When calling an extension method from another extension method, my solution was building ok, but in the published site (or the virtual asp.net server) I was getting the Compile Error "Ambiguous call".
public static string ExtensionMethodA(this ObjectToExtend myObj){//code here}
public static string ExtensionMethodB(this ObjectToExtend myObj){
string a = myObj.ExtensionMethodA(); // this line causes the error.
return a;
}
I haven't read enough to know exactly why, but here is the solution:
public static string ExtensionMethodA(this ObjectToExtend myObj){//code here}
public static string ExtensionMethodB(this ObjectToExtend myObj){
string a = ExtensionMethodA(myObj); // correct call.
return a;
}

C# ASP.NET - Controlling/updating a textbox.text value through a class

Newbie here, I need help with a website I'm creating.
I have a class that does some analysis on some text that is input by the user, the class then finds an appropriate answer and sends it back to the textbox. (in theory)
Problem is I don't know how I can control and access the textbox on the default.aspx page from a class, all I get is "object reference is required non static field".
I made the textbox public in the designer file yet still no joy. :(
I've also read this: How can I access the controls on my ASP.NET page from a class within the solution? , which I think is along the lines of what I'm trying to achieve but I need clarification/step by step on how to achieve this.
Hope someone can point me in the right direction.
Many thanks,
Kal
This is the code I have added to the designer.cs file:
public global::System.Web.UI.WebControls.TextBox TextBox3;
public string MyTextBoxText
{
get
{
return TextBox3.Text;
}
set
{
TextBox3.Text = value;
}
}
This is the class method i have created:
public static cleanseMe(string input)
{
string utterance = input;
string cleansedUtt = Regex.Replace(utterance, #"[!]|[.]|[?]|[,]|[']", "");
WebApplication1._Default.TextBox3.text = cleansedUtt;
}
I could just return the cleansedUtt string i know, but is it possible for me to just append this string to the said textbox from this method, within this class?
I also tried it this way, i wrote a class that takes in the name of the textbox and string to append to that textbox. it works BUT only on the default.aspx page and does not recognise the textbox names within the difference classes. The code is as follows:
public class formControl
{
public static void ModifyText(TextBox textBox, string appendthis)
{
textBox.Text += appendthis + "\r\n";
}
I would suggest you that do not access the Page Controls like TextBox in your class. It will be more useful and a good practice that whatever functionality your class does, convert them into function which accept the parameters and returns some value and then on the basis of that value you can set the controls value.
So now you have reusable function that you can use from any of the page you want. You do not need to write it for every textbox.
Here I am giving you a simple example
public class Test
{
public bool IsValid(string value)
{
// Your logic
return true;
}
}
Now you can use it simple on your page like this
Test objTest = new Test();
bool result=objTest.IsValid(TextBox1.Text);
if(result)
{
TextBox1.Text="Everything is correct";
}
else
{
TextBox1.Text="Something went wrong";
}
If you have your class in the same project (Web Project) the following will work:
public class Test
{
public Test()
{
//
// TODO: Add constructor logic here
//
}
public static void ValidateTextBox(System.Web.UI.WebControls.TextBox txt)
{
//validation logic here
if (txt != null)
txt.Text = "Modified from class";
}
}
You can use this from your webform like this:
protected void Page_Load(object sender, EventArgs e)
{
Test.ValidateTextBox(this.txt);
}
If your class is in a different (class project), you would need to add a reference to System.Web to your project.

Redirect to ASPX file from .cs File

In asp.net Website, On a WebForm, after button onclick event I am calling code behind method as below
protected void Button1_Click(object sender, EventArgs e)
{
MyClass obj = new MyClass();
String res = obj.CallMe("some parameters");
}
Where MyClass resides in MyClass.cs file.
Inside CallMe() :
public String CallMe("some parameters")
{
String to_return ="";
//some code : to_return="something";
string page_name= // some code returns a name of page to redirect to
if(page_name is null)
{ return to_return; }
else
//redirect to page_name;
}
How to redirect from .cs file since we dont have access to HttpResponse object?
If your class is being called from within a web page, you have access to the static HttpContext.Current instance in the class. Just import the System.Web namespace and call as normal:
using System.Web;
System.Diagnostics.Debug.WriteLine(HttpContext.Current.Timestamp.ToString());
HttpContext.Current.Response.Redirect("http://www.google.com");
try this
if(HttpContext.Current != null)
HttpContext.Current.Response.Redirect("~");
Using the HttpContext you can get the current request, response etc. However be careful to always check to ensure the current context is not null, especially if you are calling from your business layer classes.
ASP.Net Forum

How to consume COM object in ASP.NET class file

I have a COM object that I am trying to wrap in a C# class in order to make it more readily available for other applications that wish to consume it.
I have the following code that creates an instance of the COM object, and then using reflection makes a call to a method to retrieve user data. This code works fine when it is located in an aspx page.
object jdObj = Server.CreateObject("jd_api.UserCookie");
string username = jdObj.GetType().InvokeMember("GetUserName", System.Reflection.BindingFlags.InvokeMethod, null, jdObj , null).ToString();
However, when I move the code to a class file (JD_API.cs) in order to abstract it from the actual website, I can no longer get it to work. For example, I have the following static method that is declared like such:
public static string GetUserName() {
object jdObj = Server.CreateObject("jd_api.UserCookie");
string username = jdObj.GetType().InvokeMember("GetUserName",
System.Reflection.BindingFlags.InvokeMethod, null, jdObj , null).ToString();
return username;
}
Unfortunately, the Server object is restricted to some ASP.NET libraries that are included by default in web applications, and so the above code was a no-go. So at this point I decided to try to create an instance of the COM object like such:
public static string GetUserName() {
Type type = Type.GetTypeFromProgID("jd_api.UserCookie");
object jdObj = Activator.CreateInstance(type);
string username = jdObj.GetType().InvokeMember("GetUserName", System.Reflection.BindingFlags.InvokeMethod, null, jdObj , null).ToString();
return username;
}
However at runtime I get an error that says, "Attempted to read or write protected memory. This is often an indication that other memory is corrupt.".
I'm not sure where to go from here. Any help on how to abstract creating an instance of this COM object to a layer that is not within the web application itself would greatly appreciated. Thanks!!
Declare DLL functions within a class. Then define a static method for each DLL function you want to call.
The following code sample creates a wrapper named Win32MessageBox that calls the MessageBox function in User32.dll each time a .NET app calls the object Show method.
It requeres the System.Runtime.InteropServices namespace.
using System;
using System.Runtime.InteropServices;
class Win32MessageBox
{
[DllImport("user32.dll")]
private static extern int MessageBox(IntPtr hWnd, String text,
String caption, uint type);
public static void Show(string message, string caption)
{
MessageBox(new IntPtr(0), message, caption, 0);
}
}
To call it, just type:
Win32MessageBox.Show("StackOverflow!", "my stack box");
The method where you call the above line doesn't need to be aware that it's a actually calling a function in an unmanaged DLL.
Resources: the MCTS Self-Paced Training Kit (Exam 70-536) by Tony Northrup.
Hove you tried usinsing interoperating
I've done the following in the past (working from memory so you might need to fiddle with this a bit):
Right Click "References" in your project
Select "Add Reference"
Selelct the "Com" Tab
Find and add your Com Instnace
In your class file
using yourComName;
public static string GetUserName()
{
yourComName.yourComClass jdObj = new yourComClass();
string username = jdObj.GetUserName(someParameters);
return username;
}
Hope this a) works and b) helps!

Resources