Get Windows Login Via ASP.NET

Here’s a very cool, easy way to get someone’s windows login in your ASP.NET page.

Imports System.Security
………
………

and

Dim authUserName As String
Dim aspUserName As String
authUserName = User.Identity.Name
aspUserName = Principal.WindowsIdentity.GetCurrent.Name
Label1.Text = “You are: ” & authUserName
Label2.Text = “This page runs as: ” & aspUserName

1) Start IIS
2) Expand your server and its default Web site, right-click the “your
project” site, and then click Properties.
3) On the Directory Security tab in the WindowsSite Properties dialog box,
click the Edit button in the “Anonymous access and authentication control”
section.
4) Click to clear the Anonymous access check box, verify that the Integrated
Windows authentication check box is selected, and then click OK.
5) Click OK to close the “your project” Properties dialog box.
6) Switch back to Visual Studio, and then run the project. Confirm that the
page is displayed with the following message:

You are: “Your Windows user name”
This page runs as: DomainOrServer\ASPNET

Booyah!

Photo

Roy

June 24th

Coding

Moving Emails via a Windows Form

If you have the requirement to create a Windows form that tinkers with Outlook, then look no further! Here’s a basic example project that moves emails from one location to another.

1.) Create a new project

2.) Drag and drop a label (“label1″) and a button (“button1″) onto Form1

3.) Go to the button1 Click event by doubleclicking on it

4.) In the Solution Explorer (on the far right), right-click on “References,” then “Add References.” At this point a pop-up should appear. Ensure you’re in the .NET tab and scroll down until you find “Microsoft.Office.Interop.Outlook.” Your version shouldn’t matter, but I’m using 12.0.0.0. Select it and hit OK.

5.) Add the following “using” code at the appropriate spot up top:
using Microsoft.Office.Interop.Outlook;

6.) Then, go back to the button Click event and add this code:
Microsoft.Office.Interop.Outlook.Application oOutlook;
Microsoft.Office.Interop.Outlook.NameSpace oNs;
Microsoft.Office.Interop.Outlook.MAPIFolder oFldr;
Microsoft.Office.Interop.Outlook.MAPIFolder oDestFldr;

oOutlook = new Microsoft.Office.Interop.Outlook.Application();
oNs = oOutlook.GetNamespace(“MAPI”);

7.) Next, right below the above code we add more code to reference the originating email box and the destination email box. Obviously your email box will have a different name.
oFldr = oNs.Folders["Mailbox - Anderson, Roy Mr"].Folders["Inbox"];
oDestFldr = oNs.Folders["Mailbox - Anderson, Roy Mr"].Folders["test"];

8.) Now we add some code to check if there’s email in the mailbox, and display a message if so:
if (oFldr.Items.Count > 0)
{
this.label1.Text = oFldr.Items.Count.ToString() + ” emails detected.”;
this.Refresh();
}

9.) Run the application and click button1. Voila! But this isn’t good enough. We want to actually move the emails, remember? Here’s some code to handle that. Add this inside the “if” loop above:
//process normal emails
string filter = “[MessageClass] = \”IPM.Note\”";
ProcessEmails(oFldr, oDestFldr, filter);

//process encrypted emails
filter = “[MessageClass] = \”IPM.Note.SMIME\”";
ProcessEmails(oFldr, oDestFldr, filter);

Note: there are more email types than the two referenced above, but that’s an article for another day.

10.) Now for the heart of this: the “ProcessEmails” function.
private void ProcessEmails(MAPIFolder oFldr, MAPIFolder oDestFldr, string filter)
{
Microsoft.Office.Interop.Outlook.Items oTestItems = oFldr.Items.Restrict(filter);
//cycle through each email
for (int i = oTestItems.Count; i > 0; i–)
{
this.label1.Text = “Cycling through email ” + i.ToString() + ” of ” + oTestItems.Count.ToString();
this.Refresh();

MailItem oMessage = (MailItem)oTestItems[i];

//move email
oMessage.Move(oDestFldr);
}
}

