Showing posts with label .NET Framework. Show all posts
Showing posts with label .NET Framework. Show all posts

Monday, May 14, 2012

Create and Read Excel File Using Oledb provider

When working with excel file for data mining or export data to excel many time required to read excel file and also write file. One can use Oledb Provider to connect existing file or create new excel file for report in .net

1. Get Sheets Name from Excel File

      
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
try
{
string filePath = @"c:\myExcel2012.xlsx";
conn.ConnectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES"";",filePath);
conn.Open();
DataTable dtSheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in dtSheets.Rows)
{
Console.WriteLine(dr["TABLE_NAME"].ToString()); // Print Sheet Name
}
}
finally
{
if(conn.State == ConnectionState.Open)
conn.Close();
}

2. Read Sheet Data

System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
try
{
string filePath = @"c:\myExcel2012.xlsx";
conn.ConnectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES"";", filePath);
conn.Open();
DataTable dtSheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in dtSheets.Rows)
{
Console.WriteLine(dr["TABLE_NAME"].ToString());
var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM " + dr["TABLE_NAME"].ToString();
var reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader); // This will load data from excel sheet to datatable.

// your code to work on sheet data.
}
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}

3. Create and Write Data to Excel sheet

            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
try
{
string pathOfFileToCreate = "c:\newexcel.xlsx";
conn.ConnectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES"";",pathOfFileToCreate);
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE TABLE sheet1 (ID INTEGER,NAME NVARCHAR(100))"; // Create Sheet With Name Sheet1
cmd.ExecuteNonQuery();
for (int i = 0; i < 1000; i++) // Sample Data Insert
{
cmd.CommandText = String.Format("INSERT INTO sheet1 (ID,NAME) VALUES({0},'{1}')", i, "Name" + i.ToString());
cmd.ExecuteNonQuery(); // Execute insert query against excel file.
}
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}

 


I feel that above sample code is best way to explain article.

Tuesday, May 1, 2012

Global assembly cache location change in .net 4.0

When .net Framework 4.0 release it comes with one major change and that change is GAC (Global assembly cache) location. Since first version of .net framework release GAC location is fix to %windir%/assembly. This is default location and you can change that location but default installation is always point to above location . ( If you want to know how to change GAC Location manually then look at my post http://dotnetstep.in/change-the-location-of-gac 

In .net 4.0 this default location is change to C:\Windows\Microsoft.net\Assembly

Why this thing is important to know?
1.  As default location is C:\Windows\Assembly we used to drag and drop assembly directly to GAC but this is not the case when work with 4.0
2. It is better to use GACUtil tool for .net 4.0 to install assembly.

Following link contain many information regarding this.
http://stackoverflow.com/questions/2660355/net-4-0-has-a-new-gac-why

Suggestion:
It would be nice if C:\Windows\Microsoft.net\Assembly as same look and feel as older GAC.
as per msdn shell extension is obsolete (http://msdn.microsoft.com/en-us/library/34149zk3.aspx

Please provide your input if you have any other thing to add.

Sunday, June 20, 2010

Process Bitmap Faster In .NET

In .NET (C# or VB.net) you can process Bitmap pixel by pixel.

Here is the example of simple code. ( Use Example of Gray Scale)

System.Drawing.Image img = System.Drawing.Bitmap.FromFile(@"C:\Test.jpg");
Bitmap bmp = (Bitmap)img;
         for (int x = 0; x < bmp.Width; x++)
         {
             for (int y = 0; y < bmp.Height; y++)
             {
                Color c =  bmp.GetPixel(x, y);
                int gray = (int)((c.R + c.G + c.B)/3);
                bmp.SetPixel(x,y,Color.FromArgb(gray,gray,gray));
             }
         }

Above code works fine but it takes to much time to process.In order to process Bitmap Image Faster “BitmapData” is powerful class in .NET. Here is the example of that class.

System.Drawing.Image img = System.Drawing.Bitmap.FromFile(@"C:\Test.jpg");
Bitmap bmp = (Bitmap)img;           
System.Drawing.Imaging.BitmapData data = bmp.LockBits(new Rectangle() { X = 0, Y = 0, Width = bmp.Width, Height = bmp.Height }, System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
IntPtr ptr = data.Scan0;           
int bytes  =data.Stride * bmp.Height;
byte[] rgbValues = new byte[bytes];           
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
int val = 0;
for (int counter = 0; counter < rgbValues.Length; counter += 3)
{
    val = rgbValues[counter + 0] + rgbValues[counter + 1] + rgbValues[counter + 2];
    rgbValues[counter+0] =  (byte)(val/3);
    rgbValues[counter+1] =  (byte)(val/3);
    rgbValues[counter+2] =  (byte)(val/3);
}
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
bmp.UnlockBits(data);      

This code works must faster than previous code. Test it with PictureBox Control and See the effect… :)

Sunday, September 20, 2009

Cross-thread operation not valid.

In window application , when you need to use Threading and access control inside that thread, then you get this error “Cross-thread operation not valid.” The reason behind this control is working under main thread and you create another thread in which you are trying to access control.

There are two ways to solve this error.

1. Set property in Form constructor.
You need to set static property CheckForIllegalCrossThreadCalls  of control class to false value. This will disable cross thread checking.
       
       public Form1()
       {
         InitializeComponent();
           Control.CheckForIllegalCrossThreadCalls = false;
       }

Sample Code (C#):

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Test));
            th.Start(1000);           
        }

        public void Test(object o)
        {
            for (int i = 0; i < 10; i++)
            {
                label1.Text = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + " --- " + i.ToString();
                System.Threading.Thread.Sleep(int.Parse(o.ToString()));
            }
        }
    }



