Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

mornlee http://www.neokeen.com/mornlee

« Newer Snippets
Older Snippets »
Showing 1-10 of 18 total  RSS 

ISAPI URL Rewrite

// description of your code here
#include <windows.h>
#include <httpfilt.h>

#define MAX_URL_LEN 4096

BOOL WINAPI GetFilterVersion(HTTP_FILTER_VERSION * pVer)
{
      pVer->dwFlags = (SF_NOTIFY_SECURE_PORT | SF_NOTIFY_NONSECURE_PORT | SF_NOTIFY_PREPROC_HEADERS | SF_NOTIFY_ORDER_HIGH);
      pVer->dwFilterVersion = HTTP_FILTER_REVISION;
      strcpy_s(pVer->lpszFilterDesc,9,"Blah blah blah");
      return TRUE;
}

void ReMapURLs(CHAR* pUrl,HTTP_FILTER_CONTEXT* pfc,PHTTP_FILTER_PREPROC_HEADERS pHeaders)
{
      if (pUrl[0] != '/') return;

      CHAR *iUrl = 0;
      BOOL doSet = FALSE;

      char *sOldUrls[] = { "/test/", "/TEST/" };
      char *sNewUrls[] = { "/go/", "/GO/" };

      for (int i=0; i<2; i++)
      {
            if (iUrl = strstr(pUrl,sOldUrls[i]))
            {
                  doSet = TRUE;
                  memcpy(iUrl,sNewUrls[i],strlen(sNewUrls[i]));
            }
      }

      if (doSet) pHeaders->SetHeader(pfc, "url", pUrl);
}

DWORD WINAPI HttpFilterProc(HTTP_FILTER_CONTEXT *pfc,DWORD NotificationType,VOID * pvData)
{
      PHTTP_FILTER_PREPROC_HEADERS pHeaders;
      DWORD cUrlOrig = MAX_URL_LEN;
      DWORD cUrl = cUrlOrig;
      CHAR rgUrl[MAX_URL_LEN];
      CHAR *pUrl;
      BOOL result;

      switch ( NotificationType )
      {
            case SF_NOTIFY_PREPROC_HEADERS:
                  pHeaders = (PHTTP_FILTER_PREPROC_HEADERS) pvData;
                  result = pHeaders->GetHeader(pfc, "url", rgUrl, &cUrl);

                  if (!result && cUrl > cUrlOrig)
                  {
                        pUrl = (CHAR*)LocalAlloc(0, cUrl);
                        result = pHeaders->GetHeader(pfc, "url", pUrl, &cUrl);
                        if (!result)
                        {
                              LocalFree(pUrl);
                              break;
                        }
                        ReMapURLs(pUrl, pfc, pHeaders);
                        LocalFree(pUrl);
                  }
                  else
                        ReMapURLs(rgUrl, pfc, pHeaders);
                  break;
            default:
                  break;
      }
      return SF_STATUS_REQ_NEXT_NOTIFICATION;
}

SQL 2005 TSQL Script to list tables, indexes, file groups along with file names

// description of your code here

select 'table_name'=object_name(i.id)  ,i.indid
,'index_name'=i.name  ,i.groupid
,'filegroup'=f.name  ,'file_name'=d.physical_name
,'dataspace'=s.name from sys.sysindexes i
,sys.filegroups f  ,sys.database_files d
,sys.data_spaces s
where objectproperty(i.id,'IsUserTable') = 1
and f.data_space_id = i.groupid
and f.data_space_id = d.data_space_id
and f.data_space_id = s.data_space_id
order by f.name,object_name(i.id),groupid
go

HTTP Post

