Tuesday, November 24, 2009

String or StringBuilder to stream/memorystrem

string myString = sb.ToString();
byte[] myByteArray = System.Text.Encoding.UTF8.GetBytes(myString);
MemoryStream ms = new MemoryStream(myByteArray);

Thursday, November 19, 2009

Shrinking SQL Server Database and Transaction Log

I was spending time on shrinking the transaction log and DB, some of our developer boxes didnt have enough space.After a while i just figured so i thought of sharing with others


backup log [DataBase Name] with truncate_only --Not supported in 2008
go
DBCC SHRINKDATABASE ([Data Base Name], 10, TRUNCATEONLY)
go

SQL Server 2008 use different approach because its no longer supports backup log with truncate_only

In SQL Server 2008 , Transaction can be shrinked in two step.

Set Recovery Model to Simple

Shrink the file using DBCC ShrinkFile

GO

-- database recovery model

ALTER DATABASE [Database Name]

SET RECOVERY SIMPLE;

GO

-- Shrink log file to 1 MB.

DBCC SHRINKFILE (2, 1)

-- 2 means log file ID or you can specify logfile like DBCC SHRINKFILE (db_log' , 1))

GO

ALTER DATABASE [Database Name]

SET RECOVERY FULL

GO

Thursday, August 20, 2009

WSP Builder Extension Error (System.Workflow.ComponentModel.Compiler.ITypeProvider)

Solving the error :The service 'System.Workflow.ComponentModel.Compiler.ITypeProvider' must be installed for this operation to succeed. Please ensure that this service is available.
To fix this issue you have to edit your project file :
Goto <project> <propertygroup> :
<projecttypeguids>{F8810EC1-6754-47FC-A15F-DFABD2E3FA90};{D59BE175-2ED0-4C54-BE3D-CDAA9F3214C8};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}</projecttypeguids>
For VB Project <Project :
<import project="$(MSBuildExtensionsPath)\Microsoft\Windows Workflow Foundation\v3.5\Workflow.VisualBasic.Targets">

Wednesday, August 19, 2009

How to Load an assembly from a file and call the metods of a class

  • Step 1: Add the reflection namspace
    using System.Reflection;

    Step 2: Load the assembly from the file
    Assembly testAsm = Assembly.LoadFrom(@"C:\AddList.dll");


  • Creates the assembly object by calling LoadFrom method in the assembly class and pass the path of the assembly as a parameter.

    Step 3 :Create the type object
    Type testType = testAsm.GetType("Blog.Sample.ListCreator");

    Call the GetType function of the assembly class to create the Type.In above example there is a namspace called Blog.Sample and class called ListCreator.

    Step 4:Create the instance of the Class
    object testObj = Activator.CreateInstance(testType);

    Use Activator.CreateInstance method to create the instance of the required class by passing the Type object which we created in the above step.

    Step 5: Call the method
    testType.InvokeMember("CreatList", BindingFlags.Default BindingFlags.InvokeMethod, null, testObj, new object[] { "BlogSample", "AssemblyBlog" });

    Use the Type.InvokeMember to call the method in the class of loaded assembly.

    Parameter Details:
    1, Name of the Method (Ex: "CreateList")
    2, Binding Flag(We are invoking a method so it will be BindingFlags.InvokeMethod)
    3, Binding object - you can pass null
    4, Target Object - which class's method need to be called (Object which is created by Activator.Creatinstance method - instance of the class)
    5, Object Array of parameters for method (Above passed two string parameters)
  • Cheers
  • Shyju Mohan

Thursday, July 23, 2009

Solving WCF's windows authentication issue in IIS

System.ServiceModel.ServiceHostingEnvironment+HostingManager/27836922
Exception: System.ServiceModel.ServiceActivationException: The service '/internetbanksignon.svc' cannot be activated due to an exception during compilation. The exception message is: Security settings for this service require Windows Authentication but it is not enabled for the IIS application that hosts this service.. --->
in this case you will need to set windows authentication and change the iis metabase manualy
On your IIS server, start Notepad, and then open the \system32\inetsrv\Metabase.xml file located on the hard disk.
In the section, locate the following line:
NTAuthenticationProviders="NTLM"
Modify the line so that it reads exactly as follows:
NTAuthenticationProviders="Negotiate,NTLM"
Check also the attribute of the solution vdir at the metabse.xml.

Tuesday, July 7, 2009

Creating WCF client for asmx wervice and passing default Credential

If you are consuming a asmx service as a WCF client and try to pass the credential to the service you may recieve following error.

The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate,NTLM

Reason : WCF uses anonymous authentication, whereas the ASP.Net development web server uses NTLM.