At this point you should have a fully-operational email moving program. Note that in the ProcessEmails function there’s so much more you can do. You can insert a record of each email into a datatable, you can strip out and parse attachments. The sky’s the limit! Ask if you have any questions.

Photo

Roy

June 4th

Coding

Customized Pop Up Box

Let’s say you want to have a customized Javascript alert pop up when something happens on your page. Here’s an example:

1.) Create a button on your ASPX page called “Button1″

2.) In it’s button Click event, type this: PopUpBox(“this is where you’d place a customized message”)

3.) Now for the actual function. Place this code in your code-behind:

Sub PopUpBox(ByVal x As String)
Dim NewScript As String
NewScript = “<script language=JavaScript>”
NewScript = NewScript & “alert(‘” & x & “‘);”
NewScript = NewScript & “</script” & “>”
If (Not ClientScript.IsClientScriptBlockRegistered(“alert”)) Then
ClientScript.RegisterClientScriptBlock(Me.GetType(), “alert”, NewScript)
End If
End Sub

Voila! You’re done. Now, in your codebehind, you can call the PopUpBox sub from anywhere and send it whatever message you’d like.

Photo

Roy

June 4th

Coding

Reading a File Name to Generate a Page Header

(Courtesy of a coworker. Thanks Mike!) This is written in VBScript for a Classic ASP page, but the concept is easily portable to ASP.NET.

Since I’m going to be including a generic header page on our new site, I needed a way to specify the page title without simply having a list of titles and checking for the right one. So, I decided to use the file name, which has the added benefit of making the file names make sense when you’re trying to find the right one. Getting the page title to Display In A Title Case was more difficult than I thought since I couldn’t find a function to do it for me. So, I decided to just beat the string into submission:
 
Dim title, t, pagetitle

‘Strip off the folder name
title = Mid(Replace(Request.ServerVariables(“SCRIPT_NAME”),”_”,” “),14,Len(Request.ServerVariables(“SCRIPT_NAME”))-17)

‘Split the text into an array
t = Split(title)

‘For each word in the title, take the first letter and make it uppercase, then append the rest of the word and a space ‘ However, if the word is “breakbulk”, make the first and sixth letters uppercase (since the boss wants it displayed as “BreakBulk”)

For Each x in t
If x = “breakbulk” Then
pagetitle = pagetitle & Ucase(Left(x,1)) & Mid(x,2,4) & Ucase(Mid(x,6,1)) & Right(x,3) & ” ”
Else
pagetitle = pagetitle & Ucase(Left(x,1)) & Right(x,Len(x)-1) & ” ”
End If
Next

Photo

Roy

June 4th

Coding

Easy Export to Excel From Gridviews

In a rush? Need to export data from an ASP.NET gridview? Here’s your solution.

1.) Create a button on your ASPX page called “btnExport”

2.) In the page directive (on your ASPX page) enter this: EnableEventValidation=”false”. This not always strictly necessary, but it does help resolve a couple potential issues.

3.) Insert this code into the button’s on Click function:

Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbtnExportToExcel.Click

If GridView1.Rows.Count.ToString + 1 < 65536 Then
GridView1.AllowPaging = “False”
GridView1.DataBind()

Dim tw As New IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim frm As HtmlForm = New HtmlForm()

Response.ContentType = “application/vnd.ms-excel”
Response.AddHeader(“content-disposition”, “attachment;filename=export.xls”)
Response.Charset = “”
EnableViewState = False
Controls.Add(frm)
frm.Controls.Add(GridView1)
frm.RenderControl(hw)
Response.Write(tw.ToString())
Response.End()
GridView1.AllowPaging = “True”
GridView1.DataBind()
Else

End If
End Sub

****And for you C#’ers****

protected void btnExport_Click(object sender, EventArgs e)
{
if (GridView1.Rows.Count + 1 < 65536)
{
GridView1.AllowPaging = false;
GridView1.DataBind();

System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
HtmlForm frm = new HtmlForm();

Response.ContentType = “application/vnd.ms-excel”;
Response.AddHeader(“content-disposition”, “attachment;filename=export.xls”);
Response.Charset = “”;
EnableViewState = false;
Controls.Add(frm);
frm.Controls.Add(GridView1);
frm.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
GridView1.AllowPaging = true;
GridView1.DataBind();
}
else
{

}
}

Photo

Roy

June 4th

Coding

Removing Duplicates Records in SQL

The top function removes duplicate records in SQL, the 2nd removes duplicates in T-SQL. Note that both require you to have an integer “uid” field. Besides that, both should be self-explanatory. If not, shoot me an email.

DELETE FROM table1 t1
WHERE t1.uid >
(
SELECT
MIN(t2.uid)
FROM table1 t2
WHERE
t1.field1 = t2.field1 AND
t1.field2 = t2.field2
)

DELETE FROM table1
WHERE uid IN
(
SELECT t1.uid
FROM table1 t1,
table1 t2
WHERE
t1.field1 = t2.field1 AND
t1.field2 = t2.field2 AND
t1.uid < t2.uid
)

Photo

Roy

May 6th

Coding

Dates in Gridviews

Here’s a couple methods for customizing your dates in gridviews. The first utilizes a TemplateField, the second a normal databound field. I like the 2nd best because it allows for easiest customization of whatever date you need.

<asp:TemplateField HeaderText=”Invoice” SortExpression=”CommDate”>
<ItemTemplate>
<asp:Label runat=”server” ID=”txtCommDate” Width=”70px” Text=’<%# eval(“CommDate”,”{0:MM/dd/yyyy}”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>

 
<asp:BoundField DataField=”CommDate” HeaderText=”Invoice” SortExpression=”CommDate” DataFormatString=”{0:d}” HtmlEncode=”false” />

Photo

Roy

May 4th

Coding

Dealing with time outs in .NET

Here’s numerous examples of how to deal with timeouts in .NET (but remember, ensure your time outs aren’t the result of un-optimized SQL queries).

In an App.Config file:
<connectionStrings>
<add name=”BLAH.Properties.Settings.BLAHConnectionString” connectionString=”Data Source=160.160.16.160;Initial Catalog=BLAH;Integrated Security=True;Connect Timeout=99999″ providerName=”System.Data.SqlClient” />
</connectionStrings>

 
In a Web.Config file:
<connectionStrings>
<add name=”BLAHConnectionString” connectionString=”Data Source=160.160.16.160;Initial Catalog=BLAH;Integrated Security=True;timeout=99999;” providerName=”System.Data.SqlClient”/>
</connectionStrings>

In the auto-generated code of an XSD file: This method is more advanced. Make a backup prior. You’ve been warned.
1.) Left-click the plus sign next to your XSD file. Find the one that has “Designer” in it’s name and open it up.

2.) Do a CTRL-F and search for “this._commandCollection[" (without the quotes). What you're looking for is something like this:
this._commandCollection[0].Connection = this.Connection;

You’ll find several of these. Sometimes there will be a “1″ or “2″, and so on, in the index position. After the connection line, add this code:
this._commandCollection[0].CommandTimeout = 99999;

So now your code will look like this:

this._commandCollection[0].Connection = this.Connection;
this._commandCollection[0].CommandTimeout = 99999;

Do this under every Connection line you find.

In the code-behind:
this.MyTableAdapter.Adapter.SelectCommand.CommandTimeout = 99999;
this.MyTableAdapter.Fill(this.MyDataSet.BLAH);

In the web.config:
<httpRuntime maxRequestLength=”1048576″ executionTimeout=”99999″ />

In the web.config: (note, kicking up your session timeout beyond 30 mins is generally considered to be a horribly bad idea. It leads to slooowness.)
<sessionState timeout=”99999″ />

In the code-behind:
SqlCommand myCommand = new SqlCommand ( );
myCommand.CommandText = “SELECT * FROM nw_Categories ORDER BY CategoryID”;
myCommand.CommandTimeout = 99999;

Note: the last one is placed into the SQLdatasource’s “Selecting” event.

Photo

Roy

May 4th

Coding

What is “Overloading” a class?

Hey all, 

If you’re a newbie coder, you’re probably wondering what “overloading” a class is. I wrote this primer up for a long-distance associate who’s cutting his teeth on classes.  His name (no surprise) is ”Tom.” ;) Block out about 15 mins and do the below if you’re clueless about overloaded classes.

