Friday, March 9, 2018

Impersonation User in C#

Impersonation User in C#


Create a Class add below content

using System;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using Microsoft.Win32.SafeHandles;

namespace MyApplication
{
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public class Impersonation : IDisposable
    {
        private readonly SafeTokenHandle _handle;
        private readonly WindowsImpersonationContext _context;

        const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

        public Impersonation(string domain, string username, string password)
        {
            var ok = LogonUser(username, domain, password,
                           LOGON32_LOGON_NEW_CREDENTIALS, 0, out this._handle);
            if (!ok)
            {
                var errorCode = Marshal.GetLastWin32Error();
                throw new ApplicationException(string.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode));
            }

            this._context = WindowsIdentity.Impersonate(this._handle.DangerousGetHandle());
        }

        public void Dispose()
        {
            this._context.Dispose();
            this._handle.Dispose();
        }

        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

        public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
        {
            private SafeTokenHandle()
                : base(true) { }

            [DllImport("kernel32.dll")]
            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
            [SuppressUnmanagedCodeSecurity]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool CloseHandle(IntPtr handle);

            protected override bool ReleaseHandle()
            {
                return CloseHandle(handle);
            }
        }
    }
}
 
 
Add this in your whereever you want to impersonate user
 
using (new Impersonation(domain, username, password))
{
    // Add your logic
} 

Tuesday, April 4, 2017

batch run on remote using c#


Run cat file on remote using c#

1st Method:


2nd Method:

https://www.codeproject.com/kb/cs/remote_process_using_wmi_.aspx

3rd Method:

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "psexec \\my_remote_server -u my_domain\my_username -p " & password & " my_bat.bat"


Tuesday, January 3, 2017

Managed and Unmanaged Interoperability Recommendations


Managed and Unmanaged Interoperability Recommendations

https://msdn.microsoft.com/en-us/library/ms993883.aspx

Sunday, January 1, 2017

C++ Pointer and Adress example with C# class and Interfaces


C++ Pointer and Adress example with C# class and Interfaces

*   Pointer
&  Adress

example :

int Add(int *a,int *b)
{
    return a+b;
}

int main()
{
   printf("sum : " , Add(&a,&b);
}

Example with class and interfaces


Wednesday, December 28, 2016

Interview Questions



    


Interview Questions
 
Oops:
1)      Four pillars of oops
2)      Polymorphism
3)      When we go for abstract class and inheritance
4)      Types of constructors
5)      Static Constructor
6)      Default access Modifier of a class
7)      Difference between internal and protected internal
8)      Shadowing
C#
1)      Difference between ref and out keywords
2)      Difference between arrays and array list
3)      Solid Principles
4)      Difference between throw and throw ex
5)      Difference between Dispose() and Finalize()
6)      If we write return statement in try block when the finally block executed?
MVC
1)      Advantages of MVC over Asp.net
2)      Bundling and minification
3)      State management in MVC
4)      Temp data vs Viewag
5)      Peek and Keep
6)      Action Results
7)      Types of Filters
8)      Partial Views

Sql Server
1)      Difference between SP and Function
2)      Joins
3)      Triggers
4)      Cursers
5)      Indexes
6)      How do u perform Bulk insertions in sql(Using table type variables)
WCF
1)      Types of contracts
2)      Exception Handling in WCF
3)      Ways of hosting WCF Services
4)      Instance Modes
5)      What is service throttling
6)      Communication Modes


Tuesday, December 27, 2016

C++ class and interface example

C++ class and interface example

ClassLib::IMathLibPtr pCOMPtr;
    ////ClassLib::IMathLibPtr pCOMPtr;
    //// CreateInstance parameters
    //// e.g. CreateInstance (<namespace::CLSID_<ClassName>)
    HRESULT hRes =
        pCOMPtr.CreateInstance(ClassLib::CLSID_MathLib);

    if (hRes == S_OK)
    {
        BSTR str;
        pCOMPtr->ShowCOMDialog();
        //call .NET COM exported function ShowDialogResult ()
    }

    ClassLib::IDBConnectionPtr ptr1;

    HRESULT hres1 =
        ptr1.CreateInstance(ClassLib::CLSID_DBConnection);
    ClassLib::_DBConnection **ptr2 = S_OK;

    //ptr1 = &ptr2;
    if (hres1 == S_OK)
    {
        BSTR st4;
        BSTR  *str= S_OK,*str1= S_OK;       
            ptr1->ConnectionInfo(ptr2);
             ptr1->get_Userid(str);
             ptr1->get_Pasword(str1);
             str = &st4;
             SysFreeString(st4);
             std::cout << st4 << std::endl;
        //call .NET COM exported function ShowDialogResult ()
    }
    getchar();
    //CoUninitialize();

Thursday, December 22, 2016

Create a UnitTest in C++

Create a UnitTest in C++

Go to VS2010/2012/2013/2015

Solution of existing project - Add -> new Project ->

 

Add reference to project


 

  
Make sure your current project should tlb (your reference project settings) go to properties :



Unittesting project settings:


test results: