Getting username of a webform - c#

I have a webform, and I am trying to make a log of who is using it. All the research I did, was all about using on a local box, not through IIS.
using System.Security.Principal;
private void Form1_Load(object sender, EventArgs e)
{
string curuser = WindowsIdentity.GetCurrent().Name;
}
Where I get the Output:
tw.WriteLine(DateTime.Now + ": " + CurUser);
Output displayed:
12/1/2017 4:13:18 PM: System.Web.UI.WebControls.Label
I am assuming it is something silly and dumb. Thanks guys
Note: I have 'Windows Authentication' enabled within IIS for this site.

Whatever or wherever CurUser is, it's an instance of a Label. It's not your curuser variable that you declared in Page_Load and then never used.
When you try to output an object as a string, the system internally invokes the .ToString() implementation on that object. Unless overridden (and Label doesn't override it), the default implementation for .ToString() (inherited from System.Object) is to output the name of the type. In this case "System.Web.UI.WebControls.Label".
(Makes sense. After all, how would the system inherently know how a complex object, particularly any custom object you could write, should be represented as a string?)
Don't output an unrelated object, output the value:
string curuser = WindowsIdentity.GetCurrent().Name;
tw.WriteLine(DateTime.Now + ": " + curuser);

Related

Pass string from C# Code Behind Winforms application to a webpage textbox

I am trying to pass a string from a C# Winforms application to a webpage text box.
The Webpage textbox looks like this:
<input id ="sometext" class = "form-control-sometext clearable"
placholder = "Enter Infor Here" type = "text" name = "moreText">
I have tried several methods such as the following:
//string v = textBoxAutoV.Text;
//string getPage = "http://www.TheWebsite.com?moreText = v;
The information is needed to process an information request and return a string value. I would like to see a code sample if possible. Thank you.
You should try the following way:
protected void Page_Load(object sender, EventArgs e)
{
// Store a value in the Session
Session["moreText"] = "This is an example";
}
<input id ="sometext" class = "form-control-sometext clearable"
placholder = "Enter Infor Here" type = "text" name = "moreText" value=#(Session["moreText"])>
First off, you will need to use an ASP.NET WebForms text box control, if you want to do it the proper way. Here's an example with that:
Here's my code (in mypage.ascx):
<asp:TextBox id ="sometext" class = "form-control-sometext clearable"
placeholder = "Enter Infor Here" type = "text" name = "moreText" runat="server"></asp:TextBox>
And in the code behind (in mypage.ascx.cs):
/// <inheritdoc cref="UserControl.OnInit" />
protected override void OnInit(EventArgs e) {
base.OnInit(e);
sometext.Text = "mytext";
First, let me thank you all. I do not think that I explained it properly, which happens when you are trying not to reveal private information. First, the page that is 'sending' the data is not mypage.ascx ... it is mypage.cs (Winforms, not a web page). Second, the website is not mine. It is a resource. But because it is public, let me lift the veil off it. I am trying to use a site called (www.decodethis.com). It is totally legitimate to use it, but many of my customers that use the site by reference make mistakes when transferring the 17 digit VIN number to the site manually. My idea was to have them enter the information inside the application that I wrote and have it passed to the 'decodthis' page to have it processed and get a result. I am not sure that it is even possible to do this, but since it should not matter to the site owner whether the number to be decoded was entered manually or automatically, it seemed to make sense to do it this way. If it would help. I could make a webpage on my end and then use aspx.cscode to accomplish the same thing if that would work. But I prefer to use the actual application if possible. With that said, all the information about the web text box is visible using the element examination feature. SO ... perhaps using the real-life naming ... could you please suggest a way to accomplish this task (if it can be done at all?). All I want to do is pass the information from the desktop application (main.cs) to the webpage (www.decodethis.com) automatically. Thank you (ALL) again!

How to fix variable does not exist in current context in SharePoint WebPart code behind?

I am a complete noob when it comes to developing webparts for SharePoint 2010. I have created a webpart that has button on it. When that button is clicked, I would like it to redirect the user to another page. That would seem like an easy operation to do but I have run into roadblocks.
In my MyWebPart.ascx.cs file, I have the following bit of code:
protected void Button_Click(object sender, EventArgs e)
{
// Get the values the user inputted
try
{
String category = SearchBySelector.SelectedValue;
String keyword = SearchField.Text;
SPWeb root = SPContext.Current.RootWeb.Url;
String url = root + "/path/to/site.aspx?category=" + category + "&keyword=" + keyword;
SPUtility.Redirect(url);
}
catch (Exception ex)
{
StatusLabel.ForeColor = "#FF0000";
StatusLabel.Text = "Exception encountered." + ex.Message;
}
}
The problem I am having is that SPContext (and SPUtility) is not being recognized in this context. How do I fix this? I assume I need some sort of include somewhere? I am not a C# expert either which is probably evident by my code.
Any help would be appreciated.
You'll need the fully qualified namespaces for both SPContext and SPUtility, which are Microsoft.SharePoint.SPContext and Microsoft.SharePoint.Utilities.SPUtility respectively.
You can either use those fully qualified class names in your code, or tack two using statements onto the top of your code file:
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
If Visual Studio still barks at you about not recognizing these types or namespaces, you'll want to be sure the Microsoft.SharePoint assembly is added to the references in your project. You can add references from the Solution Explorer window in Visual Studio.

Retrieve variable value from flash

I have an AxShockwaveFlash object in a Windows Forms application, and load a (AS3) movie into it with LoadMovie. The movie plays correctly, but I am having a problem getting a variable from flash.
I have tried using GetVariable but it always returns an empty string. How can I get the value of a variable from flash?
I think the new security policy for AVM2 requires you to explicitly expose the variables/functions to the container application using ExternalInterface.
If you can't edit the swf, I can't think of a way to get access to them. It was really easy with AS2 though, if you defined it, you could get and set it via javascript/C#/whatever without any extra code in the swf.
Yo can use fscommand method to talk to C# from shockwave player:
fscommand("sendCmd", arg);
to catch value in C# use
flashPlayer.FSCommand += new AxShockwaveFlashObjects._IShockwaveFlashEvents_FSCommandEventHandler(flashPlayer_FSCommand);
....
void flashPlayer_FSCommand(object sender, AxShockwaveFlashObjects._IShockwaveFlashEvents_FSCommandEvent e)
{
tbOut.Text += e.command + " (" + e.args + ")" + "\r\n";
}

Generating JavaScript in C# and subsequent testing

We are currently developing an ASP.NET MVC application which makes heavy use of attribute-based metadata to drive the generation of JavaScript.
Below is a sample of the type of methods we are writing:
function string GetJavascript<T>(string javascriptPresentationFunctionName,
string inputId,
T model)
{
return #"function updateFormInputs(value){
$('#" + inputId + #"_SelectedItemState').val(value);
$('#" + inputId + #"_Presentation').val(value);
}
function clearInputs(){
" + helper.ClearHiddenInputs<T>(model) + #"
updateFormInputs('');
}
function handleJson(json){
clearInputs();
" + helper.UpdateHiddenInputsWithJson<T>("json", model) + #"
updateFormInputs(" + javascriptPresentationFunctionName + #"());
" + model.GetCallBackFunctionForJavascript("json") + #"
}";
}
This method generates some boilerplace and hands off to various other methods which return strings. The whole lot is then returned as a string and written to the output.
The question(s) I have are:
1) Is there a nicer way to do this other than using large string blocks?
We've considered using a StringBuilder or the Response Stream but it seems quite 'noisy'. Using string.format starts to become difficult to comprehend.
2) How would you go about unit testing this code? It seems a little amateur just doing a string comparison looking for particular output in the string.
3) What about actually testing the eventual JavaScript output?
Thanks for your input!
We created a library specifically for the purpose of embedding JavaScript in a fluent-like syntax into our C# code, and then made it open source.
Have a look at Adam.JSGenerator.
I typically try to create a separate .js file for most/all of my javascript code. Usually I will need to have common bahvior applied to many elements that are dynamically created by ASP controls or server-side code, so I may not be able to code everything into a .js file.
I've found that the main reason that you want to generate javascript on the server is because you won't know the IDs of elements until the page renders. Therefore, I try to condense that dependency down as much as possibly so that I'm generating as little javascript as possible. For example, in traditional ASP.Net (not MVC) if I were rendering a set of forms such as in the example, each with multiple fields, then I would probably have something in the code behind such as this:
protected void FormRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Control form = e.Item.FindControl("MyForm");
ClientScript.RegisterStartupScript(this.GetType(), "prepareForm_" + form.ClientID, #"prepareForm('" + form.ClientID + "');", true);
}
A separate .js file would include the definition of the prepareForm function, which would be something like this:
// define a formPresenter "class" that encapsulates the behavior for a given form
function formPresenter(formId) {
this.setFirstName = function(value) {
$("#" + formId + "_FirstName").val(value);
}
this.setLastName = function(value) {
$("#" + formId + "_LastName").val(value);
}
// create other functions to handle more complicated logic
// clear fields
this.clearInputs = function() {
this.setFirstName("");
this.setLastName("");
//...
}
// receive Json object
this.handleJson = function(json) {
this.clearInputs();
// populate fields with json object
this.setFirstName(json.FirstName);
this.setLastName(json.LastName);
//...
}
// "constructor" logic
}
function prepareForm(formId) {
// create a new formPresenter object and shove it onto the specified element as the "presenter"
document.getElementById(formId).presenter = new formPresenter(formId);
}
Now almost all of your actual logic is in its own .js file, which should be much easier to maintain. If you need to access the formPresenter object for a given form, then you just need to get a reference to whatever element is referenced by the formId parameter and access the presenter variable:
"document.getElementById(" + form.ClientID + ").presenter.handleJson(json);"
Note: Since I've been using JQuery, I've found less of a need to even include any javascript generated by the server. Typically I can find the elements that I need by looking for a specific CSS class name (or something to that effect) and perform whatever setup/initialization I need.
We're doing a lot of JS generation in our project as well, and we're using StringBuilder to do it.
StringBuilder sb = new StringBuilder();
sb.Append("some javascript stuff")
.Append("some more")
.AppendFormat("formatted stuff {0}", "here");
return sb.ToString();
It's not pretty, but no solution is going to be.
And concerning testing, we don't actually do any unit tests on the generated code. Before release people go and test all the features to make sure they work as expected.
If you don't care about super duper performance you could use a templating language to generate the javascript.
Then for unit testing you would just fill the templates with their appropriate bindings/variables and then run it through a Javascript evaluator like Rhino or whatever the .NET equivalent is to at least test the syntax if not the actual JS code.
Other than that I would seriously question the design of software that is generating Javascript like this. It also looks like you are using JQuery but are referencing the $ directly which may lead to some problems down the line.
If compilers generating Javascript is one thing (ala GWT) but I would separate your client side JS code as much as possible from your .NET code (not to mention your .NET code looks like server side JS talk about confusing).
This in vogue kind of design of separating the client crap from the server is known as SOFEA. I let you google that.