2. Use delegate and event.

Sample Code (C#) :

public partial class Form1 : Form
    {
        delegate void SetLabelText(string str);
        SetLabelText setLabel1Text = null;
        public Form1()
        {
            InitializeComponent();
            setLabel1Text = new SetLabelText(Label1Text);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Test));
            th.Start(1000);           
        }

        public void Test(object o)
        {
            for (int i = 0; i < 10; i++)
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(setLabel1Text, System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + " --- " + i.ToString());
                }
                System.Threading.Thread.Sleep(int.Parse(o.ToString()));
            }
        }

        public void Label1Text(string str)
        {
            label1.Text = str;
        }
    }

Please give your comment on this.

Sunday, June 14, 2009

Remove Focus Rectangle From Button

Article is about to remove focus rectangle or say cues from Button in window form application.

First let discuss what default focus rectangle. Please look at following image , in that image OK button has default focus so it display cues rectangle.

image 
(FlatStyle == System)

When we want to set background image of button to make button attractive in that case this default rectangle create problem with look and feel.

image
(FlatStyle = Standard)
 
 image
(FlatStyle = Flat)

In above two image need to set FlatApperance.BorderStyle =0. You can visualize that in all above case default focus rectangle make button look ugly with background image.

To remove this cues ( Default focus rectangle ) you need to set ShowFocusCues property of Button to false but this property does not directly available to Button. This property available in ButtonBase class with protected access specifier. In order to set this property to false we need to create class that inherits from Button or ButtonBase and set this property explicitly false.

class CustomButton : System.Windows.Forms.Button
    {
        protected override bool ShowFocusCues
        {
            get
            {
                return false;
            }
        }
}

image
Now see that default focus rectangle is removed.

More generic class for Button.

class CustomButton : System.Windows.Forms.Button
   {
       private bool _DisplayFocusCues = true;
       protected override bool ShowFocusCues
       {
           get
           {
               return _DisplayFocusCues;
           }
       }

       public bool DisplayFocusCues
       {
           get
           {
               return _DisplayFocusCues;
           }
           set
           {
               _DisplayFocusCues = value;
           }
       }
   }

Using this class you can set DisplayFocusCues at design time so CustomButton work with any case. ( Want to display focus rectangle or not).

