Monday, October 24, 2005

Forcing File Downloads

In C# (ASP.NET) it’s just as simple:

private void Page_Load(object sender, System.EventArgs e)
{
// Disable caching this page (C#)
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Buffer = true;
Response.ContentType = "application/binary";
Response.AppendHeader("Content-Disposition: attachment; " +
filename=dlimg.png");
Response.WriteFile(Server.MapPath("images/dlimg.png");
Response.End();
}

SimpleBits | Magic Icons for Lazy People (like me)

A neat little trick for those that want to change a site’s colors — but also create only one set of images that also reflects those changes. It’s been done on numerous sites, and I’ve employed the method on Fast Company with the redesign done back in April.
The idea is pretty darn simple, and works best with two-color images. Create a two-color .gif image and choose one of the colors to be transparent. Next, we’ll “fill in” the missing color with CSS using background. Change the CSS rule and the images will change with it. Very simple — but effective, and a heck of a lot simpler than creating multiple sets of icons.

Here’s an example (using inline styles to demonstrate). Below is a small little icon (13px x 13px) that is white and transparent. I’ll fill in the transparency with a few different colors using the same icon image, repeated:



On Fast Company I place icons within h3 headings and style them like this:


h3 img {
background: #369;
vertical-align: middle;
}
It’s important to note that because I’m using white as the visable color, the icons will be invisible on the un-styled version of the page. This could an unintended benefit. Keeping decorative images entirely in the CSS file using background-image is arguably a more ideal solution — but the chameleon effect you can create with one set of transparent images is a nice little trick.

Thursday, September 22, 2005

How to increase the request size limit and make possible the upload of larger files?

If you ever used the ASP.NET file upload control you may be
have noticed that if you try to upload a file which size
exceeds 4MB, the upload failes.
The reason for this is the ASP.NET precaution against
denial-of-service attacks which by default limits the
size of the requests at 4MB.
However if in your application you need to upload larger files
you may increase this limit, by simply modifying the
maxRequestLength attribute in your machine.config file
...

How to get the host name from an IP address?

public string getHost(string ip)
{
IPHostEntry IpEntry = Dns.GetHostByAddress(ip);
return iphostentry.HostName.ToString();
}

How to strip the HTML tags from text with C# and Regular expression?

string strResult = Regex.Replace(strInput,@"<(.|\n)*?>",string.Empty);

Thursday, June 23, 2005

Switch Options for Windows NT Boot.ini File

Available Switch Options for Windows NT Boot.ini File

SQL TRUNCATE

If you want to clear out a table in MS SQL that includes an identity field AND want to reset the field so it starts over at 1, use TRUNCATE instead of DELETE FROM.

Tuesday, June 14, 2005

Windows Media Player 8,9,10 CD to MP3:

HKLM\SOFTWARE\Microsoft\MediaPlayer\Settings\MP3Encoding
SetValue "HighRate"=dword:0001F400 (128000)
HKLM\SOFTWARE\Microsoft\MediaPlayer\Settings\MP3Encoding
SetValue "MediumHighRate"=dword:0001B580 (112000)
HKLM\SOFTWARE\Microsoft\MediaPlayer\Settings\MP3Encoding
SetValue "MediumRate"=dword:0000FA00 (64000)
HKLM\SOFTWARE\Microsoft\MediaPlayer\Settings\MP3Encoding
SetValue "LowRate"=dword:0000DAC0 (56000)

WinXP Home to XP Pro Lite - ?????

HKEY_LOCAL_MACHINE\Homekey\ControlSet001\Services\setupdd
key Standard format REG_BINARY all 0
01 --> 00
02 --> 00

or:

HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Control\ProductOptions
set to empty, than reboot to last known good config..

or use NTSwitch.

Monday, March 21, 2005

Close All for VS 2003

Imports EnvDTE
Imports System.Diagnostics

Public Module CloseAll
Private maxTries As Integer = 3
Sub CloseAll()
Dim currentTries As Integer = 0
While (Not exeClose()) And currentTries < maxTries
currentTries += 1
End While
End Sub

Function exeClose() As Boolean
Try
For Each d As Document In DTE.Documents()
d.Close(vsSaveChanges.vsSaveChangesPrompt)
Next
Catch
Return False
End Try

Return True
End Function

End Module

Saturday, March 19, 2005

AccessorsCreator for VS

Imports EnvDTE
Imports System.Diagnostics

Public Module AccessorsCreator
Sub createAccessor()
Dim selected As String = DTE.ActiveDocument().Selection.text()
If (selected Is Nothing Or selected.Length = 0) Then
Exit Sub
End If

selected = selected.Replace(",", "")
selected = selected.Replace(";", "")
Dim parts() As String = selected.Split(" ")
Dim memberCount As Integer = parts.Length - 2

Dim basicOutput As String = "public $TYPE$ $PROP_NAME$ {" & vbCrLf _
& vbTab & "get { return $MEMBER_NAME$; }" & vbCrLf _
& vbTab & "set { $MEMBER_NAME$ = value; }" & vbCrLf _
& "}" & vbCrLf & vbCrLf

Dim results(memberCount) As String
For i As Integer = 2 To parts.Length - 1
Dim propName As String
propName = parts(i).Substring(0, 1).ToUpper() & parts(i).Substring(1)
results(i - 2) = basicOutput.Replace("$MEMBER_NAME$", parts(i))
results(i - 2) = results(i - 2).Replace("$PROP_NAME$", propName)
results(i - 2) = results(i - 2).Replace("$TYPE$", parts(1))
Next

Dim entryLine As Integer = DTE.ActiveDocument().Selection.BottomLine + 1
DTE.ActiveDocument().Selection.GotoLine(entryLine)

For i As Integer = 0 To results.Length - 1
DTE.ActiveDocument().Selection.Insert(results(i))
Next
End Sub
End Module

Wednesday, March 02, 2005

SYSTEM: DMA

Delete these four properties to force XP to reevaluate IDE
devices DMA capabilities on next boot.

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E96A-E325-11CE-BFC1-08002BE10318}\0001]
"MasterIdDataCheckSum"=dword:0
"SlaveIdDataCheckSum"=dword:0

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E96A-E325-11CE-BFC1-08002BE10318}\0002]
"MasterIdDataCheckSum"=dword:0
"SlaveIdDataCheckSum"=dword:0

