Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, December 7, 2014

Accessing the Network remote shared folder using C#

Accessing the Network remote shared folder:

System.Net.NetworkCredential readCredentials = new NetworkCredential(username, password);
using (new NetworkConnection(filepath, readCredentials))
{
   //Access here the files
}


Include the below class in your project
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Networks
{
    public class NetworkConnection : IDisposable
    {
        string _networkName;

        public NetworkConnection(string networkName,
            NetworkCredential credentials)
        {
            _networkName = networkName;

            var netResource = new NetResource()
            {
                Scope = ResourceScope.GlobalNetwork,
                ResourceType = ResourceType.Disk,
                DisplayType = ResourceDisplaytype.Share,
                RemoteName = networkName
            };

            var result = WNetAddConnection2(
                netResource,
                credentials.Password,
                credentials.UserName,
                0);

            if (result != 0)
            {
                throw new Win32Exception(result, "Error connecting to remote share");
            }
        }

        ~NetworkConnection()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            WNetCancelConnection2(_networkName, 0, true);
        }

        [DllImport("mpr.dll")]
        private static extern int WNetAddConnection2(NetResource netResource,
            string password, string username, int flags);

        [DllImport("mpr.dll")]
        private static extern int WNetCancelConnection2(string name, int flags,
            bool force);
    }

    [StructLayout(LayoutKind.Sequential)]
    public class NetResource
    {
        public ResourceScope Scope;
        public ResourceType ResourceType;
        public ResourceDisplaytype DisplayType;
        public int Usage;
        public string LocalName;
        public string RemoteName;
        public string Comment;
        public string Provider;
    }

    public enum ResourceScope : int
    {
        Connected = 1,
        GlobalNetwork,
        Remembered,
        Recent,
        Context
    };

    public enum ResourceType : int
    {
        Any = 0,
        Disk = 1,
        Print = 2,
        Reserved = 8,
    }

    public enum ResourceDisplaytype : int
    {
        Generic = 0x0,
        Domain = 0x01,
        Server = 0x02,
        Share = 0x03,
        File = 0x04,
        Group = 0x05,
        Network = 0x06,
        Root = 0x07,
        Shareadmin = 0x08,
        Directory = 0x09,
        Tree = 0x0a,
        Ndscontainer = 0x0b
    }
}



Wednesday, July 27, 2011

Tips on Exception Handling

1. Never do a 'catch exception and do nothing'. If you hide an exception, you will never know if the exception happened or not. Lot of developers uses this handy method to ignore non-significant errors. You should always try to avoid exceptions by checking all the error conditions programmatically. In any case, catching an exception and doing nothing is not allowed. In the worst case, you should log the exception and proceed.

2. In case of exceptions, give a friendly message to the user, but log the actual error with all possible details about the error, including the time it occurred, method and class name etc.

3. Always catch only the specific exception, not generic exception.
Good:
Private Sub ReadFromFile (fileName As String)
Try
// read from file.
catch (FileIOException ex)
// log error.
// re-throw exception depending on your case.
Throw
End Try
End Sub

Not Good:
Private Function ReadFromFile (fileName As String) As String
Try
// read from file.
Catch (Exception ex)
// Catching general exception is bad... we will never know whether
// it was a file error or some other error.
// Here you are hiding an exception.
// In this case no one will ever know that an exception happened.
Return String.Empty
End Try
End Function

4. No need to catch the general exception in all your methods. Leave it open and let the application crash. This will help you find most of the errors during development cycle. You can have an application level (thread level) error handler where you can handle all general exceptions. In case of an 'unexpected general error', this error handler should catch the exception and should log the error in addition to giving a friendly message to the user before closing the application, or allowing the user to 'ignore and proceed'.

5. When you re throw an exception, use the throw statement without specifying the original exception. This way, the original call stack is preserved.
Good:
Catch
// do whatever you want to handle the exception
throw
Not Good:
catch (Exception ex)
// do whatever you want to handle the exception
throw ex

6. Do not write try-catch in all your methods. Use it only if there is a possibility that a specific exception may occur and it cannot be prevented by any other means. For example, if you want to insert a record if it does not already exists in database, you should try to select record using the key. Some developers try to insert a record without checking if it already exists. If an exception occurs, they will assume that the record already exists. This is strictly not allowed. You should always explicitly check for errors rather than waiting for exceptions to occur. On the other hand, you should always use exception handlers while you communicate with external systems like network, hardware devices etc. Such systems are subject to failure anytime and error checking is not usually reliable. In those cases, you should use exception handlers and try to recover from error.

7.Do not write very large try-catch blocks. If required, write separate try-catch for each task you perform and enclose only the specific piece of code inside the try-catch. This will help you find which piece of code generated the exception and you can give specific error message to the user.

8. Write your own custom exception classes if required in your application. Do not derive your custom exceptions from the ApplicationException class. Instead, inherit from base class System.Exception.

Good bye Exceptional Handling

Saturday, August 7, 2010

How to open a dll file?

Recently I was working for a Tool and I was bit familiar and sure that existing dll files can be open to view their source code. I knew there are some tools which help you to do that.