image 

Hope this solution is help you to create button without cues.

Your suggestion is always invited.

Programmatically Install Window Service

This article is about to install / uninstall window service programmatically from C#. This is useful when you need to install / uninstall window service from some other application.

For this purpose you need to use ServiceProcessInstaller and ServiceInstaller class from another application. These two installer classes are responsible for Installation of service.

C# Example for Programmatically Install Window Service.

ServiceProcessInstaller ProcesServiceInstaller = new ServiceProcessInstaller();
ProcesServiceInstaller.Account =  ServiceAccount.User;
ProcesServiceInstaller.Username = "<<username>>";
ProcesServiceInstaller.Password = "<<password>>";

ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
InstallContext Context = new System.Configuration.Install.InstallContext();
String path = String.Format("/assemblypath={0}", @"<<path of executable of window service>>");
String[] cmdline = { path };

Context = new System.Configuration.Install.InstallContext("", cmdline);              
ServiceInstallerObj.Context = Context;
ServiceInstallerObj.DisplayName = "MyService";
ServiceInstallerObj.Description = "MyService installer test";
ServiceInstallerObj.ServiceName = "MyService";
ServiceInstallerObj.StartType =  ServiceStartMode.Automatic;
ServiceInstallerObj.Parent = ProcesServiceInstaller;          

System.Collections.Specialized.ListDictionary state = new System.Collections.Specialized.ListDictionary();
ServiceInstallerObj.Install(state);

C# Example to Programmatically Uninstall Window Service.

ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
InstallContext Context = new InstallContext("<<log file path>>", null);
ServiceInstallerObj.Context = Context;
ServiceInstallerObj.ServiceName = "MyService";
ServiceInstallerObj.Uninstall(null);

other article related to window service.

http://dotnetstep.blogspot.com/2009/06/passing-parameter-to-installutil.html

http://dotnetstep.blogspot.com/2009/06/install-window-service-without-using.html

http://dotnetstep.blogspot.com/2009/06/install-windowservice-using-installutil.html

http://dotnetstep.blogspot.com/2009/06/get-windowservice-executable-path-in.html

Please give your idea about this article.

Saturday, June 13, 2009

Passing Parameter to InstallUtil

When installing window service or any installer ( class inherits from install class) required custom parameter at run time , Need to pass as parameter of installutil.

Crating window service using article (http://dotnetstep.blogspot.com/2009/06/install-windowservice-using-installutil.html).  This article suggest you add installer ( ProjectInstaller). Now we use installer class events to configure ServiceProcessInstaller and ServiceInstaller as per parameter pass to installutil.

[RunInstaller(true)]
public partial class ProjectInstaller : Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
           this.BeforeInstall += new InstallEventHandler(ProjectInstaller_BeforeInstall);
            this.BeforeUninstall += new InstallEventHandler(ProjectInstaller_BeforeUninstall);
        }       

        void ProjectInstaller_BeforeInstall(object sender, InstallEventArgs e)
        {
            // Configure Account for Service Process.
            switch(this.Context.Parameters["Account"])
            {
                case "LocalService":
                    this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService;
                    break;
                case "LocalSystem":
                    this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
                    break;
                case "NetworkService":
                    this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.NetworkService;
                    break;
                case "User":
                    this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.User;
                    this.serviceProcessInstaller1.Username = this.Context.Parameters["UserName"];
                    this.serviceProcessInstaller1.Password = this.Context.Parameters["Password"];
                    break;
            }      
            // Configure ServiceName
            if(!String.IsNullOrEmpty(this.Context.Parameters["ServiceName"]))
            {               
                this.serviceInstaller1.ServiceName = this.Context.Parameters["ServiceName"];
            }
        }

        void ProjectInstaller_BeforeUninstall(object sender, InstallEventArgs e)
        {
            if (!String.IsNullOrEmpty(this.Context.Parameters["ServiceName"]))
            {
                this.serviceInstaller1.ServiceName = this.Context.Parameters["ServiceName"];
            }
        }
    }