// description of your code here

            HttpWebRequest  request = (HttpWebRequest)WebRequest.Create(URL);

            byte[]    postDataBytes = Encoding.ASCII.GetBytes(postData);
            request.AllowAutoRedirect = true;

            request.Method        = "POST";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = postDataBytes.Length;
            request.Referer = URL;
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4";
            request.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
            request.Headers.Add("Accept-Language","en-us,en;q=0.5");
            request.Headers.Add("Accept-Encoding","gzip,deflate");
            request.Headers.Add("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
            
            if (cookie != "")
                request.Headers.Add("Cookie",cookie);

            Stream requestStream  = request.GetRequestStream();

            requestStream.Write(postDataBytes, 0 ,postDataBytes.Length);
            requestStream.Close();
	    
	    request.CookieContainer = new CookieContainer();
            // Get response
            resp = (HttpWebResponse)request.GetResponse();
            StreamReader responseReader =  new StreamReader(resp.GetResponseStream());

XML file to SQL

// XML file to SQL

CREATE TABLE XmlImportTest ( xmlFileName VARCHAR(300), xml_data xml ) 
GO 
DECLARE @xmlFileName VARCHAR(300) 
SELECT @xmlFileName = 'c:\TestXml.xml' 
-- dynamic sql is just so we can use @xmlFileName variable in OPENROWSET 
EXEC(' INSERT INTO XmlImportTest(xmlFileName, xml_data) SELECT ''' + @xmlFileName + ''', xmlData FROM ( SELECT * FROM OPENROWSET (BULK ''' + @xmlFileName + ''' , SINGLE_BLOB) AS XMLDATA ) AS FileImport (XMLDATA) ') 
GO 
SELECT * FROM XmlImportTest 
DROP TABLE XmlImportTest 

Digg Del.icio.us DotNetKicks javascript snippets

// description of your code here

<DIV class=diggbutton>
<SCRIPT type=text/javascript>
digg_url = 'http://digg.com/software/IE7_Pain';
</SCRIPT>

<SCRIPT src="http://digg.com/api/diggthis.js" type=text/javascript></SCRIPT>
</DIV>
<p><a  href="http://vaultofthoughts.net/ct.ashx?id=f3f92dc0-810e-45fc-a82e-3d6a761af198&url=http%3a%2f%2fwww.dotnetkicks.com%2fkick%2f%3furl%3dhttp%3a%2f%2fvaultofthoughts.net%2fIE7Pain.aspx""><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://vaultofthoughts.net/IE7Pain.aspx" border="0" alt="kick it on DotNetKicks.com" /></a></p>
		<div>
			<a href="http://del.icio.us/post" onclick="window.open('http://del.icio.us/post?v=4&noui&jump=close&url='+encodeURIComponent('http://VaultOfThoughts.net/IE7Pain.aspx')+'&title='+encodeURIComponent('IE7 Pain'), 'delicious','toolbar=no,width=700,height=400'); return false;"><img src="http://del.icio.us/static/img/delicious.small.gif" alt="Add to del.icio.us" border="0" />Add to del.icio.us</a>
		</div>

Cool Effects in Browser

// description of your code here

javascript:R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI=document.images; DIL=DI.length; function A(){for(i=0; i-DIL; i++){DIS=DI[ i ].style; DIS.position='absolute'; DIS.left=Math.sin(R*x1+i*x2+x3)*x4+x5; DIS.top=Math.cos(R*y1+i*y2+y3)*y4+y5}R++}setInterval('A()',5); void(0);

获�Exchange未读邮件数

// description of your code here

private int GetUnReadMailCount()
{
string url=“http://mail.felixwoo.com/exchange/�; //指定Exchange�务器地� 
System.Net.HttpWebRequest Request;
System.Net.WebResponse Response;
System.Net.CredentialCache MyCredentialCache;
string strUserName = “wufâ€?; //指定登录的用户å??
string strRootURI = url+strUserName ; //得到�访问邮箱的WebDAV地�
string strPassword = “123456�; //指定该用户的密�
string strDomain = “felixwoo.comâ€?; //指定域å??
string strQuery ="";
byte[] bytes = null;
System.IO.Stream RequestStream = null;
System.IO.Stream ResponseStream = null;
XmlDocument ResponseXmlDoc = null;
XmlNodeList HrefNodes= null;
XmlNodeList SizeNodes= null;
int count=0;
try
{
  // 用SQL查询WebDAV返回结果中的unreadcount节点.
  strQuery = "<?xml version=\"1.0\"?><D:searchrequest xmlns:D = \"DAV:\" >"
   + "<D:sql>SELECT \"DAV:displayname\",\"urn:schemas:httpmail:unreadcount\" FROM \"" + strRootURI + "\""
   + "</D:sql></D:searchrequest>";

  // 创建新的CredentialCache对象,构建身份凭�
  MyCredentialCache = new System.Net.CredentialCache();
  MyCredentialCache.Add( new System.Uri(strRootURI),
   "NTLM",
   new System.Net.NetworkCredential(strUserName, strPassword, strDomain)
   );

  // Create the HttpWebRequest object.
  Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(strRootURI);

  // 指定HttpWebRequest的身份凭�,此处为关键所在。如果使用之�
  // 创建的MyCredentialCache,则这个身份凭�是�以从Web�务器传递
  // 到Exchange�务器的,但是这样带�的问题也很明显,就是�能够自
  // 动获�当�登录到域的用户的身份。�便已��功登录到域,那也�
  // 能通过formå†?次输入用户å??密ç ?。因此,我在这里用的是
  // Request.Credentials = CredentialCache.DefaultCredentials,
  // 这样便å?¯ä»¥è޷得当å‰?用户的凭æ?®ï¼Œä½†æ˜¯è¿™æ ·å¸¦æ?¥çš„问题便是上é?¢æ??到的
  // 身份凭�无法传递的问题,解决方法请关注下篇文章。
  Request.Credentials = MyCredentialCache;

  // 指定WebDAV的SEARCH方法
  Request.Method = "SEARCH";

  // Encode the body using UTF-8.
  bytes = Encoding.UTF8.GetBytes((string)strQuery);

  // Set the content header length. This must be
  // done before writing data to the request stream.
  Request.ContentLength = bytes.Length;

  // Get a reference to the request stream.
  RequestStream = Request.GetRequestStream();

  // Write the SQL query to the request stream.
  RequestStream.Write(bytes, 0, bytes.Length);

  // Close the Stream object to release the connection
  // for further use.
  RequestStream.Close();

  // Set the content type header.
  Request.ContentType = "text/xml";

  // Send the SEARCH method request and get the
  // response from the server.
  Response = (HttpWebResponse)Request.GetResponse();

  // Get the XML response stream.
  ResponseStream = Response.GetResponseStream();

  // 创建XmlDocument对象,并获�收件箱的unreadcount节点的值
  ResponseXmlDoc = new XmlDocument();
  ResponseXmlDoc.Load(ResponseStream);
  HrefNodes = ResponseXmlDoc.GetElementsByTagName("a:displayname");
  SizeNodes = ResponseXmlDoc.GetElementsByTagName("d:unreadcount");
  for(int i=0;i<HrefNodes.Count;i++)
  {
   if(HrefNodes[i].InnerText=="æ”¶ä»¶ç®±")
    count=int.Parse(SizeNodes[i].InnerText);
  }
  ResponseStream.Close();
  Response.Close();
}
catch(Exception)
{
  // Catch any exceptions. Any error codes from the SEARCH
  // method request on the server will be caught here, also.
  return -1;
}
return count;
} 

获å?–当å‰?登陆用户的登陆å??

// description of your code here

http://support.microsoft.com/default.aspx?scid=kb;zh-CN;832769
//获å?–当å‰?登陆用户的登陆å?? 
WindowsPrincipal wp = (WindowsPrincipal)Thread.CurrentPrincipal; 
string wpname = wp.Identity.Name.ToString(); 
int j = wpname.LastIndexOf("\\"); 
string userName = wpname.Substring(j+1); 
string domainName = wpname.Substring(0,j); 

javascript

// description of your code here

<SCRIPT LANGUAGE="JavaScript1.1">
<!-- hide from non-scriptable browsers

// JavaScript sees numbers with leading zeros as octal values, so strip zeros
function stripZeros(inputStr) {
	var result = inputStr
	while (result.substring(0,1) == "0") {
		result = result.substring(1,result.length)
	}
	return result
}

// general purpose function to see if an input value has been entered at all
function isEmpty(inputStr) {
	if (inputStr == "" || inputStr == null) {
		return true
	}
	return false
}

// general purpose function to see if a suspected numeric input
// is a positive integer
function isNumber(inputStr) {
	for (var i = 0; i < inputStr.length; i++) {
		var oneChar = inputStr.substring(i, i + 1)
		if (oneChar < "0" || oneChar > "9") {
			return false
		}
	}
	return true
}

// function to determine if value is in acceptable range for this application
function inRange(inputStr) {
	num = parseInt(inputStr)
	if ((num < 0) || (num > 255)) {
		return false
	}
	return true
}

function isValid(inputStr) {
	if (isEmpty(inputStr)) {
		alert("Please enter a number")
		return false
	} else {
		if (!isNumber(inputStr)) {
			alert("Please enter numbers only")
			return false
		} else {
			if (!inRange(inputStr)) {
				alert("Valid range is 0 - 255")
				return false
			}
		}
	}
	return true
}

function allDone(form) {
  var inputStr1 = form.entry1.value
  var inputStr2 = form.entry2.value
  var inputStr3 = form.entry3.value
  var inputStr4 = form.entry4.value

  var doneVal
  var ok2Cont   = true

	if ( isEmpty(inputStr1) || isEmpty(inputStr2) ||
	   isEmpty(inputStr3) || isEmpty(inputStr4) ) {
     ok2Cont = false ;
     alert("All fields need to be filled in")	;
	}

  if (ok2Cont) {
     form.octet1.value = toBin(inputStr1)
     form.octet2.value = toBin(inputStr2)
     form.octet3.value = toBin(inputStr3)
     form.octet4.value = toBin(inputStr4)

     // Concatenate binary characters
     doneVal = toBin(inputStr1) + toBin(inputStr2) + toBin(inputStr3) + toBin(inputStr4) ;

     form.all4.value = doneVal

     // strip any leading zero
     doneVal = stripZeros(doneVal) ;

     // convert binary to decimal
     form.result.value = "HTTP://" + parseInt(doneVal, 2) ;
  } else {
     form.octet1.value = ""
     form.octet2.value = ""
     form.octet3.value = ""
     form.octet4.value = ""
     form.result.value = ""
  }
}


// Decimal to binary, returns an eight character string
function toBin(inVal) {
   base = 2 ;
   num = parseInt(inVal);
   binNum = num.toString(base);
   // pad leading spaces with "0"
   binNum = padTextPrefix(binNum, "0", 8) ;

   return binNum
}

// equiv to padl()
function padTextPrefix (InString, PadChar, DefLength)  {
   if (InString.length >= DefLength)
      return (InString);
   OutString = InString
   for (Count = InString.length; Count < DefLength; Count++)  {
      OutString = PadChar + OutString;
   }
   return (OutString);
}

// end hiding -->
</SCRIPT>

Search box

// description of your code here

<form action="/search" method="get"><input type="hidden" name="w" id="w" value="">
<table border="0" bgcolor="#FFFFFF" style="position:absolute;top:50;left:50%;margin-left:-120px;" cellpadding="0" cellspacing="0"  style="border-collapse: collapse"><tr><td>
<div id="bg" onmouseover="ov()" onmouseout="ot()">
<div id="bx" onmouseover="ovfm()" onmouseout="otfm()"><table border="1" cellpadding="0" cellspacing="0" bordercolorlight="#000000" bordercolordark="#000000" style="border-collapse: collapse" bordercolor="#111111"><tr><td><table border="0" cellpadding="0" cellspacing="0"><tr><td valign="bottom">
  <img src="/img/search.jpg" onclick="sh();" width="23" height="18"></td><td><input type="text" id="q" size="20" name="q" class="q" autocomplete="off" onclick="fs()" onfocus="fs()" onkeydown="rst()" style="border: 0;color: #000000;" value=""></td></tr></table></td></tr></table></div>
<div class="o" id="a1" style="visibility:hidden;" onmouseover="document.getElementById('a1').style.cursor='default'">

<div nowrap="nowrap" class="i" id="c1" onclick="si();" onMouseOver="this.className='ih';" onMouseOut="this.className='i'">
<span id="b1"><img width="10" height="13" src="/img/nodot.gif"></span>Artists similar to: </div>
<div nowrap="nowrap" class="i" id="c2" onclick="na();" onMouseOver="this.className='ih'" onMouseOut="this.className='i'">
<span id="b2"><img width="10" height="13"  src="/img/nodot.gif"></span>Artists named:</div>
<div nowrap="nowrap" class="i" id="c3" onclick="zi();" onMouseOver="this.className='ih'" onMouseOut="this.className='i'">
<span id="b3"><img width="10" height="13"  src="/img/nodot.gif"></span>Artists near zipcode: 
</div>
<div nowrap="nowrap" class="i" id="c4" onclick="ge();" onMouseOver="this.className='ih'" onMouseOut="this.className='i'">
<span id="b4"><img width="10" height="13"  src="/img/nodot.gif"></span>Artists in genre: 
</div>
<div nowrap="nowrap" class="i" id="c6" onclick="ez();" onMouseOver="this.className='ih'" onMouseOut="this.className='i'">
<span id="b6"><img width="10" height="13"  src="/img/nodot.gif"></span>Events near zipcode: 
</div>
<div nowrap="nowrap" class="i" id="c5" onclick="ws();" onMouseOver="this.className='ih'" onMouseOut="this.className='i'">
<span id="b5"><img width="10" height="13"  src="/img/nodot.gif"></span>Search whole site: 

</div>
</div>
</div>
</td><td><input type="submit" style="background:#006486; padding:0px; margin:0px; color:#fff; font-weight:bold; border:1px solid #006486;" value="Search"></td></tr></table>
</form>
« Newer Snippets
Older Snippets »
Showing 1-10 of 18 total  RSS