...
using System.DirectoryServices;
...
public bool IsValidLDAPUser(string userName, string password, string ldapPath)
{
DirectoryEntry entry = new DirectoryEntry(ldapPath, userName, password);
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.SearchScope = SearchScope.OneLevel;
try
{
SearchResult result = searcher.FindOne();
return result != null ? true : false;
}
catch
{
return false;
}
finally
{
if (searcher != null) searcher.Dispose();
if (entry != null) entry.Dispose();
}
}
...
A blog by an ordinary Linux user who uses Windows in his day job.
Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts
Tuesday, May 10, 2011
Validate user against LDAP...
Thursday, May 5, 2011
Validate webservice client via SOAP header...
First, the SOAP header
namespace SecureWebServiceDemo
{
using System;
using System.Web.Services.Protocols;
public class MySoapHeader : SoapHeader
{
private string _userName;
private string _password;
public MySoapHeader()
{
}
public string UserName
{
get { return _userName; }
set { _userName = value; }
}
public string Password
{
get { return _password; }
set { _password = value; }
}
}
}
Next, the webservice
using ...
namespace SecureWebServiceDemo
{
///
/// Summary description for MyWebService
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class MyWebService : System.Web.Services.WebService
{
public MySoapHeader _header;
private const string _userName = "testuser";
private const string _password = "123456";
[SoapHeader("_header")]
[WebMethod]
public string HelloWorld()
{
if (_header == null || _header.UserName != _userName || _header.Password != _password) throw new Exception("Invalid User");
return "Hello World";
}
}
}
Finally, the client side
...
localhost.MySoapHeader header = new localhost.MySoapHeader();
header.UserName = "testuser";
header.Password = "123456";
localhost.MyWebService test = new localhost.MyWebService();
test.MySoapHeaderValue = header;
Console.WriteLine(test.HelloWorld());
...
Friday, November 12, 2010
Converting int to base26 string in C#...
For my own reference.
public string ToBase26(int number)
{
char[] base26 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
int remainder = number % base26.Length;
int value = number / base26.Length;
return value == 0 ?
String.Format("{0}", base26[remainder]) :
String.Format("{0}{1}", ToBase26(value - 1), base26[remainder]);
}
Alternatively I can code it this way
public string ToBase26(int number)
{
if (number < 0) return String.Empty;
int remainder = number % 26;
int value = number / 26;
return value == 0 ?
String.Format("{0}", Convert.ToChar(65 + remainder)) :
String.Format("{0}{1}", ToBase26(value - 1), Convert.ToChar(65 + remainder));
}
Monday, November 8, 2010
Managing distributed transactions without enabling MSDTC...
Is it possible? Short answer is no. Long answer is yes, but only to certain extend. Another stupid attempt to solve problem in a situation where developers are the lowest being in the organisation. In the perfect world where things working as expected, dealing with distributed transaction is a snap.
This solution is not by any mean to be a replacement to MSDTC (not even in your wet dream). However, it is better to have something rather than nothing. I'd rather use this solution instead of executing another command to undo the changes manually which I feel ridiculous.
...
using(TransactionScope scope = new TransactionScope())
{
using (SqlConnection conn1 ...)
{
...
}
using (OracleConnection conn2 ...)
{
...
}
scope.Complete();
}
...
However the nightmare begin when your Server/DB admin give you a big "NO" to MSDTC but the other party insisted for data rollback if anything goes wrong during the process. So what I did was to create my own transaction manager class. Before I begin, I need to have a wrapper class that contain a connection and transaction objects, this is where the begintransaction happen. The class will be manage by the transaction manager. Technically it's just managing a group of local transactions.
using System;
using System.Data;
public class EnlistedDBConnection : IDisposable
{
private IDbConnection _connection;
private IDbTransaction _transaction;
public IDbConnection Connection
{
get { return _connection; }
}
public IDbTransaction Transaction
{
get { return _transaction; }
}
public EnlistedDBConnection(IDbConnection connection)
{
_connection = connection;
if (_connection.State == ConnectionState.Closed) _connection.Open();
_transaction = connection.BeginTransaction();
}
internal void Commit()
{
_transaction.Commit();
}
internal void Rollback()
{
_transaction.Rollback();
}
#region IDisposable Members
public void Dispose()
{
if (_connection != null && _connection.State == ConnectionState.Open) _connection.Close();
if (_connection != null) _connection.Dispose();
if (_transaction != null) _transaction.Dispose();
}
#endregion
}
Code for the transaction manager. Before commiting, I need to ensure all connections are alive, if any of it down, cancel everything. However there's still one worst case scenario that this code couldn't handle, after done with connection checking, while committing suddenly one connection down in the process. It is not possible to rollback the committed transaction. So chances for orphan data are still there.
using System;
using System.Data;
using System.Collections.Generic;
public class BasicTransactionManager : IDisposable
{
private bool _isCommited;
private List<EnlistedDBConnection> _enlistedConnections;
public BasicTransactionManager() : this(new List<EnlistedDBConnection>())
{
}
private BasicTransactionManager(List<EnlistedDBConnection> enlistedConnections)
{
_enlistedConnections = enlistedConnections;
}
public EnlistedDBConnection Enlist(IDbConnection connection)
{
EnlistedDBConnection item = new EnlistedDBConnection(connection);
_enlistedConnections.Add(item);
return item;
}
public void Complete()
{
Commit();
}
///
/// While in the loop, worst case scenario that this logic couldn't handle is that
/// if the first transaction committed, then the second one failed, chances for orphan data
/// to occur are there because we couldn't rollback something that has been commited.
///
private void Commit()
{
// if one of the db connection failed, cancel everything
if(!VerifyConnection()) throw new Exception("DB connection failed.");
string message = String.Empty;
foreach (EnlistedDBConnection enlistedConnection in _enlistedConnections)
{
try
{
enlistedConnection.Commit();
}
catch(Exception ex)
{
message += String.Format("{0}\r\n", ex.Message);
}
}
if(!String.IsNullOrEmpty(message)) throw new Exception(message);
_isCommited = true;
}
private void Rollback()
{
string message = String.Empty;
foreach (EnlistedDBConnection enlistedConnection in _enlistedConnections)
{
if(enlistedConnection.Connection != null && enlistedConnection.Connection.State == ConnectionState.Open)
{
try
{
enlistedConnection.Rollback();
}
catch (Exception ex)
{
message += String.Format("{0}\r\n", ex.Message);
}
}
}
if (!String.IsNullOrEmpty(message)) throw new Exception(message);
}
private bool VerifyConnection()
{
bool _allOpened = true;
foreach(EnlistedDBConnection enlistedConnection in _enlistedConnections)
{
if(enlistedConnection.Connection == null || enlistedConnection.Connection.State != ConnectionState.Open)
{
_allOpened = false;
break;
}
}
return _allOpened;
}
#region IDisposable Members
public void Dispose()
{
if (!_isCommited) Rollback();
_enlistedConnections.ForEach( delegate(EnlistedDBConnection item) { item.Dispose(); } );
// _enlistedConnections.ForEach( item => item.Dispose() );
}
#endregion
}
This is how I use it in my business object. EnlistedDBConnection exposed connection and transaction property. That's how I obtain the instance and pass it to Command object.
using (BasicTransactionManager transaction = new BasicTransactionManager())
{
EnlistedDBConnection dbcon1 = transaction.Enlist(/* your db connection object */);
EnlistedDBConnection dbcon2 = transaction.Enlist(/* your db connection object */);
...
transaction.Complete();
}
Note:This solution is not by any mean to be a replacement to MSDTC (not even in your wet dream). However, it is better to have something rather than nothing. I'd rather use this solution instead of executing another command to undo the changes manually which I feel ridiculous.
Monday, November 1, 2010
Compress and Decompress text using System.IO.Compression...
I'm lazy today. This code was copied directly from internet for my personal reference.
using System;
using System.Text;
using System.IO;
using System.IO.Compression;
public static class GZipStreamUtility
{
public static string Compress(string text)
{
if (String.IsNullOrEmpty(text)) return String.Empty;
byte[] buffer = Encoding.UTF8.GetBytes(text);
MemoryStream ms = new MemoryStream();
using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
}
ms.Position = 0;
MemoryStream outStream = new MemoryStream();
byte[] compressed = new byte[ms.Length];
ms.Read(compressed, 0, compressed.Length);
byte[] gzBuffer = new byte[compressed.Length + 4];
System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return Convert.ToBase64String(gzBuffer);
}
public static string Decompress(string compressedText)
{
if (String.IsNullOrEmpty(compressedText)) return String.Empty;
byte[] gzBuffer = Convert.FromBase64String(compressedText);
using (MemoryStream ms = new MemoryStream())
{
int msgLength = BitConverter.ToInt32(gzBuffer, 0);
int length = gzBuffer.Length - 4;
ms.Write(gzBuffer, 4, length);
byte[] buffer = new byte[msgLength];
ms.Position = 0;
using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
{
zip.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
}
}
}
Monday, October 18, 2010
Creating DBHelper that can support various types of database...
Yes I know there's a framework (EF, NH and whatever name that I've never heard before) that can solve the problem. Unfortunately, EF only works on new technologies (at least with .NET framework 3.5). What if we're stucked with an old Microsoft technologies (NH is another option, but I still couldn't figure out on how and where to begin with - ~ I ain't a .NET superstar ~)? Is it possible to do it then? Yes!!! back to basic stuff!!!
I've try it on .NET framework 2.0. IDBConnection, IDBTransaction and IDBDataParameter are available in System.Data namespace since .NET framework 1.1 however, DBDataReader in System.Data.Common was available not until .NET framework 2.0 (DBDataReader was derived by SqlDataReader, OracleDataReader and OleDbDataReader). Those are the important interfaces and class needed.
Basically we need to create an abstract layer to our db helper. Let's just call it IDBHelper. Define all basic methods that can support various databases. It's important not to have a method that is specific to any data provider such as ExecuteXmlReader.
Create an object factory that'll return the helper instance. This is the only place that we need to change if the project owner aka our client suddenly decided to use different data provider in future (reality is cruel).
I've try it on .NET framework 2.0. IDBConnection, IDBTransaction and IDBDataParameter are available in System.Data namespace since .NET framework 1.1 however, DBDataReader in System.Data.Common was available not until .NET framework 2.0 (DBDataReader was derived by SqlDataReader, OracleDataReader and OleDbDataReader). Those are the important interfaces and class needed.
Basically we need to create an abstract layer to our db helper. Let's just call it IDBHelper. Define all basic methods that can support various databases. It's important not to have a method that is specific to any data provider such as ExecuteXmlReader.
...For concrete implementation. Create a class that implement IDBHelper interface. I named the class as SqlClientHelper.
using System.Data;
using System.Data.Common;
public interface IDbHelper
{
IDbConnection CreateConnectionInstance(string connectionString);
...
DbDataReader ExecuteReader(IDbConnection connection, string query, CommandType cmdType, params IDbDataParameter[] commandParameters);
...
IDbDataParameter CreateParam(string paramName, object paramValue);
}
...Then, the code for OracleClientHelper.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
public class SqlClientHelper : IDbHelper
{
public IDbConnection CreateConnectionInstance(string connectionString)
{
return new SqlConnection(connectionString);
}
...
public DbDataReader ExecuteReader(IDbConnection connection, string query, CommandType cmdType, params IDbDataParameter[] commandParameters)
{
...
}
...
public IDbDataParameter CreateParam(string paramName, object paramValue)
{
SqlParameter param = new SqlParameter(paramName, paramValue);
...
}
...
}
...Noticed that the instantiation of connection and parameter object has been done in the class itself. Ideally, if we don't use any specific data provider namespaces in DAL layer, it should be flexible enough to use any database without the need to change the code logic. The concern is more on the abstract layer method signature.
using System;
using System.Data;
using System.Data.OracleClient;
using System.Data.Common;
public class OracleClientHelper : IDbHelper
{
public IDbConnection CreateConnectionInstance(string connectionString)
{
return new OracleConnection(connectionString);
}
...
public DbDataReader ExecuteReader(IDbConnection connection, string query, CommandType cmdType, params IDbDataParameter[] commandParameters)
{
...
}
...
public IDbDataParameter CreateParam(string paramName, object paramValue)
{
OracleParameter param = new OracleParameter(paramName, paramValue);
...
}
...
}
Create an object factory that'll return the helper instance. This is the only place that we need to change if the project owner aka our client suddenly decided to use different data provider in future (reality is cruel).
...The code at DAL
public static class SomeObjectFactory
{
public static IDBHelper GetHelperInstance()
{
return new SqlClientHelper();
// uncomment the code below for oracle client
// return new OracleClientHelper();
}
}
...This way, adding System.Data and System.Data.Common namespace should be sufficient enough to our DAL.
using (IDbConnection connection = SomeObjectFactory.GetHelperInstance().CreateConnectionInstance(connectionString))
{
connection.Open();
string query = "SELECT * FROM tblSomething WHERE Id = @Id";
IDbDataParameter param = MyObjectFactory.GetDBHelperInstance().CreateParam("@Id", id);
DBDataReader reader = SomeObjectFactory.GetHelperInstance().ExecuteReader(connection, query, CommandType.Text, param);
...
}
...
Monday, September 6, 2010
VB.NET vs C#, why bother? We're .NET developers after all...
I can't believe that people are still debating on this topic. While searching for anonymous methods in VB.NET, I came across to this article "Top 10 reasons VB.NET is better than C#". It was posted on August 23rd 2004 and the last comment was on August 31st 2010!!!
Update:
Did a search further with keyword "vb.net vs c#" and found out that there's another article from the same person on the same day, but this time it's the other way around. "Top 10 reasons C# is better than VB.NET".
Update:
Did a search further with keyword "vb.net vs c#" and found out that there's another article from the same person on the same day, but this time it's the other way around. "Top 10 reasons C# is better than VB.NET".
Exposing DTO to javascript in ASP.NET...
This post is a continuity from my previous post related to Calling a webservice from javascript in ASP.NET 2.0. Fundamentally it's sharing the same concept. This time I've written the code in ASP.NET 3.5 (Visual Studio 2008). There's no prerequisite required compare to when I did it in ASP.NET 2.0 (Visual Studio 2005).
Once I knew how to call a webservice from javascript in ASP.NET (regardless of version). I've search google to check whether it's possible to pass an object as a parameter to webservice method. Indeed it is possible to do that, but I must make sure that the object should be simple enough without any business logic and with limited behaviour. The object known as Data Transfer Object or in short DTO. Now here's the step by step on how to do it.
1) Using Visual Studio 2008, create new web site. Select ASP.NET Web Site.
2) To create DTO object, add new class under App_Code folder. Lets name it as Student. Paste the code below.
Once I knew how to call a webservice from javascript in ASP.NET (regardless of version). I've search google to check whether it's possible to pass an object as a parameter to webservice method. Indeed it is possible to do that, but I must make sure that the object should be simple enough without any business logic and with limited behaviour. The object known as Data Transfer Object or in short DTO. Now here's the step by step on how to do it.
1) Using Visual Studio 2008, create new web site. Select ASP.NET Web Site.
2) To create DTO object, add new class under App_Code folder. Lets name it as Student. Paste the code below.
using System;3) Create new webservice call MyWebService. Add System.Web.Script.Services namespace then add GenerateScriptType and ScriptService attribute to the webservice class. Notice that what I did here is almost the same as my previous post. The only extra code is at line 7 which is to expose Student class to javascript.
///
/// Summary description for Student
///
public class Student
{
public Student()
{
}
public string Id
{
get;
set;
}
public string Name
{
get;
set;
}
}
...4) Add two methods call GetStudents and TestSubmit. GetStudents method will return a list of students to the caller. Since I want to return it as a JSON object, I've set the ResponseFormat to JSON.
using System.Web.Script.Services;
///
/// Summary description for MyWebService
///
[GenerateScriptType(typeof(Student))]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class MyWebService : System.Web.Services.WebService
{
...
}
...5) Go to Default.aspx, add ScriptManager (again another same step as my previous post in ASP.NET 2.0).
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<Student> GetStudents()
{
var students = new List<Student>();
for (int x = 0; x < 10; x++)
{
students.Add(new Student
{
Id = x.ToString(),
Name = "Name" + x.ToString()
});
}
return students;
}
[WebMethod]
public string TestSubmit(Student student)
{
return String.Format("You've submitted Student object with Id: {0} and Name: {1}", student.Id, student.Name);
}
...6) Now add the html control
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference InlineScript="true" Path="~/MyWebService.asmx" />
</Services>
</asp:ScriptManager>
...
...7) and the javascript
<div>
<input id="btnLoad" type="button" value="Get Students" onclick="javascript:btnLoad_Click();" />
<input id="txtId" type="text" /><input id="txtName" type="text" />
<input id="btnSubmit" type="button" value="Submit" onclick="javascript:btnSubmit_Click();" />
<table id="myTable" border="1" cellpadding="1" cellspacing="1"></table>
</div>
...
...Now I have a web site that can call a webservice and passing an object as a parameter via javascript.
<script language="javascript" type="text/javascript">
function btnLoad_Click()
{
try
{
MyWebService.GetStudents(OnGetStudentsComplete);
}
catch(e)
{
alert("error " + e);
}
}
function OnGetStudentsComplete(result)
{
var htmlVal = "";
for(var x=0; x<result.length; x++)
{
htmlVal += "<tr><td>" + result[x].Id + "</td><td>" + result[x].Name + "</td></tr>";
}
$get("myTable").innerHTML = htmlVal;
}
function btnSubmit_Click()
{
try
{
var stu = new Student();
stu.Id = $get("txtId").value;
stu.Name = $get("txtName").value;
MyWebService.TestSubmit(stu, OnTestSubmitComplete);
var htmlVal = $get("myTable").innerHTML;
htmlVal += "<tr><td>" + stu.Id + "</td><td>" + stu.Name + "</td></tr>";
$get("myTable").innerHTML = htmlVal;
}
catch(e)
{
alert(e);
}
}
function OnTestSubmitComplete(result)
{
alert(result);
}
</script>
Sunday, September 5, 2010
Evolution of data query in C#...
One of the most common operation in programming is data query. In C# 1.2, normally I would use a custom collection class that derived from System.Collections. But for sake of example here, I'll show it with an ArrayList instead.
Here's a class that'll become an element of the collection (yes, I know Auto-Implemented Properties).
1) Lambda Expression
Here's a class that'll become an element of the collection (yes, I know Auto-Implemented Properties).
public class StudentThis is how I normally code in C# 1.2 (.NET Framework 1.1) with an ArrayList.
{
private int _id;
private string _name;
private string _gender;
public Student()
{
}
public int Id
{
get { return _id; }
set { _id = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public string Gender
{
get { return _gender; }
set { _gender = value; }
}
}
private ArrayList SomeFilterMethod(ArrayList myList)Generic list with action and predicate was introduced in C# 2.0 (.NET Framework 2.0). This is how my code will look like.
{
ArrayList result = new ArrayList();
for (int x = 0; x < myList.Count; x++)
{
if (((Student)myList[x]).Gender == "Male")
{
result.Add(myList[x]);
}
}
return result;
}
private List<Student> SomeFilterMethod(List<Student> myList)Not to forget an anonymous methods.
{
return mylist.FindAll(GetMaleStudents);
}
private bool GetMaleStudents(Student item)
{
return item.Gender == "Male";
}
private List<Student> SomeFilterMethod(List<Student> myList)In C# 3.0 (.NET Framework 3.5), there's LINQ with 2 flavours.
{
return mylist.FindAll( delegate(Student item) { return item.Gender == "Male"; } );
}
1) Lambda Expression
private List<Student> SomeFilterMethod(List<Student> myList)2) Query Expression
{
return mylist.FindAll( item => item.Gender == "Male" );
}
private List<Student> SomeFilterMethod(List<Student> myList)Between the two, personally I prefer the former.
{
return (from student in mylist
where student.Gender == "Male"
select student).ToList<Student>();
}
Wednesday, September 1, 2010
Calling a webservice from javascript in ASP.NET 2.0...
Prerequisite:
In Visual Studio 2005, to make a web project template available, you need to upgrade to SP1. The "other alternative" is to install VS80-KB915364-X86-ENU.exe and WebApplicationProjectSetup.msi. If you choose SP1 than ignore the "alternative" way.
1) For Ajax-Enabled Web Site, install ASP.NET Ajax 1.0.
2) Create new ASP.NET Ajax-Enabled Web Site.
3) Add reference System.Web.Extensions ver 1.0.61025.0.
4) On server side, create new WebService, add System.Web.Script.Services namespace and add ScripService attribute to your webservice class.
Here's the full source code:
MyWebService.asmx.cs
In Visual Studio 2005, to make a web project template available, you need to upgrade to SP1. The "other alternative" is to install VS80-KB915364-X86-ENU.exe and WebApplicationProjectSetup.msi. If you choose SP1 than ignore the "alternative" way.
1) For Ajax-Enabled Web Site, install ASP.NET Ajax 1.0.
2) Create new ASP.NET Ajax-Enabled Web Site.
3) Add reference System.Web.Extensions ver 1.0.61025.0.
4) On server side, create new WebService, add System.Web.Script.Services namespace and add ScripService attribute to your webservice class.
...5) On client side, create new web form and add ScriptManager to the aspx file that pointing to your webservice (MyWebService.asmx).
using System.Web.Script.Services;
...
[ScriptService]
public class MyWebService : WebService
{
public MyWebService()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
...6) Add an html button and its eventhandler.
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference InlineScript="true" Path="~/MyWebService.asmx" />
</Services>
</asp:ScriptManager>
...
...Done!!! Your first Ajax-Enabled Web Site.
<input id="btnOk" type="button" value="Ok" onclick="javascript:btnOk_Click();" />
...
<script language="javascript" type="text/javascript">
function btnOk_Click()
{
try
{
MyWebService.HelloWorld(OnHelloWorldComplete);
}
catch(e)
{
alert("error " + e);
}
}
function OnHelloWorldComplete(result)
{
alert(result);
}
</script>
Here's the full source code:
MyWebService.asmx.cs
using System;Default.aspx
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
///
/// Summary description for MyWebService
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class MyWebService : WebService
{
public MyWebService()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<!-- to include webservice proxy, set inlinescript=true, it's much more easier compare to adding script src=webservice.asmx/js -->
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference InlineScript="true" Path="~/MyWebService.asmx" />
</Services>
</asp:ScriptManager>
<div>
<input id="btnOk" type="button" value="Ok" onclick="javascript:btnOk_Click();" />
</div>
</form>
</body>
</html>
<script language="javascript" type="text/javascript">
function btnOk_Click()
{
try
{
MyWebService.HelloWorld(OnHelloWorldComplete);
}
catch(e)
{
alert("error " + e);
}
}
function OnHelloWorldComplete(result)
{
alert(result);
}
</script>
Tuesday, April 20, 2010
Retrieving data from LDAP...
//person
strFilter = String.Format("(&(objectCategory=person)(objectClass=user)({0}={1}))", strFieldNm, strValue);
//distribution group
strFilter = String.Format("(&(objectCategory=group)(objectClass=group)({0}={1}))", strFieldNm, strValue);
private SearchUsersList GetUsersOrDistributionGroups(string strFilter, string strLDAPPath, bool blnIsGroup)
{
SearchUsersList objResult = new SearchUsersList();
DirectorySearcher search = null;
try
{
if (strFilter != String.Empty)
{
search = new DirectorySearcher(new DirectoryEntry(strLDAPPath), strFilter);
}
else
{
search = new DirectorySearcher(strFilter);
}
if (search != null)
{
foreach (SearchResult result in search.FindAll())
{
DirectoryEntry entry = result.GetDirectoryEntry();
if (entry.Properties["mail"].Value != null && !String.IsNullOrEmpty(entry.Properties["mail"].Value.ToString()))
{
SearchUsers objUser = new SearchUsers();
objUser.ID = entry.Properties["samaccountname"].Value.ToString();
objUser.MailAddress = entry.Properties["mail"].Value.ToString();
objUser.UserName = entry.Properties["name"].Value.ToString();
objUser.UserType = blnIsGroup ? "LDAP Distribution Group" : "LDAP User";
objResult.Add(objUser);
}
}
}
}
catch
{
throw;
}
return objResult;
}
Saturday, October 3, 2009
HttpUtility.ParseQueryString save the day...
Imagine when coding, you're getting a querystring as a parameter in string format with something like "studentid=1024&stateid=12&zipcode=90210&editmode=false". To manipulate the zip code value how would you normally do?
Guess what, I'll blindly do a string manipulation to get or update the value. This is inefficient (on second thought, I feel like I'm stupid). I just noticed that there's an easy way available in .NET Framework that will make my life easier. It's available since .NET Framework 2.0!!! HttpUtility.ParseQueryString definitely save me from headache.
Sample code:
Guess what, I'll blindly do a string manipulation to get or update the value. This is inefficient (on second thought, I feel like I'm stupid). I just noticed that there's an easy way available in .NET Framework that will make my life easier. It's available since .NET Framework 2.0!!! HttpUtility.ParseQueryString definitely save me from headache.
Sample code:
private void SomeFunction()Here's the output:
{
const string queryString = "studentid=1024&stateid=12&zipcode=90210&editmode=false";
// Parses a query string into a NameValueCollection using UTF8 encoding.
var collection = HttpUtility.ParseQueryString(queryString);
// Original value
Console.WriteLine("original value in string format : ");
Console.WriteLine("{0}", collection);
// Get existing value
Console.WriteLine("existing value : {0}", collection.Get("zipcode"));
// Set new value
collection.Set("zipcode", "10001");
// Display the new value
Console.WriteLine("updated value : {0}", collection.Get("zipcode"));
// Convert back to string
Console.WriteLine("value in string format");
Console.WriteLine("{0}", collection);
}
original value in string format :
studentid=1024&stateid=12&zipcode=90210&editmode=false
existing value : 90210
updated value : 10001
value in string format
studentid=1024&stateid=12&zipcode=10001&editmode=false
Press any key to continue . . .
Thursday, October 1, 2009
System.Net.NetworkInformation...
An old post from my lost blog.
My brother was asking for help on how to get the information from network interface so that it can be use to monitor the network activity. I did some googling and I've found this piece of code. Simple enough but can be very useful if we expand it further.
My brother was asking for help on how to get the information from network interface so that it can be use to monitor the network activity. I did some googling and I've found this piece of code. Simple enough but can be very useful if we expand it further.
private static void GetNetworkInfo()
{
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
if (NetworkInterface.GetIsNetworkAvailable())
{
foreach (NetworkInterface iface in interfaces)
{
if (iface.OperationalStatus == OperationalStatus.Up && iface.NetworkInterfaceType != NetworkInterfaceType.Loopback)
{
IPv4InterfaceStatistics stats = iface.GetIPv4Statistics();
long newsentbytes = stats.BytesSent;
long newreceivedbytes = stats.BytesReceived;
long sentbytes = newsentbytes - (oldsentbytes == 0 ? newsentbytes : oldsentbytes);
long receivedbytes = newreceivedbytes - (oldreceivedbytes == 0 ? newreceivedbytes : oldreceivedbytes);
Console.WriteLine("Bytes sent: {0}", sentbytes.ToString());
Console.WriteLine("Bytes received: {0}", receivedbytes.ToString());
oldsentbytes = newsentbytes;
oldreceivedbytes = newreceivedbytes;
}
}
}
}
Subscribe to:
Posts (Atom)