Above ProjectInstaller class handle two events : BeforeInstall and BeforeUninstall. BeforeInstall is called just before install method of installer (ProjectInstaller) called via InstallUtil and same way BeforeUninstall called just before Uninstall method of projectinstaller class. After adding that two event handler use following to configure service using installutil.

1. Install
installutil /Account=User /UserName=admin /Password=admin /ServiceName=WinService1 /i WindowService1.exe

2. Uninstall
installutil /ServiceName=WinService1 /u WindowService1.exe

This will also help you configure WindowService1.exe with two different name and different account.
installutil /Account=User /UserName=admin /Password=admin        /ServiceName=WinService1 /i WindowService1.exe

installutil /Account=LocalSystem /ServiceName=WinService2 /i WindowService1.exe

Install window service without using installutil

Article is about to install window service without using InstallUtil utility.
Windows XP or Later has command line utility called sc . (This utility talks with service controller and with services from command line).
SC is a window base utility. AS explain in article http://dotnetstep.blogspot.com/2009/06/install-windowservice-using-installutil.html sc does not required ProjectInstaller.

1. Start service using sc
          sc start ServiceName

2. Stop serivce
         sc stop ServiceName

3. Delete window service
        sc delete servicename
        Note : During delete call if service is in running state then service is delete when nexttime service is stop or PC restart.

4. Create window service
       sc create ServiceName binpath= “c:\windowservice1\windowservice1.exe”

       Apart from above many option available . For that just go to command prompt and type sc create /?

  For example configure service running account.

sc create servicename binpath= “c:\windowservice1\windowservice1.exe” obj= administrator password= pass

Hope this article will help you .

Please give your comment or idea about this.

In above all case Service ServiceName ( Mark as blue) , don’t use display name.

 image

Install WindowService using installutil.

This article is about to install to window service using installutil.exe. InstallUtil.exe or simply say installutil utility comes up with .NET Framework 2.0.

Steps.
1. Create new Window Service Project.
image 
2. After that open services1.cs in design mode . It looks like this.
image 
3. Now right click on design window. It open popup menu with installer option.
image
4. When you click on Add Installer. It will will add new class called projectinstaller.cs. It contain serviceprocessinstaller1 and serviceinstaller component. ServiceProcess installer is used to configure service account and serviceinstaller contain information about service.
image
5. Apart from above ProjectInstaller.cs contain following code which is used to call from installutil.
image
In above code RunInstaller attribute marked as true. So InstallUtil take this thing into consideration and use this information to call installer.

To install using installutil open VS 2005/VS 2008 command prompt or go to  %windir%\Microsoft.NET\Framework\v2.0.50727.

installutil.exe /i  WindowService1.exe ( To Install ).

installutil.exe /u WindowSerivce1.exe ( To uninstall).

Installutil use Installer class (Projectinstaller) to install service.

If you mark RunInstlaller as false then this installutil not work.

If you don’t want to use installutil to install wndow service then go to http://dotnetstep.blogspot.com/2009/06/install-window-service-without-using.html.

Tuesday, June 9, 2009

Get WindowService Executable Path In .NET

WindowService has a property called “Path to Executable” . This property contains path of window service that is going to execute. When you need this path in .NET Application there is no direct way to do it . You can not get it either via ServiceControler or any other way.

image 
To get that you need to read Registry. All information about all window service installed on machine storead at following location.
HKLM\SYSTEM\CurrentControlSet\Services.

C# Code to read Service Registry.

RegistryKey services = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services");
if (services != null)
{
object pathtoexecutable = services.OpenSubKey(<<ServiceName>>).GetValue("ImagePath");
}

In Above code replace <<ServiceName>> with your service name.

Also this is a registry operation so you need proper permission to read registry and apply any other registry operation at your own risk.

Give your comment or any new idea about this task.

Sunday, June 7, 2009

Redirect console application output to another application in .NET

In .NET sometime it is required to execute system command and capture its result or data in application that execute that command.
For example you want to execute ipconfig command from .NET application and display its result in window application or need to read output of .NET console application.

