index
CSharp Items
The methods and properties of the HttpResponse class are exposed through the Response
property of the HttpApplication, HttpContext, Page, and UserControl classes.
This works: HttpContext.Current.Response.Write("<strong>Hello from clsTinettiMisc</strong><hr />")
In Web.config, I added a value for testing:
<appSettings>
<add key="IsTesting" value="True"/>
</appSettings>
At top of each class I have a boolean variable that reads the value in Web.config:
private bool _IsTesting = Convert.ToBoolean(System.Web.Configuration.WebConfigurationManager.AppSettings["IsTesting"]);
Private _IsTesting As Boolean = Convert.ToBoolean(System.Web.Configuration.WebConfigurationManager.AppSettings("IsTesting"))
What about this?
Private _IsTesting As Boolean = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings("IsTesting").ToString())
If (_IsTesting) Then
HttpContext.Current.Response.Write("hdnTotalScore.Value = " & hdnTotalScore.Value & "<hr/>")
End If
If _IsTesting Then
HttpContext.Current.Response.Write("In clsTUGTest.SaveData(): TUGTest_ID = " & TUGTest_ID.ToString() & "<hr/>")
End If
Somewhere else in the class, I have a function that takes in an Exception and outputs
detailed information about it to the screen IF AND ONLY IF IsTesting is True:
private function:
private void ErrorMsgToResponse(Exception ex)
{
string sEx = String.Format("Source: {0}" +
"<br />TargetSite: {1}" +
"<br />Message: {2}" +
"<br />Exception: {3}" +
"<br />InnerException: {4}<hr />",
ex.Source, ex.TargetSite, ex.Message,
ex.ToString(), ex.InnerException);
if (_IsTesting) Response.Write(sEx);
}
usage:
try
{
Code that might blow up.
Code that might blow up.
Code that might blow up.
Code that might blow up.
Code that might blow up.
}
catch (Exception ex)
{
SendErrorMsgToResponse(ex);
}
The cool thing is, since the value is set in the Web.config,
I can change it from False to True on the QA (or even production) site
without re-compiling or re-deploying the code.
To get the local computer's time, when you want that instead of the server's DateTime.Now:
/*
PURPOSE: assuming there is a hidden control on a page called hdnClientSideDate,
gets the user machine's date and formats it so that C#'s DateTime.TryParse()
can read it, and puts that value into hdnClientSideDate, to replace DateTime.Now
aka server time for OnTime Incidents.
*/
function GetClientSideTime() {
var hdnDate = $("#<%= hdnClientSideDate.ClientID %>");
if (hdnDate.length > 0) {
var d = new Date();
var month = d.getMonth() + 1;
hdnDate.val(d.getFullYear() + "-" + month.toString() + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds());
}
return true;
}
In code:
<!-- to pass local DateTime to server -->
<asp:HiddenField ID="hdnClientSideDate" runat="server" />
Code behind:
private DateTime _clientSideDate = DateTime.Now;
public DateTime ClientSideDate
{
get { return _clientSideDate; }
set { DateTime.TryParse(hdnClientSideDate.Value, out _clientSideDate); }
}
To get a valid email address:
<asp:ValidationSummary ID="vldAddEditEquipmentSummary" runat="server" CssClass="validation" Style="margin-top:-5px; margin-bottom:10px;" EnableClientScript="true" DisplayMode="BulletList" HeaderText="The Following Error(s) Occurred:" ShowSummary="true" ValidationGroup="AddEditEquipment" Visible="true" />
<label>Alt Email Address:</label>
<asp:TextBox ID="txtAltEmailAddress" runat="server" style="margin-left:2px;" />
<asp:RegularExpressionValidator
ValidationExpression="^\s*[\w\.\-]+@[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]{1,})*(\.[a-zA-Z]{2,3}){1,2}\s*$"
EnableClientScript="true"
ID="vldAltEmailAddress" runat="server" Display="None"
ControlToValidate="txtAltEmailAddress" ValidationGroup="AddEquipmentRequest"
ErrorMessage="Alt Email Address must be in a valid email address format." />
google: string to stream c sharp
http://www.csharp411.com/c-convert-string-to-stream-and-stream-to-string/
To convert a C# String to a MemoryStream object, use the GetBytes Encoding method to create a byte array, then pass that to the MemoryStream constructor:
byte[] byteArray = Encoding.ASCII.GetBytes( test );
MemoryStream stream = new MemoryStream( byteArray );
Convert Stream to String
To convert a Stream object (or any of its derived streams) to a C# String, create a StreamReader object, then call the ReadToEnd method:
StreamReader reader = new StreamReader( stream );
string text = reader.ReadToEnd();
----- OR -----
string test = "Testing 1-2-3";
// convert string to stream
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter( stream );
writer.Write( test );
writer.Flush();
// convert stream to string
stream.Position = 0;
StreamReader reader = new StreamReader( stream );
string text = reader.ReadToEnd();
google: C# stream to file
http://www.java2s.com/Tutorial/CSharp/0300__File-Directory-Stream/SavetheMemoryStreamasafile.htm
google: c# write stream to response
http://gargmanoj.wordpress.com/2008/07/17/writing-a-memorystream-to-response-object-for-opening-a-open-save-cancel-dialogue-in-aspnet-20/
Following code block can be used to show user on Open/Save/Cancel dialogue box in browser for a memory stream.
if (ms != null)
{
Byte[] byteArray = ms.ToArray();
ms.Flush();
ms.Close();
Response.BufferOutput = true;
// Clear all content output from the buffer stream
Response.Clear();
//to fix the “file not found” error when opening excel file
//See http://www.aspose.com/Community/forums/ShowThread.aspx?PostID=61444
Response.ClearHeaders();
// Add a HTTP header to the output stream that specifies the default filename
// for the browser’s download dialog
string timeStamp = Convert.ToString(DateTime.Now.ToString(“MMddyyyy_HHmmss”));
Response.AddHeader(“Content-Disposition”, “attachment; filename=testFileName_” + timeStamp + “.fileextention”);
// Set the HTTP MIME type of the output stream
Response.ContentType = “application/octet-stream”;
// Write the data
Response.BinaryWrite(byteArray);
Response.End();
}
This is what I did in C:\VRM\Products\ITServices\1.0\SourceCode\VRM.ITServices.Website\Directory\ADPUpload.aspx.cs
string file = sbFile.ToString();
byte[] bytes = Encoding.ASCII.GetBytes(file);
Response.Clear();
Response.ClearHeaders();
//attachment makes the save as dialog appear in this case
Response.AddHeader("Content-Disposition", string.Concat("attachment; filename=", importFileName));
Response.AddHeader("Content-Type", "application/octet-stream");
Response.BinaryWrite(bytes);
Response.End();