To avoid This error you have to spcify security configuration for wcf client in app.config of client


<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="WebsSoap" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />


<!--keey come here you have to spcify mode as TransportCredentialOnly -->
<security mode="TransportCredentialOnly">
<!--keey come here you have to spcify the clientCredentialType as Ntlm-->
<transport clientCredentialType="Ntlm"/>
</security>
</binding>
</basicHttpBinding>
<client>
<endpoint address="http://litwaredemo:28519/_vti_bin/webs.asmx"
binding="basicHttpBinding" bindingConfiguration="WebsSoap"
contract="SharePointService.WebsSoap" name="WebsSoap" />
</client>
</system.serviceModel>


How to pass Credential

SampleServiceClient sourceService = new SampleServiceClient ();

sourceService.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;

sourceService.ClientCredentials.Windows.ClientCredential = (NetworkCredential) System.Net.CredentialCache.DefaultCredentials;


Cheers
Shyju Mohan

Friday, July 3, 2009

Use of Dataview Find / FindRow OR DataTable Filtering


Some time people will get into confusion of usage and which object need to be used .Most of the time when we are dealing with a set of Data we have to filter the data based on certain criteria.Normally we all are dealing with two objects called DataView and DataTable. Let how these object can support filtering option.

1.Using DataTable

DataRow[] rows = dataTable.Select("Age > '25'", "Eid DESC")

Here you have a datatable in which you are applying filter condition as well as sorting order.

2.Using DataView

dataView.Sort = "ID";
DataRowView[] rows = dataView.FindRows("2500");

Here the limitation is you have to sort based on coloumn then filter based on that coloumn

3.Using DataView with filter Property
Dataset1.Tables[0].DefaultView.RowFilter = "Age > '25'";

Cheers
Shyju Mohan

Tuesday, April 28, 2009

How to get selected or current row from a gridview? How can i retrieve the hidden coloumns value from selected gridview row?

How to get current selcted row index in GridView?
I saw many people are struggling to get the current selected row when the rowcommand event.
In asp.net 2.0 row comand will be like this

protected void gridcommand(object sender, GridViewCommandEventArgs e)
here you can't get any property like e.RowIndex or e.Keys

But if you look at other specific event like OnRowUpdating OnRowDeleted ,properties like e.RowIndex or e.Keys are available so it will be easy to retrieve the values.you dont have to worry about this there is work around for getting this values in the command event ,i know that if you are using Gridview then you will definetly come across situation where you need to use the command event other than normal edit update and delete events.
thfollowing code sample will help you to retrieve those

protected void gridcommand(object sender, GridViewCommandEventArgs e) { GridViewRow row = (GridViewRow)((Control)e.CommandSource).Parent.Parent; GridView gv = (GridView)(e.CommandSource); string s = gv.DataKeys[row.RowIndex][0].ToString(); }

Wednesday, April 1, 2009

Build In Visual Studio

There are two type of compilers used for compiling
1. Visual Studio comes with a in-process compiler, or in-proc compiler.
2. In the .NET Framework we also ship a separate compiler: the framework compiler, CSC.EXE.

The downside of using the in-proc compiler is that it limits scalability. The Visual Studio address space is pretty crowded, and compiling large projects takes up a lot of address space. This wouldn't be a concern if Visual Studio spawned CSC.EXE for the build. So if you run into build scalability issues with a Visual Studio full build, you can often work around them by invoking MSBUILD.EXE from the command line supplying the .SLN file.

First Approach
So if you want to use the compiler comes with .Net Framework then change the setting of UseHostCompilerIfAvailable property in your project (.csproj) file to false (it defaults to true). Just put the following in the first PropertyGroup element at the top of your project file

<UseHostCompilerIfAvailable>false</UseHostCompilerIfAvailable>

Second Approach
"%SystemRoot%\Microsoft.NET\Framework\v3.5\msbuild.exe" "..\MysampleProject.sln" /p:"Platform=Mixed Platforms" /p:Configuration=Debug /t:rebuild /maxcpucount:20

Sunday, March 29, 2009

How do you find the CD Key of the Windows CD you have?

There different way you can find out the cd key

1. If you explore the windows cd and open up I386 it does reside in a file named UNATTEND.txt. I have successfully used this on VALID windows installations

2.The product key is typically printed on a label on the product packaging containing the CD when you purchase it. If you look closely at several copies of the same product, you'll see that the key is different on each label.

3.The product key is typically printed on a label at the bottom side of your laptop.

4.The product key is typically printed on a label at the right side of your desktop Cabinet.

Cheers