For this purpose you need to use Process class that belongs to System.Diagnostics namespace.

//Create process class object
System.Diagnostics.Process p = new System.Diagnostics.Process();

// Set StartInfo property.
// Set redirection true for Error and output stream.
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardOutput = true;

// When you set redirection you must set UseShellExecute to false .
p.StartInfo.UseShellExecute = false;

// Set window style
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

// Set Command paramter.
p.StartInfo.FileName = "ipconfig";
p.StartInfo.Arguments = " /all";

// Set CreateNoWindow to true as window is not required here.
p.StartInfo.CreateNoWindow = true;

// Following two events are new in .NET framework 2.0 which allow us to capture data asynchronously.

p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(p_OutputDataReceived);
p.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(p_ErrorDataReceived);

// Start the process.
p.Start();

// Must call following two methods in order to capture data asynchronously.
p.BeginErrorReadLine();
p.BeginOutputReadLine();

// Wait for Process to Exit ( This is not must done ).
p.WaitForExit();

// Event Handler for ErrorStream.
void p_ErrorDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
            System.Diagnostics.Debug.WriteLine(e.Data);   
}

// Event Handler for OutputStream.
void p_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
           System.Diagnostics.Debug.WriteLine(e.Data);
}

Even you can use this functionality to make utility like process command background and produce result in window application.

p.StartInfo.FileName = @"%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler.exe";
p.StartInfo.Arguments = @" -v / -f -p C:\Blog\WebSite1 c:\WebSite1Compile";
// Note : Replace %windir% with your window directory. or use p.StartInfo.EnvironmentVariables["windir"]

Above is the one example to compile website application from window application.

Apart from this there is event called Exited associated with Process class object. In order to receive this event you need to set EnableRasingEvents property to true value.

Give your comment and idea on this article.

Saturday, June 6, 2009

DateTime operation in .NET Application

DateTime is a very important datatype and data in terms of realtime application. Some of the application that run timely manner and some of the application that generate data (log file) with time.
To generate such report you need to required store information about date and time.

In .NET there is datatype called DateTime. This contain all information about datetime but sometime problem with this too.

For example:

DateTime dt = DateTime.Now;  // 6/6/2009 09:35:00 PM.
This is used to get current current time of system. If you store this time in file or in a database and later you retrieve then you get that time. So at last “6/6/2009 09:35:00 PM” this is going to  store in a file.

Problem occur when you retrieve this later to display information and by some reason you make changes to current time zone of system or sometime timezone of application. So then also you get “6/6/2009 09:35:00 PM.” as data , which is not right.

So best way to store date is UTC format.

DateTime dt = DateTime.UtcNow and after retrieval convert it to LocalTime but for that also you have to confirm that stored DateTime is in Utc format.

DateTime structure contains  methods called ToBinary() and FromBinary().

long binaryDate  = DateTime.Now.ToBinary() ;

Now store ‘binaryDate’ value in database or text file. So later when you get this value.

DateTime dt =  DateTime.FromBinary(binaryDate).  This will generate correct Date and Time even after timezone changed. This is because of binaryDate( Long ) value contain information about TimeZone too. So it automatically adjust as per system timezone.

Apart from this DateTime structure contain one field called ‘Kind’. which contain current DateTime format kind and that is Utc , Local or Unspecified. Many of case when you store simple way DateTime and later you retrieve kind is unspecified. But when you store binary date and later you retrieve you get either Utc or Local.

Please give your comment or any new idea about storing datetime.

Usage of aspnet_compiler.exe and aspnet_merge.exe

Whenever asp.net website or webapplication publish,aspnet_compiler.exe is used for compilation. 

Example :

WebSite : c:\myProject\TestSite

1 . Go to Visual Studio Tool from program menu and start Visual studio command prompt.
                                     or
     If you do not have visual studio installed on your machine and just .NET Framework 2.0 installed on your machine then also you can use aspnet_compiler tool. 