Tuesday, March 01, 2005

C#: Hebrew Date

public static string GetHebrewJewishDateString(DateTime anyDate, bool addDayOfWeek)
{
System.Text.StringBuilder hebrewFormatedString = new System.Text.StringBuilder();

// Create the hebrew culture to use hebrew (Jewish) calendar
CultureInfo jewishCulture = CultureInfo.CreateSpecificCulture("he-IL");
jewishCulture.DateTimeFormat.Calendar = new HebrewCalendar();

#region Format the date into a Jewish format

if (addDayOfWeek)
{
// Day of the week in the format " "
hebrewFormatedString.Append(anyDate.ToString("dddd", jewishCulture) + " ");
}

// Day of the month in the format "'"
hebrewFormatedString.Append(anyDate.ToString("dd", jewishCulture) + " ");

// Month and year in the format " "
hebrewFormatedString.Append("" + anyDate.ToString("y", jewishCulture));

#endregion

return hebrewFormatedString.ToString();
}

Monday, February 28, 2005

C#: only specific characters to be typed into a TextBox

private void TextBox1_KeyPress(object sender, ystem.Windows.Forms.KeyPressEventArgs e)
{
e.Handled = e.KeyChar < '0' e.KeyChar > '9';
}

C#: restrict a program to a single instance

static void Main()
{
Process ThisProcess = Process.GetCurrentProcess();
Process [] AllProcesses = Process.GetProcessesByName(ThisProcess.ProcessName);
if (AllProcesses.Length > 1)
{
MessageBox.Show(ThisProcess.ProcessName + " is already running", ThisProcess.ProcessName, MessageBoxButtons.OK, MessageBoxIcon.Error);
} else {
Application.Run(new MainForm());
}
}

C#: progress bar in status

/// SNIPPET #1 ///
private ProgressBar m_ctrlProgress;
private System.Windows.Forms.StatusBarPanel panelProgress;
private void MainForm_Load(object sender, System.EventArgs e)
{
m_ctrlProgress = new ProgressBar();
m_ctrlProgress.SetBounds(104, 2, panelProgress.Width, statusBar.Height - 4); statusBar.Controls.Add(m_ctrlProgress);
m_ctrlProgress.Minimum = 0;
m_ctrlProgress.Maximum = 100;
m_ctrlProgress.Value = 0;
}
public void SetProgressRange(int nMin, int nMax)
{
m_ctrlProgress.Minimum = nMin;
m_ctrlProgress.Maximum = nMax;
}
public void SetProgressValue(int nValue)
{
m_ctrlProgress.Value = nValue;
}

/// SNIPPET #2 ///
// application level
ProgressStatusBar psb;
ProgressPanel pp;
public Form1() {
pp = new ProgressPanel();
pp.AutoSize = StatusBarPanelAutoSize.Spring;
psb = new ProgressStatusBar();
psb.Parent = this;
psb.Panels.AddRange(new ProgressPanel[] {pp});
ResizeRedraw = true;
this.Controls.Add(psb);
}

private void button1_Click(object sender, System.EventArgs e)
{
psb.UpdateValue(pp, pp.Value+10);
Invalidate(true);
}

C#: Retrieving Browser Capabilities