1.) Create a new web site in Visual Studio.

2.) Right-click on your solution, go to “Add New Item” and create a new class (in should go in the app_code directory). Call your new class “Tom.” It should look just like this:

Imports Microsoft.VisualBasic

Public Class Tom

End Class

So yeah, you got class now.

3.) Now hop over to your webpage’s codebehind (Default.vb) and go into your page_load (accessible via one of the two dropdowns up top) and type “Tom.” Note the period at the end of “Tom.” That’ll give you an intellisense dropdown. Those two auto-generated functions you see are what every new object has by default. So, yes, you JUST created a “Tom” object! Woohoo! Your page_load should look like this:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Tom.

End Sub

4.) But we don’t want Tom to just have two default functions. That’s lame. Let’s give Tom some hands, feet, and brains functions! Your Tom class should now look like this:

Imports Microsoft.VisualBasic

Public Class Tom

Shared Sub hands()

End Sub

Shared Sub feet()

End Sub

Shared Sub brain()

End Sub

End Class

Save the file then hop back to step 3 again and re-do! You’ll see that when you re-type “Tom.” you get FIVE functions in your dropdown! Tom now has hands, feet, and brains! *sniffle* They grow up so fast…

5.) But Tom’s not finished. Those hands, feet, and brains don’t do shit! Our Tom is weak! Frail! We should add some processing or something in the those Subs so that they actually DO something…but hell with that. You get the idea, you can add processing if you so desire. Let’s move on to overloading!

6.) You can kick off the Tom “hands” function in the page_load just by typing “Tom.hands()” and whatever processing you have in the “hands” Sub will kick off when the page loads. Duh. There’s absolutely no need to send in a variable to the “hands” Sub. “Hands” gets along just fine without variables. BUT let’s say we want to have the option to send “hands” different variables. So we just dupicate “hands” like so:

Imports Microsoft.VisualBasic

Public Class Tom

Shared Sub hands()

End Sub

Shared Sub hands(ByVal ball As String)

End Sub

Shared Sub hands(ByVal ball As String, ByVal bat As String)

End Sub

Shared Sub hands(ByVal ball As String, ByVal bat As String, ByVal glove As String)

End Sub

Shared Sub feet()

End Sub

Shared Sub brain()

End Sub

End Class