- Start > run  and type cmd.
- set path=%windir%\Microsoft.NET\Framework\v2.0.50727
- aspnet_compiler –v / –p c:\myproject\testsite c:\testcompile
  
   It will compile c:\myproject\testsite and put published site in c:\testcompile. 
- When you compile site using above command site is not updatable after publish. 
-  If you want to site updatable after publish add –u option to it.
- It is good to add –f option in order to override existing published site.
- Fore more help just type aspnet_compiler /?

Now let discuss about aspnet_merge.exe tool. This tool is introduce later and it is used to merge all assemblies that is located in bin directory of published site. When you published website project many assemblies are in bin directories depending upon your option.

- In aspnet_compiler if you add –fixednames option then it will generate single assembles for each page otherwise it is generated per directory (this is default for asp.net website project).

- Main disadvantage of different assembles either way is problem with reflection. You are not able to get control and page information located in another assemblies without assemblies loading programmatically.

- aspnet_merge.exe tool merge all aspnet generated assemblies to single assemblies.

Example :

1. set path=%programfiles%\Microsoft SDKs\Windows\v6.0A\bin
2. aspnet_merge c:\testcompile
   This will create single DLL ( assembly ) in bin directory.
3. To set generated assembly name use this.
    aspnet_merge –o Single.dll c:\testcompile.

Hope this will help you.

Please give your comment and advice on this.

Thursday, May 14, 2009

Important Tool For .NET

1. Managed Stack Explorer 
    This tool is used to monitor all managed process and their threads.
    You can download that tool at following location DownLoad

2. Process Explorer
    This tool is same as Taskmanager but it will give you more detail than taskmanager. Even this tool show you process in parent child relation so it is easy to manager.
     You can find more detail and download location at following link Process Explorer.

3. CLRProfiler
    This tool is specially designed for CLR ( Common language runtime ) . This tool give you more detail about Heap graph of your application.
For .Net Framework 1.1
For .NET Framework 2.0

Friday, April 17, 2009

WebService Authenticate against proxy server.

When proxy server configured for PC or in a network , if it require authentication to make certain request then you have to use following code.

Error: (407) Proxy Authentication Required.

Here i am taking example of SharePoint List service. I added reference of SharePoint List Service.


ListSerivce lst = new ListSerivce();
//Get Default Proxy Setting
IWebProxy proxy = System.Net.WebRequest.DefaultWebProxy;
// Authenticate using network credential. In My case i need authentication using windows account.
proxy.Credential = new System.Net.NetworkCredential(“username”,”password”,”domain”);
lst.Proxy = proxy;
// Make Call to WebService Method.

You can even find System.Net.WebProxy.GetDefaultProxy() return default proxy setting but it is deprecated to better to use WebRequest.DefaultWebProxy.

You can even configure your own webproxy