Note: This is only possible if dll not obfuscated.

Obfuscation: It is a process that makes it difficult to reengineer the code. Obfuscating is a way to hide your assembly or EXE code from reflection.

Obfuscation simple meaning is making something difficult to read, understand and interpret. Obfuscation leads to doing something intentionally ambogious and confusing.

The same applies to .Net dll files. We know that .Net assemblies can be open to know what inside using reflector tools provided. So it is the need of individuals or personnel to protect their work that nobody copies or understand.The obfuscation alogorthims may use one of the following approaches.

  • Changing the variables, functions and method name.
  • Using Encoding
  • Using encyrption and dycryption techniques.

I will demonstrate this proces using a tool Red Gat’s .Net Reflector.You can download from here: http://www.red-gate.com/products/reflector/

Step1: Run the tool

Go to File->Open-> Browse the dll file to open. Here I have selected PM.dll file

Step2: Explore your methods, classes, properties to see the code

There are many tools availble like .Net Reflector 2.4 etc. You can download to look into your dll files.

I hope you enjoyed this, but at the same time you should also understand how can you protect your dll not to be open by anyone else if they values.

Sunday, August 1, 2010

How to read Windows Registry

Sometime we are required to read windows registry values in our applications. It is quite simple just 3-4 lines of code make you life easy while reading from registry.

Here we go.

I am sure you know how to Add Registry Data, lets take an example here.

Step1: Add a new Registry data, for that I will add connection string settings to my windows registry.

/*Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\MyApplication\DAL]

"ConnectionString"="Persist Security Info=False;User ID=UserId;Initial Catalog=MyDatabase; Password=Password;Data Source=MyServer"*/

This will add a Registry value of “String Value” to my Registry.

Step2: Step 2 includes how you read the value of the registry by passing the key name.

Here first of all we need to include the name space

using Microsoft.Win32

Here is the function that return the value:

public string GetConnectionString()

{

RegistryKey connkey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\MyApplication\DAL");

if (connkey != null)

{

object keyvalue = connkey.GetValue("ConnectionString");

return keyvalue.ToString();

}

throw new Exception("ConnectionString Connection string is not set in Windows Registry");

}

This way you get the connection string value set in the registry. I hope you got the way it needs to be achieved.

Thanks and please share your valuable comments.

Sunday, July 11, 2010

Reading Image or files like .xml,.txt as embedded resource from Assembly

As we requires images in our .Net application, There are many ways people make use of these resources to use .
Some of just read images or files from physical location, which seems more inconvenient than just reading from complied Assembly.
The metadata and all other information of the assembly is easily accessible. So it is easy to read it as embedded resource.
The only concern it increases the size of the assembly.
Reading an image from the assembly when the image is added to the project as
Embedded Resource,
I will explain here step by step.

1. Add an image to the solution




















2. Set the Build Action as "Embedded Resource".
3. Now build the project, the image will be complied into your project assembly which you can refer whenever required.
4. Make sure you add the following two namespaces
using System.Reflection; using System.IO;
4. Now the following lines of code can get you your complied image from the assembly.
Assembly assembly = Assembly.GetExecutingAssembly();
Stream streamObject = assembly.GetManifestResourceStream("WindowsFormsApplication1.images.Untitled.png");             Bitmap myImage= new Bitmap(streamObject);

Hope it works for you as expected.



Tuesday, April 6, 2010

Executing Client Side Script at Server Side

Guys, some time we need to call some javascript function from code behind. It is very easy to do with the following one line of code.
It can alert a message you required. For example a validation message.

1. Showing an alert message from server side
ScriptManager.RegisterStartupScript(this, typeof(Page), "test","alert('" + message + "');",true);


2. Opening a .aspx page in new window from server side using javascript.
Example code:




string jScript = "window.open('../Report/" + reportFileName + "','_blank','height=655,width=810,top=150,left=150,status=no,toolbar=no,menubar=no,location=no,scrollbars=no,resizable=yes,copyhistory=false')";

ScriptManager.RegisterStartupScript(this, typeof(Page), "Report",
jScript, true);

How to convert FileStream to MemoryStearm?

We do require sometime to convert a FileStream to MemoryStream. This is basically needed you need to download an existing file from the file system.
Steps:

//Open the File into file stream
FileStream fileStream = new FileStream(Server.MapPath(fileName), FileMode.Open, FileAccess.Read, FileShare.Read);

//Create and populate a memorystream with the contents of the filestream object

private MemoryStream StreamToMemory(FileStream fileStream)
{
MemoryStream memoryStream = new MemoryStream();
memoryStream.SetLength(fileStream.Length);
fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);


memoryStream.Flush();
fileStream.Close();
memoryStream.Close();
return memoryStream;


}
// Download the file at client end

byte[] byteArray = mstream.ToArray();
mstream.Flush();


mstream.Close();
Response.Clear();


Response.BinaryWrite(byteArray);
Response.AddHeader("Content-Disposition", "attachment; filename=QatargasTimesheet.xls");
Response.AddHeader("Content-Length", byteArray.Length.ToString());
Response.ContentType = "application/octet-stream";