Now, go back to the page_load in Default.vb and type “Tom.hands(”  After you type the parantheses you’ll see that the “hands” Sub now has FOUR possible ways to call it. You can just kick it off. Or you can send in different variables.

That is “overloading.” Basically, you’re duplicating a Function or Sub in a class BUT changing the variables. That’s all folks. Email if you have any questions. Another way to think of it is to use the phrase: “same function, different variables.”

P.S.—I know what you’re probably thinking: why not just create a Sub with a completely different name if you’re going to be sending in different variables? Why call multiple Subs the same name? This is done primarily for simplicity’s sake because the code in those same-named Subs accomplishes the same thing.

Photo

Roy

May 3rd

Coding

Project: Cyber-Sex (or Roy Gets Perverted)

Project: Cyber-Sex is at a standstill. I gave up on a volunteer and trolled the seedier areas of the inet, looking for a cyber forum whereby I could lose my cyber-virginity as sluttily as possible. Nothing major here. Just wanted to get in, do some cybering and get out. But oh no, it could never be so easy.

All the ladies I chatted to—get a load of this—wanted to GET TO KNOW ME FIRST. Seriously. WTF. I mean, why not just go to a bar then?? But whatever, so I tried to get to know them, but they were talkin’ about a couple hours worth of idle chit-chat before they were ready to “get it on.”  *rolls eyes*  Anyways, I did however manage to strike up some conversation in the forums about “cyber-sex.”

Resolved: Most cyberers cyber because they’re really horny and it’s a natural extension of online chatting.

Resolved pt2: There are a shit-load of sexual subcultures online! HOLY SHIT. From bestiality, to whipping, to Domination/Submission forums where all the women call all the men “sir” and/or “master” to forums where all the men call the women “maam” and/or “mistress.” Wife-swapping, organized group-sex, furry-sex, plushy-sex, sex-groups-i-can’t-even-figure-out-yet. Wow. And I thought I was a freak! I’m a joke compared to some of these folks!

Photo

Roy

January 1st

Day In The Life

Wanted: Cyber-Sex Volunteer

Good day ladies & gents. It is I, your friendly, neighborhood Roy. For far too long I have lambasted and ridiculed “cyber-sex” afficionados. I have done this because they are completely ridiculous bastards.

Well, perhaps I was being a tad too hard on them.

It’s recently occurred to me that the phrase “don’t knock it till you try it” comes into play. How can I continually bash these braindead fleshsacks if I’ve never even tried cybering?

In that vein, I ask that you all support me in PROJECT: Cyber-Sex. What I’ll need for this experiment is a willing female (or at least a really convincing male). At some point over the next couple days, me and said lady will do what the slack-jawed masses call “cyber-sex” over IM. We shall save copies of this “cyber-sex” and each post our opinions of the experience online.

I feel that this is important to do, since it will provide me with first-hand experience through which I can use to diss cyber-sexers even more. However, if by some freak chance, it really is “kewl,” “l33t,” or “r0xorz,” I shall happily eat crow and chime “Cyber-sex, ftw!” from the rooftops.

Do I have a volunteer? Cyber-sex virgin like myself preferred.

UPDATE:
The cyber-sex project is in jeopardy as it’s recently been pointed out to me that people who “cyber” are expected to masturbate while they “cyber.” I did not know this. This has immediately created in my mind about 20 billion more jokes. Exactly how the fuck do people masturbate AND type? I mean, I can’t imagine any two more opposite things on the arousal spectrum than holding a keyboard in one hand and my dick in the other. WTF IS WRONG WITH YOU PEOPLE?!

At any rate, the project is still on, but masturbation is clearly optional (this researcher will be abstaining, thankyouverymuch). I’m assuming the cyber experience will last about…I dunno…10 mins? I mean, this isn’t Paris in the springtime, it’s a keyboard at midnight.

Photo

Roy

January 1st

Day In The Life

The Love Masta Is IN

Here ye, here ye!

Me being the guru of sexual magnetism that I am, women the world over flock to me with their questions. Now when I’m not deflowering virgins, I try to take a little time out of my busy cunnilingus-filled day to answer some of the more interesting ones.
Q: Dear Roy The Sex-God, what do I have to do to make my online pics hotter w/o being too slutty?
A: Put your finger in your mouth. Trust me. You’ll only look goofy to other chicks.

Q: Dear Roy The Man-Candy, what’s the best way to find the man of my dreams?
A: Heh, you just found him sugar. I’ll be the wind beneath those wings, if ya know what I mean.

Q: Dear Roy The Founder of Lust-Ruckus-2006, why do I always attract the worst men?
A: That’s clearly indicative of a psychological defect on your part. I recommend an in-depth internal probe conducted on-site by yours truly. You can swing by about midnight or so…

Q: Dear Roy The Mighty Geyser of Love Honey, I’m going out on a blind date and I can’t decide what to wear. Should I go preppy, sleazy, or maybe casual?
A: Show cleavage. Everything else is optional.

Q: Dear Roy The Vibrating-Universal-Membrane-of-Love, why can’t I seem to get laid?
A: Huh? That is weird. Lemme check out yer pic—-AAAAAAAAAAAH!!! SWEET JEEZUS! MY EYES!!

Roy The Masturbatory Magnate has graciously made himself open to questions from his frothing audience. Ask away. Or turn into a cat lady. Your choice.

Photo

Roy

January 1st

Day In The Life

Planetary Conspiracies!

Dear friends,
It’s recently come to my attention that a self-appointed clique of supposed “scientists” seeks to strip Pluto of it’s title as a planet. Surely this is madness and folly. What’s next? Legalized bestiality in mall food courts?! I have no doubt that the real reason for this planet-stripping-attempt is in fact part of a wider political agenda orchestrated by the bloated energy industry! Or possibly the pharmaceutical industry as we all know that mining for chemicals is cheaper on bodies not defined as planets. Whatever.

In light of this Plutonic brouhaha, it’s occurred to me that the reason Pluto is in the cross-hairs is because it’s an easy target. Just a typical case of interplanetary bullying that’s all too common in these troubled times. You may ask yourself ’why aren’t the other planets up for reconsideration?’ Well, I’ll tell ya why…

Mercury: Shortest year, speediest orbit. One side of him is almost absolute zero and the other side blazing hot. Sounds like a bipolar case to me. Fast too. Wouldn’t take much to tip him into the homicidal (planecidal?) category. The planets actually sent someone to tell this runt he wasn’t a planet before(see “Asteroid Belt”).Now they just leave him be…

Venus: Molten surface, 24/7 acid rain, average temp could melt lead… Rumor has it she had a moon, but it got on her nerves once.ONCE.

Earth: Flower-child of the system. If it went away, where would the other planets buy their moonshine and weed?

Mars: Named for the God of War. They say it’s surface is red because of iron oxidization. Right. Sure.

Asteroid Belt: Was once a planet till it talked some smack to Mercury. The other planets don’t like to talk about what happened…

Jupiter: Mobster of the system. As big as 1000 earths. Has a crew of like 19 moons. You try telling it what it is to it’s face.

Saturn: Pretty boy of the system. Loves to model. Totally maxed out on groupies, has like 20 moons.

Uranus: Smells like ass. The other planets tell it it’s a planet just to keep it downwind in the back areas of the system.

Pluto: Old man. Has 3 teeny-weeny moons. Minds his own business. Easy to pick on.

EDIT: One of my more astute readers pointed out to me that I had forgotten the planet Neptune. To Neptune, I apologize. The list should henceforth include the following entry:

Neptune: Everyone always forgets it’s a planet anyways, so who cares?

Photo

Roy

August 14th

Day In The Life

At Gus’s Funeral

The murmur of mourners trailed the two as they left the funeral.

“John, right?” said Jane, offering a hand.

“That’s me, and you’re Jane, correct?” John waited for her nod before continuing. “It’s a shame we had to meet here, like this. Were you close to Gus?”

Jane looked askance at John. “Very. I’ll miss hi–” she stopped mid-sentence, turnt her head, and placed her hand over her mouth.

John rested his hand on her back as she shuddered. He felt her bra strap against his palm, the contents it withheld springing to mind. He shoved the thoughts back even as his eyes drifted over her curves.

“I’m sorry Jane. You know, at least he’s at peace now.”

“I know, I know.” Her breath came in huffs as she held back tears. “It’s just…I owe him so much. I’ve come so far because of him!”

John noticed the gold Rolex as her hand gestured. “He got you a job too, didn’t he?” he asked.

“No, a sex change.” said Jane.

Photo

Roy

January 1st

Stories
line
May 2012
S M T W T F S
« Jul    
 12345
6789101112
13141516171819
20212223242526
2728293031