Boolean ActiveXControls = <%=Request.Browser.ActiveXControls.ToString()%>
Boolean AOL = <%=Request.Browser.AOL.ToString()%>
Boolean BackgroundSounds = <%=Request.Browser.BackgroundSounds.ToString()%>
Boolean Beta = <%=Request.Browser.Beta.ToString()%>
String Browser = <%=Request.Browser.Browser%>
Boolean CDF = <%=Request.Browser.CDF.ToString()%>
Boolean Cookies = <%=Request.Browser.Cookies.ToString()%>
Boolean Crawler = <%=Request.Browser.Crawler.ToString()%>
Boolean Frames = <%=Request.Browser.Frames.ToString()%>
Boolean JavaApplets = <%=Request.Browser.JavaApplets.ToString()%>
Boolean JavaScript = <%=Request.Browser.JavaScript.ToString()%>
Int32 MajorVersion = <%=Request.Browser.MajorVersion.ToString()%>
Double MinorVersion = <%=Request.Browser.MinorVersion.ToString()%>
String Platform = <%=Request.Browser.Platform%>
Boolean Tables = <%=Request.Browser.Tables.ToString()%>
String Type = <%=Request.Browser.Type%>
Boolean VBScript = <%=Request.Browser.VBScript.ToString()%>
String Version = <%=Request.Browser.Version%>
Boolean Win16 = <%=Request.Browser.Win16.ToString()%>
Boolean Win32 = <%=Request.Browser.Win32.ToString()%>

C#: directory size

public static long DirSize(DirectoryInfo d)
{
long Size = 0;
// Add file sizes.
FileInfo[] fis = d.GetFiles();
foreach (FileInfo fi in fis)
{
Size += fi.Length;
}
// Add subdirectory sizes.
DirectoryInfo[] dis = d.GetDirectories();
foreach (DirectoryInfo di in dis)
{
Size += DirSize(di);
}
return(Size);
}

//using:
DirectoryInfo dir_info = new DirectoryInfo(path_to_the_directory);
long Size = DirSize(dir_info);

HTML: desable the theme on the page

<meta equiv="MSThemeCompatible" content="No">

JAVASCRIPT: Trim

String.prototype.trim = function() {
// skip leading and trailing whitespace
// and return everything in between
var trimmedString = this
trimmedString = trimmedString.replace(/^\s+/,"");
trimmedString = trimmedString.replace(/\s+$/,"");
return trimmedString;
}
//using:
var trimmed_str=field_name.value.trim();

C#: restart ASP.NET site using code!

HttpRuntime.UnloadAppDomain();

C#: files operations

using System.IO;

//create directory:
Directory.CreateDirectory("C:\\testcsharp");
//create subdirectory:
Directory.CreateDirectory("C:\\testcsharp\\dump");
//move:
Directory.Move("C:\\testcsharp\\dump", "C:\\dump");
File.Move( "c:\\gooli.jpg", "c:\\temp\\gooli.jpg");
//delete:
Directory.Delete("C:\\dump");
File.Delete( "c:\\gooli.jpg" );
//copy:
File.Copy( "c:\\gooli.jpg", "c:\\temp\\abc.jpg");
//size of the file:
FileInfo fi = new FileInfo("C:\\gooli.jpg");Console.WriteLine("File size of gooli.jpg: {0}", fi.Length);
//delete a directory recursively:
Directory.Delete("C:\\testcsharp", true);

C#: running processes on a machine

using System.Diagnostics;

public static Process[] GetProcesses();
public static Process[] GetProcesses(string);
Sample:
Process[] procList = Process.GetProcesses();
for ( int i=0; i<20; i++)
{
string strProcName = procList[i].ProcessName;
int iProcID = procList[i].Id;
}

If you want processes on the local machine, you use GetProcesses(), else you use GetProcesses(string machinename).

C#: start a new process

System.Diagnostics.Process.Start("http://www.c-sharpcorner.com" );

HTML: link style

A,A:LINK,A:VISITED,A:ACTIVE,A:FOCUS{
color:#16420A;
text-decoration:underline;
xxx: expression(this.hideFocus = true);
}

JAVASCRIPT: createPopup

var macamMailPopup = window.createPopup();

function openMacamMailPopup() {
var popupBody = macamMailPopup.document.body;
popupBody.style.backgroundColor = "lightyellow";
popupBody.style.border = "solid black 1px";
popupBody.innerHTML = document.getElementById("macamMailPopupHtml").innerHTML;
macamMailPopup.show(0, 0, 250, 85, document.getElementById("macamMailComment"));
}

C#: Run a new instance of IE from an application

run new instance of IE:
using SHDocVw;
public void OpenBrowser(string url)
{
object o = null;
SHDocVw.InternetExplorer ie = newSHDocVw.InternetExplorerClass();
IWebBrowserApp wb = (IWebBrowserApp) ie;
wb.Visible = true;
//Do anything else with the window here that you wish
wb.Navigate(url, ref o, ref o, ref o, ref o);
}