A Developer Journey who codes for fun

Daily Dose Of Code

  • Home
  • Dot.Net Basics
    • .Net Basics
      • CTS
      • CLS
      • CLR
      • Strong Vs Weak Ref
      • .Net Framework
      • What is Manifest
    • Memory Management
      • Garbage Collection 1
      • Garbage Collection 2
      • Circular Reference
  • C Sharp
    • Abstract Class in C#
    • Interfaces in C#
    • Value type by Val and By Ref
    • Var keyword
    • Null Coalescing Operator
    • Buit-in code snippets
  • OOPS
    • Abstraction and Encapsulation
    • Polymorphism
    • Inheritence
    • Aggregation
  • Threading
    • Delegates
      • Calling Delegate using Invoke, BeginInvoke
      • Multicast Delegate
      • Exception Handling in Multicast Delegate
      • Action
      • Predicate
      • Func
    • Synchronization
    • Thread Pool
    • Exception Handling
    • TPL
  • Design Pattern
    • Creational Patterns
      • Singleton Pattern
      • Factory Pattern
      • Abstract Factory Pattern
      • Prototype Pattern
      • Builder Pattern
    • Structural Patterns
      • Adapter Pattern
      • Bridge Pattern
      • Composite Pattern
      • Proxy Pattern
      • Facade Pattern
      • Decorator Pattern
      • Flyweight Pattern
    • Behavioral Patterns
      • Command Pattern
      • Interpreter Pattern
      • Iterator Pattern
      • Mediator Pattern
      • Memento Pattern
      • Observer Pattern
      • State Pattern
      • Strategy Pattern
      • Visitor Pattern
      • Chain Of Responsibility Pattern
      • Template Pattern
  • Data Structures
    • Generic List in C#
    • 2d array to 1d array
    • 3d arrayto 1d array
    • Linked List
      • Singly Linked List in C#
    • Queue
      • Dummy Data 1
    • Stack
      • Dummy Data 2
    • Tree
      • Dummy Data 3
    • Graph
      • Dummy Data 4
  • WCF
    • WCF Service using VS 2015
  • Scripts
    • Chrome Extensions
      • Create a Chrome Extension
      • Facebook autologout script
      • Gmail autologout script