Lists lst = new Lists();
System.Net.WebProxy proxy = new WebProxy();
proxy.Address = new Uri("
http://proxy:8090");
proxy.Credentials = new NetworkCredential ("username", "password", "domain");
lst.Proxy = proxy;

In both case credential pass as NetworkCredential but you can use CredentialCache to pass other type of credential.

Please give comment on this. Also if you have any better idea please free give your suggestion.

Thursday, April 9, 2009

CrystalReport redistribution package

This is just a small information about Crystal Report redistribution package. You can fine different packages related to Visual Studio at following location

“<system drive>:\Program Files\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages”

At this location you can different directories that contains .exe or .msi related to Visual Studio 2008 installation.

Friday, April 3, 2009

WSE 3.0 Setting Tool For Visual Studio 2008

WSE 3.0 Setting Tool not available in VS 2008. Here i am explaining steps required to enable it in Visual Studio 2008.

1 . Download Following Tool
     WSE 3.0 Tools
2.  Install that MSI File.
     “Basically that installation is for Visual Studio 2005.”
3.  After installation you find one file at following location.
     C:\Documents and Settings\All Users\Application Data\Microsoft\MSEnvShared\Addins
      Here i assumed that your OS is installed at C:\.
4. At that location you find this file “WSESettingsVS3.Addin”.
5. Open file in Notepad , you find following XML content.   

  <HostApplication>
    <Name>Microsoft Visual Studio Macros</Name>
    <Version>8.0</Version>
  </HostApplication>
  <HostApplication>
    <Name>Microsoft Visual Studio</Name>
    <Version>8.0</Version>
  </HostApplication>

change it to

  <HostApplication>
    <Name>Microsoft Visual Studio Macros</Name>
    <Version>9.0</Version>
  </HostApplication>
  <HostApplication>
    <Name>Microsoft Visual Studio</Name>
    <Version>9.0</Version>
  </HostApplication>

save that file.
6. Open Visual Studio , Tools – > Options –> Environments

image

Add Following
“C:\Documents and Settings\All Users\Application Data\Microsoft\MSEnvShared\Addins”

(Note : In Image it displayed D:\ as my os is on D Drive.)

7. Close all instance of Visual Studio.

8. Open it again , create web service application . Now you can se that WSE 3.0 Setting option enable.

Thursday, April 2, 2009

How to get assembly name for registration ?

When assembly added into global assembly cache and there is need for adding that assembly to web.config assemblies section.

<compilation debug="false">
          <assemblies>
            <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            </assemblies>
</compilation>

Now there is need to add System.Web.Extensions assembly , for that you need assembly detail with its public key token to register.

Easiest way to get that detail is 

1. Go to run and type assembly.

run

it will open following window.

window1

2. Now select assembly , for example system.web.extensions , then go to edit menu and select option Copy display name as shown in following image.

window2

3. Now paste data.

image

you get all detail to register assembly. Enjoy… !

Thursday, March 5, 2009

Unauthorized (401.1) Exception calling Web Services in SharePoint (.Net Framework 3.5 )

After installing .NET Framework 3.5 sp1 following error may occur while making call to webservice. This thing mostly happen when you are trying to make webservice call using fully qualified domain name instead of IPAddress or Hostheader is used to map request on single port.

I found one strange thing in IIS Log that , for such request it is not sending authentication information to webservice request even though you pass it in NetworkCredential. One solution is to disable integrated authentication and use basic authentication. This will compromise with security but solve problem. Another solution that need to require registry changes. You can find it at following link with grate explanation.

http://www.crsw.com/mark/Lists/Posts/Post.aspx?ID=44
http://support.microsoft.com/default.aspx?scid=kb;EN-US;896861

SPAlert DynamicRecipient On Custom List

In SharePoint default. alert functionality available. You can subscribe Alert on List or ListItem using AlertMe action. But in certain situation you need to automize this alert. Like Alert automatically send to particular user even though he/she did not subscribe event.

There are two way to do . Create feature that receive ItemAdded or ItemUpdated Event , Find out user and email address , send email using SendEmail Functionality of SharePoint.

Another way is use DynamicRecipient property of SPAlert.

Sample List :

list

Here you can see that To Field is type of Person or Group. Send automatic email to user enter ‘To’ Field.

List Entry look Like (Edit View).

alert list entry

Note : UserName must have email id associated with him.SMTP also configured properly for site.

Now run following code against your site. (use console application).

SPSite site = new SPSite("http://yoursite");
SPWeb web = site.OpenWeb();
SPList lst = web.Lists["Alert Test"];
SPAlert alert = web.Alerts.Add();
alert.AlertFrequency = SPAlertFrequency.Immediate;
alert.AlertType = SPAlertType.List;
alert.EventType = SPEventType.All;
alert.DynamicRecipient = "To";
alert.List = lst;
alert.Status = SPAlertStatus.On;
alert.Title = “Auto Email Alert”;
alert.Filter = "<Query><IsNotNull><FieldRef Name='To'></FieldRef></IsNotNull></Query>";            
alert.Update();

You can even use FeatureReceiver to install/ Activate / deactivate this thing as a feature.