How to add Custom Property to System.Managment Object using WMI, C# in ASP.Net Application?

AA,
I want to add a custom property to a WMi Object's Propert Collection. So that whenever i retrieve the properties of that object, i get the custom added property as well. Specifically speaking lets see the following code.
foreach (ManagementObject WebSite in WebSitesCollection)
{
if (WebSite.Properties["Name"].Value.ToString().Contains(appPoolName))
{
foreach (PropertyData propertyData in WebSite.Properties)
{
try
{
HttpContext.Current.Response.Write(propertyData.Name + " " + propertyData.Value + "<br/>");
if (propertyData.Name.Equals("Enable32BitAppOnWin64"))
{
AppPoolx.SetPropertyValue("Enable32BitAppOnWin64", true);
AppPoolx.Put(); return true;
}
else
{
AppPoolx.Properties.Add("Enable32BitAppOnWin64", true);
AppPoolx.Put(); return true;
}
}
catch (Exception ex1)
{
HttpContext.Current.Response.Write("Error Ocurred while Setting Property: " + ex1.Message + "<br />");
break;
}
}
}
}
But the AppPoolx.Properties.Add("Enable32BitAppOnWin64", true); returns error
Operation is not valid due to current state of the object.
I was wondering whether it was even possible to add a custom property to the WMi object. If what is this Add() function for?
In any case, what is the correct procedure of add a "Custom Property to a WMI Object."
Please do not suggest that i may store in DB.
Regards
Steve
WMI Objects are basically com objects, much like a C# object those objects are populated by the code at the other end.
For you to add this custom property you would have to have the functionality in the code at the other end to store the object data for your custom property.
The add property method you're calling is not valid for all (pretty much most) com objects that are returned by WMI API's this is likely your problem, i understand that this is something to do with how the objects from WMI calls are marshalled from the com component in which they are called from.
So in short:
This is not likely possible.
A more correct approach would be to determine the actual type of the object you are working with and set a property value on a property that is writable for the object then push that back to the WMI API.

Categories

Resources