Built-in Code Snippets (C#)

 Unknown     11:55 PM     No comments   

List of built in code snippets -

#if :- Creates a #if directive and a #endif directive.
#region :- Creates a #region directive and a #endregion directive.
~ :- Creates a destructor for the containing class.
checked :- Creates a checked block.
ctor :- Creates a constructor for the containing class.
cw :- Creates a call to Console.WriteLine.
for :- Creates a for loop.
forr :- Creates a for loop that decrements the loop variable after each iteration.
invoke :- Creates a block that safely invokes an event.
iterindex :- Creates a "named" iterator and indexer pair by using a nested class.
lock :- Creates a lock block.
mbox :- Creates a call to System.Windows.Forms.MessageBox.Show. You
may need to add a reference to System.Windows.Forms.dll.
prop :- Creates a automatic property
propg :- Creates a property declaration with only a "get" accessor and a backing field.
propfull : Creates a property with private field.
sim :- Creates a static int Main method declaration.
svm :- Creates a static void Main method declaration.
try :- Creates a try-catch block.
tryf :- Creates a try-finally block.
unsafe :- Creates an unsafe block.
unchecked :- Creates an unchecked block.

Happy to code.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

.Net Standard Date-Time-Format strings

 Unknown     11:13 PM     No comments   


Have a look on this image you will find very interesting i mentioned all the date-time format strings in this image.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Message-Box refreshing issue

 Unknown     10:34 PM     No comments   

I have used many message boxes in my current application but in some places where i used list box,list there when i move messagebox then the back screen is looks like everything is removing or cleaning nothing just refreshing issue, then i look and sort out by sinety testing like i used listView.BeginUpdate(); before dialog box check when i used after it then it works fine. because this method is used to update listview without any flicker and refreshing but i used before dialog check thats why i was facing that problem.

Happy to code...
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to collapse Environmental variables in a path using C# ?

 Unknown     4:39 AM     No comments   

Pass the path if there are environmental variables exist in the path then it will be collapsed into a valid path and return the valid path.
Constants :-
public const string PATH_SEPARATOR = @"\";
public const string ENVIROMENT_VARIABLE_FORMAT = "%{0}%";

public static string CollapseEnviromentVariables(string pathString)
{
string result = pathString;

if (string.IsNullOrEmpty(pathString) == false)
{
IDictionary environmentVariables = Environment.GetEnvironmentVariables();
Dictionary matchingEnv = new Dictionary();
bool isReplaceEnv = false;

foreach (DictionaryEntry environmentVariable in environmentVariables)
{
if ((pathString.Length >= ((string)environmentVariable.Value).Length) && (pathString.Contains((string)environmentVariable.Value)))
{
isReplaceEnv = false;

foreach (string matchingEnvEntry in matchingEnv.Keys)
{
if ((((string)matchingEnv[matchingEnvEntry]).Length <= ((string)environmentVariable.Value).Length) &&
((string)environmentVariable.Value).Contains((string)matchingEnv[matchingEnvEntry]))
{
matchingEnv.Remove(matchingEnvEntry);
matchingEnv.Add((string)environmentVariable.Key, (string)environmentVariable.Value);
isReplaceEnv = true;
break;
}
}

if (isReplaceEnv == false)
{
matchingEnv.Add((string)environmentVariable.Key, (string)environmentVariable.Value);
}
}
}

int matchingEnvIndex = 0;
int matchingEnvLength = 0;

foreach (string matchingEnvEntry in matchingEnv.Keys)
{
matchingEnvIndex = result.IndexOf(matchingEnv[matchingEnvEntry]);
matchingEnvLength = matchingEnv[matchingEnvEntry].Length;

//Replace environment variable only if environment variable value is enclosed by path seperators
//and matched value is found after replacing other variables.

if ((matchingEnvIndex > -1) &&
((matchingEnvIndex == 0) || (result[matchingEnvIndex - 1].ToString() == Constants.PATH_SEPARATOR)) &&
((matchingEnvIndex + matchingEnvLength == result.Length) || (result[matchingEnvIndex + matchingEnvLength].ToString() == Constants.PATH_SEPARATOR)))
{
result = result.Replace(matchingEnv[matchingEnvEntry], string.Format(Constants.ENVIROMENT_VARIABLE_FORMAT, matchingEnvEntry));
}
}
}
return result;
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to allign multiple strings using seperator in C# ?

 Unknown     4:20 AM     No comments   

Constant file.public const char SYMBOL_SPACE_CHARACTER = ' ';

public static List AlignText(string[] strings, char seperator)
{
List formattedStringList = new List();
List ListOfCommaSeperatedStringsInLine = new List();
string[] commaSeperatedStringsArray = null;
List maxColumnWidthArray = new List();

//split strings into list of comma seperated array of strings and calculate maximum length of string array.
foreach (string str in strings)
{
commaSeperatedStringsArray = str.Split(seperator);

//remove all trailing and leading spaces.
for (int index = 0; index < commaSeperatedStringsArray.Length; ++index)
{
commaSeperatedStringsArray[index] = commaSeperatedStringsArray[index].Trim();

//initialize maximum characters in each column.
if (maxColumnWidthArray.Count > index)
{
maxColumnWidthArray[index] = (maxColumnWidthArray[index] < commaSeperatedStringsArray[index].Length) ? commaSeperatedStringsArray[index].Length : maxColumnWidthArray[index];
}
else
{
maxColumnWidthArray.Add(commaSeperatedStringsArray[index].Length);
}
}

ListOfCommaSeperatedStringsInLine.Add(commaSeperatedStringsArray);
}

StringBuilder formattedString = new StringBuilder();
int accumlativeMaxLength = 0;
int pad = 0;

//Insert spaces to align text and append in single line text.
foreach (string[] stringsInLine in ListOfCommaSeperatedStringsInLine)
{
formattedString.Append(stringsInLine[0]);
accumlativeMaxLength = maxColumnWidthArray[0];

for (int index = 1; index < maxColumnWidthArray.Count; ++index)
{
if (stringsInLine.Length > index)
{
pad = accumlativeMaxLength - formattedString.Length;
formattedString.Append(seperator);
formattedString.Append(Constants.SYMBOL_SPACE_CHARACTER, pad);

if (IsNumeric(stringsInLine[index]))
{
formattedString.Append(Constants.SYMBOL_SPACE_CHARACTER, maxColumnWidthArray[index] - stringsInLine[index].Length);
}

formattedString.Append(stringsInLine[index]);
accumlativeMaxLength += maxColumnWidthArray[index] + 1;
}
}

formattedStringList.Add(formattedString.ToString());
formattedString.Length = 0;
}

return formattedStringList;
}
This is very useful method when you have to align certain strings and there is a seperator then this method will allign all the lines, just pass the array of strings and a seperator.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to check invalid characters in path using C#

 Unknown     3:26 AM     10 comments   

If you create a new folder then there are some characters which are not allowed and any thing in which user have rights to create path then firstly check the invalid characters otherwise your application or program will through an exception.

Pass the path or string for which you have to check.
public static bool CheckInvalidCharacters(string path)
{
bool invalidCharacters = false;

if (string.IsNullOrEmpty(path) == false)
{
char[] invalidChars = Path.GetInvalidFileNameChars();

foreach (char invalidChar in invalidChars)
{
if (path.Contains(invalidChar.ToString()))
{
invalidCharacters = true;
break;
}
}
}
return invalidCharacters;
}
This will return a bool variable if path or string contains invalid characters then it will return true else false.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Delegates in C#

 Unknown     9:58 PM     No comments   

Event - Delegates are the key feature of C#,You can say heart of C#.Look on a example :- Suppose if you have two forms and there is no communication between those even you can't create object to access then how will you send some information.In this tutorial i will teach you how to handle and play with delegates to proper communication.

Suppose you have to pass the multiple file paths to different forms and they are in different solutions or different forms :-
Step.1 :-
Make a class which will contain all the file path like this :-

public class FileOpenEventArgs : EventArgs
{
#region Private Fields

private string [] _filePath;

#endregion

#region properties

///
/// Sets/Gets the path of files.
///

public string [] FilePath
{
get
{
return _filePath;
}
set
{
_filePath = value;
}
}

#endregion
}

step.2 :- Now come to form from you have to pass the information
Declare a delegate and event like :-

public delegate void FileOpenHandler(object sender, FileOpenEventArgs e);
public event FileOpenHandler FileOpen;

step.3 :- Now do the operation suppose you have to send the file name on drag-drop or on a mouse click or on mouse hover any event then create the object of the class and set the file names and then pass like in this way :-
I have used on drag-drop so get the file names in this way :-
string[] files = (string[])drgevent.Data.GetData(DataFormats.FileDrop);
or you can do other way to get the file names.
Create the object and set the file names.
FileOpenEventArgs fileOpen = new FileOpenEventArgs();
fileOpen.FilePath = files;
OnFilesOpen(this, fileOpen);

Handles FileOpen event.
protected void OnFilesOpen(object sender, FileOpenEventArgs e)
{
if (FileOpen != null)
{
FileOpen(this, e);
}
}

Step.4 :- Now handle your event on the form where you can create the object of this form or you can handle the event here too but I handled the event on onother solution like :-
private solution.explorer lightView;
then again create delegate and event like:-
public delegate void FileOpenHandler(object sender, FileDataOpenEventArgs e);
public event FileOpenHandler FileOpen;
Now handles the event :-
lightView.FileOpen += new solution.explorer.FileOpenHandler(lightView_FileOpen);

void lightView_FileOpen(object sender, FileOpenEventArgs e)
{
string [] fileData = e.FilePath;
FileDataOpenEventArgs fileDataOpenEventArgs = new FileDataOpenEventArgs(fileData);
OnFilesOpen(fileDataOpenEventArgs);
}

Handle protected method :-
protected void OnFilesOpen(FileDataOpenEventArgs e)
{
if (FileOpen != null)
{
FileOpen(this, e);
}
}
now create the event where you have to open or do something for files :-
create the instance of above class where you handle your event.


private lightView_lightViewPanel = new lightView();
_lightViewPanel.FileOpen += new lightView.FileOpenHandler(_lightViewPanel_FileOpen);

private void _lightViewPanel_FileOpen(object sender, FileDataOpenEventArgs e)
{
if (e != null)
{
now play with your path accesss e.FilePath property of this event you will get path.
}
}

Happy to code.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Generics in C#

 Unknown     5:36 AM     No comments   

Hi everyone..in .net 2.0 we do programming in a very smarter way Generics is the example like if we are using minimum finction to find minimum between two numbers they may be integer,string,object and may be some other data types.
Consider the following code :-
Returns minimum between two integers.
int Min( int a, int b )
{
if (a < b) return a;
else return b;
}

let suppose you have objects or string then this will not work.To use this code, we need a different version of Min for each type of parameter we want to compare then developers think to use in the folllowing manner :-
Returns minimum between two objects.
object Min( object a, object b )
{
if (a < b) return a;
else return b;
}

But less than operator (<) is not defined for the generic object type.So we need to use a coomon interface to use ex:-Icomparable. like in the following manner :-

IComparable Min( IComparable a, IComparable b )
{
if (a.CompareTo( b ) < 0) return a;
else return b;
}
By this way problem has been solved but now there is a big issue.A caller of Min that passes two integers should make a type conversion from IComparable to int and may be it gives an exception. like :-

int a = 7, b = 16
int c = (int) Min( a, b );
but .net 2.0 solved the issue using Generics.


This is the generic version of MIN method.
T Min( T a, T b ) where T : IComparable
{
if (a.CompareTo( b ) < 0) return a;
else return b;
}

Now you can call like in this manner :-
int a = 7 b = 16;
int c = Min( a, b );

Happy to code.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Singleton Pattern

 Unknown     10:08 PM     4 comments   

Singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is very useful when only there is a need of single object which handles all the actions across the system.This pattern restrict the instantiation to a certain number of objects and this concept is to generalize the systems to operate more efficiently when only one object exists.
Example :-
The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation

Implementation of Singleton pattern :-
///
/// Thread-safe singleton example without using locks
///

public sealed class SingletonClass
{
private static readonly SingletonClass singletonInstance = new SingletonClass();

// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static SingletonClass()
{
}

private SingletonClass()
{
}

///
/// The public Instance property to use
///

public static SingletonClass SingletonInstance
{
get { return singletonInstance ; }
}
}
Happy to code...
Hiii...One more example to clear singleton approach :-
I have implement progress bar for ma current application so i am giving some reference here:-
#region Private Fields

private static StatusProgressBar _instance = null;

#endregion

#region Constructor

private StatusProgressBar()
{
this.Style = ProgressBarStyle.Blocks;
this.Step = 1;
}

#endregion

#region Properties

///
/// Get Singleton instance of progressBar
///

public static StatusProgressBar Instance
{
get
{
if (_instance == null)
{
_instance = new StatusProgressBar();
}

return _instance;
}
}

#endregion
Made the above class as public and access it suppose class name is StatusProgressBar

StatusProgressBar.Instance.PerformStep();
then if instance is already running then it will return that instance otherwise will return a new instance.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Custom Number Formats.

 Unknown     12:30 AM     No comments   


I found something very interesting regarding number formats.have a look on the image
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

What is LINQ?

 Unknown     3:03 AM     No comments   

■ LINQ is a uniform programming model for any kind of data. LINQ enables you to query
and manipulate data with a consistent model that is independent from data sources.
■ LINQ is just another tool for embedding SQL queries into code.
■ LINQ is yet another data abstraction layer.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Remove special characters from string ?

 Unknown     3:39 AM     No comments   

public override string ToString()
{
string specialCharacters = "~!@#$%^&*<()+=`',.?>/\\\"";
string[] stringAfterRemovingSpecialCharacters= displayText.Split(specialCharacters .ToCharArray());
return string.Concat(stringAfterRemovingSpecialCharacters);
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

File/Folder is being used by another process Error?

 Unknown     2:14 AM     No comments   

Hi Friends..
Resolved Error - File/Folder is being used by another process

As i discussed in my current project i made a self explorer.exe so i accessed all the folders,files .i am doing same behaviour as lioke window explorer.exe. But I was facing a error This file/folder is being used by another process and all that and i face all these errors when i rename,delete,move,copy,drag-drop.

Solution :- I add folders runtime and updation is all as real time.so I used shell com object and make tree using shell namespace like :-

node is treeNode of tree.

Shell32.FolderItem folderItem = (Shell32.FolderItem)node.Tag.FolderItem;
Shell32.Folder folder = (Shell32.Folder)folderItem.GetFolder;


then iterate thorugh foreach and used break statement because i add a dummynode in each node who have folders and when i expand that node then delete the dummynode and create the nodes for that treenode beacuase of efficiency.So on creating dummyNode i used foreach statement like :-

bool hasFolders = false;
foreach (Shell32.FolderItem item in folder.Items())
{
if (item.IsFileSystem && item.IsFolder && !item.IsBrowsable)
{
hasFolders = true;
break;
}
}
if (hasFolders)
{
TreeNode newTreeNode = new TreeNode();
newTreeNode.Tag = STRING_DUMMY_TREENODE;
treeNode.Nodes.Add(newTreeNode);
}
so this foreach actually its an iterator so when i use break statement so tis break from the loop but still it holds the object and shell thinks its used by some other program and all so dont use foreach if you using break statement like this :-

Shell32.FolderItems items = folder.Items();
for (int itemIndex = 0; itemIndex < items.Count; itemIndex++)
{
Shell32.FolderItem item = items.Item(itemIndex);
if (item.IsFileSystem && item.IsFolder && !item.IsBrowsable)
{
hasFolders = true;
break;
}
}
and now as above you will never face the error like file/folder is being used by another process so in your application if you are facing then firstly check it out and make sure you are not using any iterator.

Happy to code.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

List with ForEach

 Unknown     3:49 AM     No comments   

List Names = new List();
Names.Add("Saurabh");
Names.Add("Somu");
Names.Add("Sandy");

//For every item in the list, say you want to append the last name "Somu" and print it

//WITHOUT ForEach()
foreach (string name in Names)
{
Console.WriteLine(name + " Somu");
}

//WITH ForEach
Names.ForEach(delegate(string name) { Console.WriteLine( name + " Somu" ); });
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Yield Keyword

 Unknown     2:03 AM     No comments   

class Program
{
static void Main(string[] args)
{
List Names = new List();
Names.Add("saurabh");
Names.Add("somu");
Names.Add("vivek");

foreach (string item in GetNames(Names))
{
Console.WriteLine(item);
}
}

public static IEnumerable GetNames(List Names)
{
for (int i = 0; i < Names.Count; i++)
{
yield return Names[i];
}
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

?? keyword

 Unknown     1:47 AM     No comments   

?? keyword is used to check null.

Example using if-else statement:-
if (tempString == null)
{
x = "Null string";
}
else
{
x = tempString ;
}
Console.WriteLine(x);

Example using ?? Keyword

string tempString = null;
string x = tempString ?? "Null string";
Console.WriteLine(x); //Prints "Null string"
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Problem about Instances...

 Unknown     7:56 PM     No comments   

Hii..Frends this is very genuine problem.
Functionality :-When i was developing Window Explorer control for my application then i just stuck in a problem I had three instances of window - explorer.. One is as similar as Window file explorer by which you can drag drop files and that will open in any editor.(We had given additional functionality like to show INF,INI,BAK and ORG files) and other two are as same as Window File - Folder Explorer like in left hand side Folder Explorer(TreeView) and Right hand side ListView which shows all the files with size,Modified date and type of file.and you can sort using coloumn click.(Like Window File detail view in windows) and the third one which is just below of this one has same feature but the root node of this tree will be a path where ever we want to show we said this is destination view and above one is source view .You can drag files from Source listView to Destination TreeView and ListView both and that will copy the whole directory at that path physically and You can add folder from source treeview to destination treeView and we can move folder and files from destination listView to destination treeview.We given the special functionality like we can add new folder,delete the folder and rename the folder.That all the features we have given in all the controls.

Problem:-
I have only one control with three instances if i m doing some changes from application and rename and bla bla..n all the tree view has opened a same path then i want to make all the controls as real time like if we add a folder of some path then in all the controls will be the same...So i need some notification then i know the methods about shell if we add , delete and rename from shell then shell will send a notification to application and then WndProc method will send the notification to all the instances and to invoke shell methods i have already make a post related to How to Copy,Delete,Rename from Shell.

If you add delete , add folder,media and other devices and rename and all other changes then how system invokes the message and will reflect real time.

Enjoy the Code..
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to Copy,Delete,Rename and Move files and create new directory using Shell32 in C#?

 Unknown     2:41 AM     No comments   

#region Enum
public enum FileOp
{
Move = 0x0001,
Copy = 0x0002,
Delete = 0x0003,
Rename = 0x0004
}

[Flags]
public enum FileOpFlags
{
MultiDestFiles = 0x0001,
ConfirmMouse = 0x0002,
Silent = 0x0004,
RenameCollision = 0x0008,
NoConfirmation = 0x0010,
WantMappingHandle = 0x0020,
AllowUndo = 0x0040,
FilesOnly = 0x0080,
SimpleProgress = 0x0100,
NoConfirmMkDir = 0x0200,
NoErrorUI = 0x0400,
NoCopySecurityAttributes = 0x0800,
NoRecursion = 0x1000,
NoConnectedElements = 0x2000,
WantNukeWarning = 0x4000,
NoRecursiveReparse = 0x8000
}

#endregion

#region Structure
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
public struct SHFILEOPSTRUCT
{
public IntPtr hwnd;
[MarshalAs(UnmanagedType.U4)]
public int wFunc;
public string pFrom;
public string pTo;
public short fFlags;
[MarshalAs(UnmanagedType.Bool)]
public bool fAnyOperationsAborted;
public IntPtr hNameMappings;
public string lpszProgressTitle;
}
#endregion

Import a shell method to copy file from one location to another,delete file,copy file and rename files and folders.
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
public static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);

Import a shell method to create a new directory.
[DllImport("shell32.dll")]
public static extern int SHCreateDirectoryEx(IntPtr hwnd, string pszPath, IntPtr psa);

To create a new folder :
private const string NULL_STRING = "\0";
newFolderPath is the path where you want to create your directory.
SHCreateDirectoryEx(this.Handle, newFolderPath + NULL_STRING, IntPtr.Zero);

To do all the file operation like move , copy ,delete and rename :-
public bool FileOperation(string sourceFileName, string destinationFileName, FileOp fileOp)
{
bool success = true;
try
{
SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT();
shf.wFunc = (int)fileOp;
shf.fFlags = (short)FileOpFlags.AllowUndo | (short)FileOpFlags.NoConfirmation;
if(!string.IsNullOrEmpty(sourceFileName))
{
shf.pFrom = sourceFileName + NULL_STRING;
}
if(!string.IsNullOrEmpty(destinationFileName))
{
shf.pTo = destinationFileName + NULL_STRING;
}
int result = SHFileOperation(ref shf);

if (result != 0)
{
success = false;
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, Application.ProductName, MessageBoxButtons.OK);
}
return success;
}

How to call this method :-
To Delete the file or folder.
FileOperation(newFolderPath, string.Empty, FileOp.Delete);

To Copy the File or Folder.
FileOperation(sourcePath, destinationPath, FileOp.Move);

To Rename the file or Folder.
FileOperation(sourcePath, destinationPath, FileOp.Rename);
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to create FilePropertyDialog like Windows in C#?

 Unknown     7:45 AM     No comments   

#region Enum
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SHELLEXECUTEINFO
{
public int cbSize;
public uint fMask;
public IntPtr hwnd;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpVerb;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpFile;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpParameters;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpDirectory;
public int nShow;
public IntPtr hInstApp;
public IntPtr lpIDList;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpClass;
public IntPtr hkeyClass;
public uint dwHotKey;
public IntPtr hIcon;
public IntPtr hProcess;
}
#endregion

private const int SW_SHOW = 5;
private const uint SEE_MASK_INVOKEIDLIST = 12;

[DllImport("shell32.dll")]
static extern bool ShellExecuteEx(ref SHELLEXECUTEINFO lpExecInfo);

Pass the file name for which you want to see the file property dialog.
public static void ShowFileProperties(string Filename)
{
SHELLEXECUTEINFO shellInfo = new SHELLEXECUTEINFO();
shellInfo .cbSize = System.Runtime.InteropServices.Marshal.SizeOf(info);
shellInfo .lpVerb = "properties";
shellInfo .lpFile = Filename;
shellInfo .nShow = SW_SHOW;
shellInfo .fMask = SEE_MASK_INVOKEIDLIST;
ShellExecuteEx(ref info);
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to stop multiple instances running of my application using C# ?

 Unknown     1:47 AM     No comments   

public static void Main()
{
bool isNew = false;
Mutex mtx = new Mutex( true, "MyApp_Mutex", out isNew );
if( !isNew )
{
MessageBox.Show( "MyApp is already running." );
return;
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Older Posts Home

About The Author

Unknown
View my complete profile

Total Pageviews

Popular Posts

  • Clr - Common Language Runtime
    .Net framework provides a run time environment - CLR. Common language runtime takes the IL code from the compiler( language specific) and p...
  • Predicate delegate in C#
    Hello Everyone, In the article we will talk about Predicate delegate. Predicate is also a delegate which encapsulate a method that takes...
  • Auto logout chrome extension for Gmail
    Hello Friends, In the last article we learned to create a sample chrome extension. Here we are going to create auto logout Gmail script as...
  • .Net Framework overview
    Hello friends : Here i am writing my first article on .Net framework anyways....So the question is What is .Net Framework ? The .Net fram...
  • Nagarro Placement Papers..
    Ques.1 :- Seat Reservation prog for the theatre. Write a function for seat allocation for the movie tickets. Total no of seats available are...
  • C code to Check the string has valid identifier or not in.
    #include #include #include char keyword[][10]={"auto","break","case","char","const","...
  • What does it mean by disconnected data access architecture of ADO.Net?
    ADO.Net introduces the concept of disconnected data architecture. In traditional data access components, you make a connection to the databa...
  • Calling the Delegates using Invoke(), BeginInvoke() and DynamicInvoke() ?
    Hello Guys, So in the last article we talked about What is delegate and how can we create a delegate. In this article we will discuss w...
  • Delegates in C Sharp
    A Delegate is a type variable that holds the reference to a method. Delegates are similar to Pointer to functions in C and C++ When we...
  • Garbage Collection - Automatic memory management
    While thinking of this question few things are coming in my mind ~ How .Net reclaims objects and memory used by an application ? So the ans...

Blog Archive

  • ▼  2016 (4)
    • ▼  September (2)
      • ▼  Sep 03 (2)
        • Auto logout chrome extension for Gmail
        • Auto logout chrome extension for facebook
    • ►  August (1)
      • ►  Aug 28 (1)
    • ►  April (1)
      • ►  Apr 24 (1)
  • ►  2015 (12)
    • ►  September (10)
      • ►  Sep 30 (1)
      • ►  Sep 29 (1)
      • ►  Sep 28 (1)
      • ►  Sep 27 (2)
      • ►  Sep 26 (3)
      • ►  Sep 20 (1)
      • ►  Sep 19 (1)
    • ►  August (1)
      • ►  Aug 16 (1)
    • ►  March (1)
      • ►  Mar 31 (1)
  • ►  2013 (10)
    • ►  June (1)
      • ►  Jun 16 (1)
    • ►  April (1)
      • ►  Apr 21 (1)
    • ►  February (8)
      • ►  Feb 18 (3)
      • ►  Feb 17 (2)
      • ►  Feb 16 (2)
      • ►  Feb 15 (1)
  • ►  2012 (1)
    • ►  May (1)
      • ►  May 27 (1)
  • ►  2010 (22)
    • ►  October (14)
      • ►  Oct 21 (1)
      • ►  Oct 06 (12)
      • ►  Oct 04 (1)
    • ►  April (2)
      • ►  Apr 22 (1)
      • ►  Apr 16 (1)
    • ►  March (1)
      • ►  Mar 30 (1)
    • ►  January (5)
      • ►  Jan 08 (3)
      • ►  Jan 01 (2)
  • ►  2009 (110)
    • ►  December (8)
      • ►  Dec 18 (2)
      • ►  Dec 05 (1)
      • ►  Dec 04 (5)
    • ►  November (1)
      • ►  Nov 27 (1)
    • ►  October (14)
      • ►  Oct 09 (4)
      • ►  Oct 07 (1)
      • ►  Oct 06 (3)
      • ►  Oct 05 (3)
      • ►  Oct 01 (3)
    • ►  September (17)
      • ►  Sep 30 (1)
      • ►  Sep 29 (1)
      • ►  Sep 28 (1)
      • ►  Sep 25 (1)
      • ►  Sep 24 (1)
      • ►  Sep 17 (2)
      • ►  Sep 15 (3)
      • ►  Sep 11 (2)
      • ►  Sep 09 (3)
      • ►  Sep 08 (2)
    • ►  August (31)
      • ►  Aug 31 (1)
      • ►  Aug 27 (3)
      • ►  Aug 26 (1)
      • ►  Aug 25 (2)
      • ►  Aug 24 (1)
      • ►  Aug 22 (2)
      • ►  Aug 21 (3)
      • ►  Aug 20 (2)
      • ►  Aug 19 (3)
      • ►  Aug 18 (1)
      • ►  Aug 16 (1)
      • ►  Aug 12 (2)
      • ►  Aug 11 (1)
      • ►  Aug 10 (3)
      • ►  Aug 07 (4)
      • ►  Aug 06 (1)
    • ►  July (24)
      • ►  Jul 25 (4)
      • ►  Jul 24 (20)
    • ►  April (15)
      • ►  Apr 10 (3)
      • ►  Apr 07 (9)
      • ►  Apr 06 (3)

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments
copyright @ TechGiant 2015. Powered by Blogger.

Disclaimer

This is my personal blog and i write articles on .Net, WPF, C#, OOPS, Threading and other .Net technologies. This is not related to any of my employer and organizations. This is the result of my personal interest.

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Followers

Copyright © A Developer Journey who codes for fun | Powered by Blogger
Design by Hardeep Asrani | Blogger Theme by NewBloggerThemes.com