Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all 8156 articles
Browse latest View live

How to add a DLL Dynamically in c#

$
0
0

Hi,

There is a Sage DLL which I have used in my c# windows application.

The problem is that, whenever a new update comes for Sage, the DLL name will be changed.

Like sgEngine230.dll  or sgEngine240.dll

So Whenever there is update, we have to modify the c# code which is using this dll, and deploy the code once again.

I would like to know if there is any way to load this DLL at runtime, so that I dont have to modify the code whenever there is new DLL available.

Thanks in advance.

RC


Building C# Class library project .Net Framework 4.0 from VS2017

$
0
0

Hi,

I have a C# Class Library "CL01" build against .Net Framework 4.0 using Visual Studio 2017. I am referencing the "CL01" assembly to a another class (Say "CL02") library project configured to Target Framework 4.0.
When I build CL02 from Visual Studio 2017, I am betting the bellow warning

The primary reference "CL01, Version=1.0.0.0, Culture=neutral, processorArchitecture=x86"

could not be resolved because it was built against the ".NETFramework,Version=v4.6.1" framework.

This is a higher version than the currently targeted framework ".NETFramework,Version=v4.0"

Actually both the C# class library projects are configured to Target Framework 4.0. But when I build the CL02, the build error says, The CL01 is build against the .Net Framework v4.6.1.
Is the anyway to resolve this issue ?



Gops

The type or namespace name 'SqlDataAdapter' could not be found

$
0
0

Hi every one

The type or namespace name 'SqlDataAdapter' could not be found for my asp.net project. i use .net standard 

and the version is 4.5.2 and visual studio 2017. this issue seems related to the compatibility? 

also i found this issue from github.

please help me.

thanks.


Events, EventHanders and GenericAttributeProfile notifications (BLE)

$
0
0

Hello all, 

 I am using the GenericAttributeProfile to communicate with a Bluetooth (Low Energy) radio. A problem I'm seeing is that when the data is received, it is not necessarily in the order sent. I believe the data is arriving at the receiver in order, but due to the the speed the data comes in, and how events are implemented, the data is evaluated out of order. Is my thinking correct? 

The mechanism is to subscribe to a GattCharateristic object's ValueChanged event. Every time data is received (a notification) the EventHandler will be invoked. Unfortunately, when I log my data to console, it seems to be produced out of order. 

private GattCharacteristic characteristic;

...

characteristic.ValueChanged += Characteristic_ValueChanged


So if I send 10 packets of data across. This will cause 10 events, and hence 10 eventHandlers to be invoked. Can these events/eventHandlers be invoked in any order? Do not conflate what I just said with what was ask here: this http://stackoverflow.com/questions/1645478/order-of-event-handler-execution

I only  have 1 eventHandler per event. The problem is that when events occur, my eventHandler logs the data to console, and I see that it is out of order sometimes. 

So to consolidate, my questions are

1. Are events handled in the order received?

2. Is there another mechanism for receiving notifications for Bluetooth Low Energy? 

Please let me know if you do not understand my question. 

Many Thanks

Thomas


2010: Q6700 3GHz; 6GB DDRII; ~ 2.7TB internal; ATI RAEDON 5770 1GB @ Stock; Elixir Keyboard; Gigabyte GM-M6800; 2 x E173FPf 2005: 2GIG RAM, 3.6Ghz P4, 2 x 200gb SATA HD 8mb cache, 256mb 9950 ATI RADEON,19" LCD Core i7 3.2GHz, 6GB DDRIII, ASUS 512MB EN8800GT

AES_Encryption in MySQL, Decryption in C#

$
0
0

Review this

http://stackoverflow.com/questions/7712372/aes-encryption-in-mysql-decryption-in-c-net

Later on discussion i decided to move validation by instead of manually decrypting i used query to Decrypt the data

 

i.e

SELECT     AES_DECRYPT(Component, 'admin123') AS `Component`FROM         intab

it works fine as i expect .


on the method i written as

public DataTable GetAllItems()
    {try
        {
            _connection.Open();var ds = new DataSet();
            _adapter = new MySqlDataAdapter("SELECT AES_DECRYPT(Component, 'admin123') AS Component  FROM  intab", _connection);
            _adapter.Fill(ds);
            _connection.Close();return ds.Tables[0];
        }catch (Exception e)
        {
            _connection.Close();
            Debug.WriteLine(e.Message);returnnull;
        }
    }


it works fine but return binary data only. (i.e Byte array)

 

Idk what i made a mistake review and comment the code

 

Getting to Know the Current Application Running and in Use in the Foreground and the Final Screen time for all the applications used during 24 hours

$
0
0

Hello, 

I am not sure if this Question fits here,But I am developing a user productivity suite and wanted to know is there any official application from the Microsoft which can tell which application is currently running and is in use.For example currently it should report as Internet Explorer.Also at the end it should tell me the amount of time I have spent in each application at any time.

Its like  screen time feature in IOS phones.

Is there any Windows API available for it , which I can use?

Kindly suggest any application currently which is mostly used.

If this Question doesn't fit in this forum , kindly move it to an appropriate forum and please let me know the link.

Eagerly Looking for the reply !

Thanks and Regards,

Rp

LISTVIEW GROUPS

$
0
0

I have a System.Windows.Forms.ListView with View = Detail and SelectFullRow. I use grouping.

Consider the following scenario:
...
item A
Group Header
item B
...

Let item A be selected; when I press the down arrow selection passes to item B as expected, however the Group Header is highlighted by a dotted rectangle like the glyph indicating focus; pressing the down arrow again, the rectangle disappears but selection remains on item B. The same happens if now I press the up button.

As a result, scrolling through the list shows an annoying hysteresis when crossing the groups.

Have I missed any setting?




Does WEC7 webserver support SVG files

$
0
0

All;

I am looking to see if the webserver in WEC7 embedded supports the use of .SVG files? If so, how is it enabled in visual studio platform builder? Are there any examples of use in a web screen?

Thanks, Jeff


HTMLHelp API - ShowHelp does not work properly after installing KB4471329-x64 or KB4462919

$
0
0

Hello,

Not sure what the best forum is for a Win32 API/KB breakage is, but starting here.

Recently KB4471329 was installed on our client computers as part of regular updates and compliance.  When this KB is applied to our computers, it changes the way Help.ShowHelp works.  Previously we were able to call this API in response to an F1 press and ask the API to show a specific CHM book that was part of a larger set of books and display a specific page.  This allowed the software to launch help to a specific page, but allow the user to browse to any other book in our integrated setup.

We use the form:

      Help.ShowHelp(this, @"../../../HelpFiles/Master.chm", @"SiteA.chm::/SiteA.htm");

After install of this KB, the behavior is changed.  The help book is properly launched.  The contents listing (tree view) shows the help topics on the left, but the main view shows a blank page with the following text:

 "This page can’t be displayed.  Make sure the web address //ieframe.dll/dnserrordiagoff.htm# ..."

If we remove the KB from the machine, then F1 works properly again and the content of the page is shown in the right hand view.

We've created a sample program that illustrates this and would like to provide it.  Using it, you can see the effect before and after installing KB4471329.  Your test machine needs to have KB4471329 (or equivalent) installed to see the problem.  Remove it to see the problem undone.  What is the best way to provide the sample?

We are hoping to bring this to the attention of Microsoft so that an updated patch could be created.

We do not see any workaround in the code that we can do to keep the overall integrated book displaying.

Lastly, here is a related posting that seems to point out the same issue:

https://developercommunity.visualstudio.com/content/problem/364201/showhelp-with-double-colon-does-not-workkb4462919.html

Thanks,


Brian R.

Header content moved to the previous page while compare with DOC and DOCX format documents.

$
0
0

Hi, While viewing this attached“HeadingsShiftingUpwards.doc” document, “Notification History” text present in 5<sup>th</sup> page. Same text moved to the 4<sup>th</sup> page after resave the same document as DOCX format(HeadingsShiftingUpwards_MS.docx) by using Microsoft Word application as like attached screenshot.

I have attached Word documents and screenshot for your references.
 
Can anyone help on this, what is exact behavior difference exist in these documents (DOC and DOCX formats). Is there any known limitation?


Thanks,
Sivasubramani.

شحن فريون ثلاجات هيتاشي & 0235695244 &صيانه هيتاشي & 01225025360&العبور

FileUpload class and FTP User

$
0
0

Dear .NET Experts,

I have looked at the definition for the file upload class (https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.fileupload?view=netframework-4.7.2) and wonder now,

where do I put the user information for the user (ftp) that has the right to the path directory?

Unmanaged Resources Created By Authz

$
0
0
I've been working on application where I need to calculate Effective access of user of specific shared File or Folder and I've successfully achieved it by using the Authz.dll . The problem I'm facing now is related to unmanaged resources created by authz.dll I've tried everything to clear those resources but I'm failed to do so. I used the methods provided by dll to clear resources but still unable to clear them I'm using these methods to clear the memory.

if (AccessReply != IntPtr.Zero) flag = AuthzFreeHandle(AccessReply); if (hManager != IntPtr.Zero) flag = AuthzFreeResourceManager(hManager); if (pClientContext != IntPtr.Zero) flag = AuthzFreeContext(pClientContext); AuthzFreeCentralAccessPolicyCache();

using Imanami.GroupID.DataTransferObjects.DataContracts.Replication;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace EffectiveRightsUsingAuthzAPI
{
    public class Helper
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        static extern uint GetEffectiveRightsFromAcl(IntPtr pDacl, ref TRUSTEE pTrustee, ref ACCESS_MASK pAccessRights);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
        struct TRUSTEE
        {
            IntPtr pMultipleTrustee; // must be null
            public int MultipleTrusteeOperation;
            public TRUSTEE_FORM TrusteeForm;
            public TRUSTEE_TYPE TrusteeType;
            [MarshalAs(UnmanagedType.LPStr)]
            public string ptstrName;
        }
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
        public struct LUID
        {
            public uint LowPart;
            public int HighPart;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct AUTHZ_ACCESS_REQUEST
        {
            public int DesiredAccess;
            public byte[] PrincipalSelfSid;
            public OBJECT_TYPE_LIST[] ObjectTypeList;
            public int ObjectTypeListLength;
            public IntPtr OptionalArguments;
        };
        [StructLayout(LayoutKind.Sequential)]
        public struct OBJECT_TYPE_LIST
        {
            OBJECT_TYPE_LEVEL Level;
            int Sbz;
            IntPtr ObjectType;
        };

        [StructLayout(LayoutKind.Sequential)]
        public struct AUTHZ_ACCESS_REPLY
        {
            public int ResultListLength;
            public IntPtr GrantedAccessMask;
            public IntPtr SaclEvaluationResults;
            public IntPtr Error;
        };

        public enum OBJECT_TYPE_LEVEL : int
        {
            ACCESS_OBJECT_GUID = 0,
            ACCESS_PROPERTY_SET_GUID = 1,
            ACCESS_PROPERTY_GUID = 2,
            ACCESS_MAX_LEVEL = 4
        };
        enum TRUSTEE_FORM
        {
            TRUSTEE_IS_SID,
            TRUSTEE_IS_NAME,
            TRUSTEE_BAD_FORM,
            TRUSTEE_IS_OBJECTS_AND_SID,
            TRUSTEE_IS_OBJECTS_AND_NAME
        }

        enum AUTHZ_RM_FLAG : uint
        {
            AUTHZ_RM_FLAG_NO_AUDIT = 1,
            AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION = 2,
            AUTHZ_RM_FLAG_NO_CENTRAL_ACCESS_POLICIES = 4,
        }

        enum TRUSTEE_TYPE
        {
            TRUSTEE_IS_UNKNOWN,
            TRUSTEE_IS_USER,
            TRUSTEE_IS_GROUP,
            TRUSTEE_IS_DOMAIN,
            TRUSTEE_IS_ALIAS,
            TRUSTEE_IS_WELL_KNOWN_GROUP,
            TRUSTEE_IS_DELETED,
            TRUSTEE_IS_INVALID,
            TRUSTEE_IS_COMPUTER
        }

        [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
        static extern uint GetNamedSecurityInfo(
            string pObjectName,
            SE_OBJECT_TYPE ObjectType,
            SECURITY_INFORMATION SecurityInfo,
            out IntPtr pSidOwner,
            out IntPtr pSidGroup,
            out IntPtr pDacl,
            out IntPtr pSacl,
            out IntPtr pSecurityDescriptor);
        [DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzInitializeContextFromSid", CharSet = CharSet.Unicode)]
        static extern public bool AuthzInitializeContextFromSid(
                                               int Flags,
                                               IntPtr UserSid,
                                               IntPtr AuthzResourceManager,
                                               IntPtr pExpirationTime,
                                               LUID Identitifier,
                                               IntPtr DynamicGroupArgs,
                                               out IntPtr pAuthzClientContext
                                               );



        [DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzInitializeResourceManager", CharSet = CharSet.Unicode)]
        static extern public bool AuthzInitializeResourceManager(
                                        int flags,
                                        IntPtr pfnAccessCheck,
                                        IntPtr pfnComputeDynamicGroups,
                                        IntPtr pfnFreeDynamicGroups,
                                        string name,
                                        out IntPtr rm
                                        );
        [DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzFreeResourceManager", CharSet = CharSet.Unicode)]
        static extern public bool AuthzFreeResourceManager(IntPtr hManager);

        [DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzFreeHandle", CharSet = CharSet.Unicode)]
        static extern public bool AuthzFreeHandle(IntPtr hAccessCheckResults);

        [DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzFreeContext", CharSet = CharSet.Unicode)]
        static extern public bool AuthzFreeContext(IntPtr hAuthzClientContext);
        [DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzFreeCentralAccessPolicyCache", CharSet = CharSet.Unicode)]
        static extern public bool AuthzFreeCentralAccessPolicyCache();
        [DllImport("authz.dll", EntryPoint = "AuthzAccessCheck", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
        private static extern bool AuthzAccessCheck(int flags,
                                                    IntPtr hAuthzClientContext,
                                                     ref AUTHZ_ACCESS_REQUEST pRequest,
                                                     IntPtr AuditEvent,
                                                     IntPtr pSecurityDescriptor,
                                                    byte[] OptionalSecurityDescriptorArray,
                                                    int OptionalSecurityDescriptorCount,
                                                    ref AUTHZ_ACCESS_REPLY pReply,
                                                    out IntPtr phAccessCheckResults);

        enum ACCESS_MASK : uint
        {
            FILE_TRAVERSE = 0x20,
            FILE_LIST_DIRECTORY = 0x1,
            FILE_READ_DATA = 0x1,
            FILE_READ_ATTRIBUTES = 0x80,
            FILE_READ_EA = 0x8,
            FILE_ADD_FILE = 0x2,
            FILE_WRITE_DATA = 0x2,
            FILE_ADD_SUBDIRECTORY = 0x4,
            FILE_APPEND_DATA = 0x4,
            FILE_WRITE_ATTRIBUTES = 0x100,
            FILE_WRITE_EA = 0x10,
            FILE_DELETE_CHILD = 0x40,
            DELETE = 0x10000,
            READ_CONTROL = 0x20000,
            WRITE_DAC = 0x40000,
            WRITE_OWNER = 0x80000,


            ////////FILE_EXECUTE =0x20,   
        }

        [Flags]
        enum SECURITY_INFORMATION : uint
        {
            OWNER_SECURITY_INFORMATION = 0x00000001,
            GROUP_SECURITY_INFORMATION = 0x00000002,
            DACL_SECURITY_INFORMATION = 0x00000004,
            SACL_SECURITY_INFORMATION = 0x00000008,
            UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000,
            UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000,
            PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000,
            PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000
        }

        enum SE_OBJECT_TYPE
        {
            SE_UNKNOWN_OBJECT_TYPE = 0,
            SE_FILE_OBJECT,
            SE_SERVICE,
            SE_PRINTER,
            SE_REGISTRY_KEY,
            SE_LMSHARE,
            SE_KERNEL_OBJECT,
            SE_WINDOW_OBJECT,
            SE_DS_OBJECT,
            SE_DS_OBJECT_ALL,
            SE_PROVIDER_DEFINED_OBJECT,
            SE_WMIGUID_OBJECT,
            SE_REGISTRY_WOW64_32KEY
        }



        public static PermissionValues GetEffectivePermissions(string UserName, string Path, out string object_sid)
        {
            List<string> result = new List<string>();
            IntPtr pSidOwner, pSidGroup, pDacl, pSacl, pSecurityDescriptor;
            ACCESS_MASK mask = new ACCESS_MASK();
            uint ret = GetNamedSecurityInfo(Path,
                SE_OBJECT_TYPE.SE_FILE_OBJECT,
                SECURITY_INFORMATION.DACL_SECURITY_INFORMATION | SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION | SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION,
                out pSidOwner, out pSidGroup, out pDacl, out pSacl, out pSecurityDescriptor);

            IntPtr hManager = IntPtr.Zero;

            bool f = AuthzInitializeResourceManager(1, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, null, out hManager);

            NTAccount ac = new NTAccount(UserName);
            SecurityIdentifier sid;
            if (Imanami.PermissionProvider.FileSystem.Helper.isObjectSID(UserName))
                sid = new SecurityIdentifier(UserName);
            else
                sid = (SecurityIdentifier)ac.Translate(typeof(SecurityIdentifier));
            object_sid = sid.Value;
            byte[] bytes = new byte[sid.BinaryLength];
            sid.GetBinaryForm(bytes, 0);
            String _psUserSid = "";
            foreach (byte si in bytes)
            {
                _psUserSid += si;
            }

            LUID unusedSid = new LUID();
            IntPtr UserSid = Marshal.AllocHGlobal(bytes.Length);
            Marshal.Copy(bytes, 0, UserSid, bytes.Length);
            IntPtr pClientContext = IntPtr.Zero;

            if (f)
            {
                f = AuthzInitializeContextFromSid(0, UserSid, hManager, IntPtr.Zero, unusedSid, IntPtr.Zero, out pClientContext);


                AUTHZ_ACCESS_REQUEST request = new AUTHZ_ACCESS_REQUEST();
                request.DesiredAccess = 0x02000000;
                request.PrincipalSelfSid = null;
                request.ObjectTypeList = null;
                request.ObjectTypeListLength = 0;
                request.OptionalArguments = IntPtr.Zero;

                AUTHZ_ACCESS_REPLY reply = new AUTHZ_ACCESS_REPLY();
                reply.GrantedAccessMask = IntPtr.Zero;
                reply.ResultListLength = 0;
                reply.SaclEvaluationResults = IntPtr.Zero;
                IntPtr AccessReply = IntPtr.Zero;
                reply.Error = Marshal.AllocHGlobal(1020);
                reply.GrantedAccessMask = Marshal.AllocHGlobal(sizeof(uint));
                reply.ResultListLength = 1;
                int i = 0;
                Dictionary<String, String> rightsmap = new Dictionary<String, String>();
                List<string> effectivePermissionList = new List<string>();
                string[] rights = new string[14] { "Full Control", "Traverse Folder / execute file", "List folder / read data", "Read attributes", "Read extended attributes", "Create files / write files", "Create folders / append data", "Write attributes", "Write extended attributes", "Delete subfolders and files", "Delete", "Read permission", "Change permission", "Take ownership" };
                rightsmap.Add("FILE_TRAVERSE", "Traverse Folder / execute file");
                rightsmap.Add("FILE_LIST_DIRECTORY", "List folder / read data");
                rightsmap.Add("FILE_READ_DATA", "List folder / read data");
                rightsmap.Add("FILE_READ_ATTRIBUTES", "Read attributes");
                rightsmap.Add("FILE_READ_EA", "Read extended attributes");
                rightsmap.Add("FILE_ADD_FILE", "Create files / write files");
                rightsmap.Add("FILE_WRITE_DATA", "Create files /  write files");
                rightsmap.Add("FILE_ADD_SUBDIRECTORY", "Create folders / append data");
                rightsmap.Add("FILE_APPEND_DATA", "Create folders / append data");
                rightsmap.Add("FILE_WRITE_ATTRIBUTES", "Write attributes");
                rightsmap.Add("FILE_WRITE_EA", "Write extended attributes");
                rightsmap.Add("FILE_DELETE_CHILD", "Delete subfolders and files");
                rightsmap.Add("DELETE", "Delete");
                rightsmap.Add("READ_CONTROL", "Read permission");
                rightsmap.Add("WRITE_DAC", "Change permission");
                rightsmap.Add("WRITE_OWNER", "Take ownership");


                f = AuthzAccessCheck(0, pClientContext, ref request, IntPtr.Zero, pSecurityDescriptor, null, 0, ref reply, out AccessReply);
                if (f)
                {
                    int granted_access = Marshal.ReadInt32(reply.GrantedAccessMask);

                    mask = (ACCESS_MASK)granted_access;

                    foreach (ACCESS_MASK item in Enum.GetValues(typeof(ACCESS_MASK)))
                    {
                        if ((mask & item) == item)
                        {
                            effectivePermissionList.Add(rightsmap[item.ToString()]);
                            i++;
                        }

                    }
                }
                //Clear Memory
                {
                    Marshal.FreeHGlobal(reply.GrantedAccessMask);
                    if (reply.Error != IntPtr.Zero)
                        Marshal.FreeHGlobal(reply.Error);
                    if (UserSid != IntPtr.Zero)
                        Marshal.FreeHGlobal(UserSid);
                    if (pSidOwner != IntPtr.Zero)
                        Marshal.Release(pSidOwner);
                    if (pSidGroup != IntPtr.Zero)
                        Marshal.Release(pSidGroup);
                    if (pDacl != IntPtr.Zero)
                        Marshal.Release(pDacl);
                    if (pSacl != IntPtr.Zero)
                        Marshal.Release(pSacl);
                    if (pSecurityDescriptor != IntPtr.Zero)
                        Marshal.Release(pSecurityDescriptor);
                    if (reply.SaclEvaluationResults != IntPtr.Zero)
                        Marshal.FinalReleaseComObject(reply.SaclEvaluationResults);
                    if (request.OptionalArguments != IntPtr.Zero)
                        Marshal.FinalReleaseComObject(request.OptionalArguments);
                    bool flag = false;
                    if (AccessReply != IntPtr.Zero)
                        flag = AuthzFreeHandle(AccessReply);
                    if (hManager != IntPtr.Zero)
                        flag = AuthzFreeResourceManager(hManager);
                    if (pClientContext != IntPtr.Zero)
                        flag = AuthzFreeContext(pClientContext);
                    AuthzFreeCentralAccessPolicyCache();
                }
                
                if (i == 16)
                {
                    effectivePermissionList.Insert(0, "Full Control");
                    return PermissionValues.FULL_CONTROL;
                }
                PermissionValues per = PermissionValues.NONE;
                foreach (string r in effectivePermissionList)
                {

                    switch (r)
                    {
                        case "Traverse Folder / execute file":
                            per |= PermissionValues.FILE_TRAVERSE;
                            break;
                        case "List folder / read data":
                            per |= PermissionValues.FILE_LIST_DIRECTORY;
                            break;
                        case "Read attributes":
                            per |= PermissionValues.FILE_READ_ATTRIBUTES;
                            break;
                        case "Read extended attributes":
                            per |= PermissionValues.FILE_READ_EA;
                            break;
                        case "Create files / write files":
                            per |= PermissionValues.FILE_ADD_FILE;
                            break;
                        case "Create files /  write files":
                            per |= PermissionValues.FILE_WRITE_DATA;
                            break;
                        case "Create folders / append data":
                            per |= (PermissionValues.FILE_ADD_SUBDIRECTORY | PermissionValues.FILE_APPEND_DATA);
                            break;
                        case "Write attributes":
                            per |= PermissionValues.FILE_WRITE_ATTRIBUTES;
                            break;
                        case "Write extended attributes":
                            per |= PermissionValues.FILE_WRITE_EA;
                            break;
                        case "Delete subfolders and files":
                            per |= PermissionValues.FILE_DELETE_CHILD;
                            break;
                        case "Delete":
                            per |= PermissionValues.DELETE;
                            break;
                        case "Read permission":
                            per |= PermissionValues.READ_CONTROL;
                            break;
                        case "Change permission":
                            per |= PermissionValues.WRITE_DAC;
                            break;
                        case "Take ownership":
                            per |= PermissionValues.WRITE_OWNER;
                            break;
                    }
                }                
                return per;                
            }            
            return PermissionValues.NONE;            
        }
    }
}

Trying to run a MicrosoftGraph Api on a windows service

$
0
0
0
<button aria-label="down vote" aria-pressed="false" class="js-vote-down-btn grid--cell s-btn s-btn__unset c-pointer" data-selected-classes="fc-theme-primary" style="margin:2px;box-sizing:inherit;font:inherit;padding:0px;border-width:initial;border-style:none;border-color:initial;border-radius:3px;background-image:none;background-background-size:initial;background-repeat:initial;background-attachment:initial;background-origin:initial;background-clip:initial;outline:none;box-shadow:none;" title="This question does not show any research effort; it is unclear or not useful"><svg aria-hidden="true" class="svg-icon m0 iconArrowDownLg" height="36" viewBox="0 0 36 36" width="36"><path d="M2 10h32L18 26z"></path></svg></button><button aria-label="favorite" aria-pressed="false" class="js-favorite-btn s-btn s-btn__unset c-pointer py8" data-selected-classes="fc-yellow-600" style="margin:0px;box-sizing:inherit;font:inherit;padding:0px;border-width:initial;border-style:none;border-color:initial;border-radius:3px;background-image:none;background-background-size:initial;background-repeat:initial;background-attachment:initial;background-origin:initial;background-clip:initial;outline:none;box-shadow:none;" title="Click to mark as favorite question (click again to undo)"><svg aria-hidden="true" class="svg-icon iconStar" height="18" viewBox="0 0 18 18" width="18"><path d="M9 12.65l-5.29 3.63 1.82-6.15L.44 6.22l6.42-.17L9 0l2.14 6.05 6.42.17-5.1 3.9 1.83 6.16z"></path></svg>
</button>

I created a wrapper for the Microsoft graph api. I created it using a windows application and got it all working. However, I wanted to run the code on a windows service. As soon as i called it on the windows service I started getting the following exception

System.Security.Cryptography.CryptographicException: 'Key not valid for use in specified state.’

When the following code is ran

    internal static void BeforeAccessNotification(TokenCacheNotificationArgs args)
    {
        lock (FileLock)
        {
            args.TokenCache.Deserialize(File.Exists(CacheFilePath)
                ? ProtectedData.Unprotect(File.ReadAllBytes(CacheFilePath),
                                          null,
                                          DataProtectionScope.CurrentUser)
                : null);
        }
    }

The issue I have is the exact same code works fine on a windows form.

The full code is below

//------------------------------------------------------------------------------

using System.IO;
using System.Security.Cryptography;
using Microsoft.Identity.Client;

namespace TridentBusinessLogicLayer.ExternalAPICalls
{
    internal static class TokenCacheHelper
    {
        internal static string ClientId = "e1d695b5-xxxx-xxxx-xxxx-xxxxxxxxx";
        internal static string Tenant = "c69a670d-xxxx-xxxx-xxxx-xxxxxxxxx";

        internal static TokenCache GetUserCache()
        {
            if (usertokenCache == null)
            {
                usertokenCache = new TokenCache();
                usertokenCache.SetBeforeAccess(BeforeAccessNotification);
                usertokenCache.SetAfterAccess(AfterAccessNotification);
            }
            return usertokenCache;
        }

        static TokenCache usertokenCache;

        internal static readonly string CacheFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location + ".msalcache.bin";

        internal static readonly object FileLock = new object();

        internal static void BeforeAccessNotification(TokenCacheNotificationArgs args)
        {
            lock (FileLock)
            {
                args.TokenCache.Deserialize(File.Exists(CacheFilePath)
                    ? ProtectedData.Unprotect(File.ReadAllBytes(CacheFilePath),
                                              null,
                                              DataProtectionScope.CurrentUser)
                    : null);
            }
        }

        internal static void AfterAccessNotification(TokenCacheNotificationArgs args)
        {
            if (args.HasStateChanged)
            {
                lock (FileLock)
                {
                    File.WriteAllBytes(CacheFilePath,
                                       ProtectedData.Protect(args.TokenCache.Serialize(),
                                                             null,
                                                             DataProtectionScope.CurrentUser)
                                      );
                }
            }
        }
    }
}


using System.Linq;
using Microsoft.Graph;
using Microsoft.Identity.Client;
using System;
using System.Configuration;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Net.Http;

namespace TridentBusinessLogicLayer.ExternalAPICalls.Helpers
{
    // This class encapsulates the details of getting a token from MSAL and exposes it via the
    // IAuthenticationProvider interface so that GraphServiceClient or AuthHandler can use it.
    // A significantly enhanced version of this class will in the future be available from
    // the GraphSDK team.  It will supports all the types of Client Application as defined by MSAL.
    public class MsalAuthenticationProvider
    {

        public MsalAuthenticationProvider() 
        {
            GetDataAsync().GetAwaiter().GetResult();
        }

        static async Task GetDataAsync()
        {
            PublicClientApplication clientApp = new PublicClientApplication(ConfigurationManager.AppSettings["clientId"].ToString());

            GraphServiceClient graphClient = new GraphServiceClient(
                "https://graph.microsoft.com",
                new DelegateAuthenticationProvider(
                    async (requestMessage) =>
                    {
                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", await GetTokenAsync(clientApp));
                    }));
            var currentUser = await graphClient.Me.Request().GetAsync();

        }

        /// <summary>
        /// Acquire Token
        /// </summary>
        static async Task<string> GetTokenAsync(PublicClientApplication clientApp)
        {
            string[] scope = {"User.Read" };
            string token = null;
            AuthenticationResult authResult = await clientApp.AcquireTokenAsync(scope);
            token = authResult.AccessToken;
            return token;
        }

    }

how to acess the textbox in form1.cs using the program.cs

$
0
0
Hi Geeks,
               i have a problem in updating a textbox that is used in a class in  form1.cs .Textbox should get updated by a message sent from the program.cs.the idea is i have to chnage the message in the textbox based on the condition in the code present in the program.cs,as i cant acess the textbox object craeted in the form1.cs class...plz help me in this regard of using the Ui component in the program.cs....

Thanks in Advance.....
Regards /-\\/|/\//-\S|-|"Life IS An opportunity To prove Ur Self"

jq ajax not working with web form

$
0
0

Hi   I copied example of ajax and tried to run it. I am using .net 4.6.1  web form. I am getting error: Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

is this CORS issue? Please help

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Ajax._Default" %><asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server"><div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div><button>Get External Content</button><script>
        $(document).ready(
            function () {
                $('button').click(

                function () {
                    $.ajax({
                        url: "./test.txt",
                        success: function (data) {

                            $('#div1').innerHtml = data;
                        }
                    });
                })
                }
);

    </script></asp:Content>

I am getting run time error:Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

Lambda Groupby 2 or more properties. Why is this not working

$
0
0
classPerson {
internalintPersonID;
internalstringcar ;
internalstringFirstName;
internalstringLastName;
internalstringCarSeries;
}

//Program snippet below not working correctly

Person[] persons =newPerson[3];
persons[0] =newPerson {PersonID = 2,car = "Ferrari",FirstName="Martin",LastName="James",CarSeries="Series A" };
persons[0] =newPerson {PersonID = 2,car = "Ferrari",FirstName="Martin",LastName="James" ,CarSeries="Series B" };
persons[0] =newPerson {PersonID = 2,car = "Ferrari",FirstName="Martin",LastName="James" ,CarSeries="Series C" };
persons[1] =newPerson {PersonID = 1,car = "BMW",FirstName="Joanne",LastName="James" ,CarSeries="Series 1" };
persons[1] =newPerson {PersonID = 1,car = "BMW",FirstName="Joanne",LastName="James" ,CarSeries="Series 3" };
persons[2] =newPerson {PersonID = 2,car = "Audi",FirstName="Martin",LastName="James" ,CarSeries="A3" };
persons[2] =newPerson {PersonID = 1,car = "Porche",FirstName="Joanne",LastName="James" ,CarSeries="Series Carrera" };
persons[2] =newPerson {PersonID = 3,car = "Lexus",FirstName="Leon",LastName="James" ,CarSeries="S Class"};
Console.Out.WriteLine("--------------------------------------------");
varresults5 =persons.GroupBy(p=>new {FirstName=p.FirstName,LastName=p.LastName,Car=p.car,CarSeries= p.CarSeries}).
Select(grp =>new { Name =grp.Key.FirstName+" "+grp.Key.LastName,Car = grp.Key.Car,CarSeries=grp.Key.CarSeries}).ToList();
foreach(vargpin results5){
Console.Out.WriteLine(gp.Name+", "+gp.Car+","+gp.CarSeries);
}

noviceDeveloper


HttpWebRequest returns error in c#, works in simple php example

$
0
0

I have working php example, which does its job, but can not make the same in .NET - returning:

System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel. at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) at System.Net.HttpWebRequest.GetRequestStream() at

PHP Code:

$curl = curl_init();
$post_fields = "command=a&amount=".$var_amount."&currency=981&client_ip_addr=192.168.0.88&description=UFCTEST&msg_type=SMS";
$submit_url = "https://ecommerce.........";
Curl_setopt($curl, CURLOPT_SSLVERSION, 1); //0 
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, '0');
curl_setopt($curl, CURLOPT_SSLCERT,         getcwd().'/sert.pem');
curl_setopt($curl, CURLOPT_SSLKEYPASSWD,   'XXXXXXXX');
curl_setopt($curl, CURLOPT_URL, $submit_url);
$result = curl_exec($curl);
$info = curl_getinfo($curl);

.NET Code

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string addr1 = "https://ecommerce......";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(addr1);

req.Method = "POST"; // Post method
System.Net.ServicePointManager.ServerCertificateValidationCallback =
    delegate
    {
        return true; // **** Always accept
    };

req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version10;

//Certificate with private key
string certName = "ecommerce.ufc.ge_5300954_merchant_wp";
string certpwd = "xxxxxxxx";
X509Certificate2 cert = new X509Certificate2(@"c:\WebSites\Demo\" + certName + ".pem", certpwd);

req.ServerCertificateValidationCallback =
    delegate
    {
        return true; // **** Always accept
    };

req.ClientCertificates.Add(cert);

//req.PreAuthenticate = false;

string langStr = "";
String XML = "command=a&amount=" + priceStr + "&currency=981" + langStr + "&client_ip_addr=" + Request.UserHostAddress.ToString() + "&description=PaymentForEtendersServices&msg_type=SMS";//reader.ReadToEnd();

byte[] buffer = Encoding.ASCII.GetBytes(XML);
req.ContentLength = buffer.Length;

// Wrap the request stream with a text-based writer

Stream writer = req.GetRequestStream();
writer.Write(buffer, 0, buffer.Length);
writer.Close();

WebResponse rsp = req.GetResponse();
String post_response = "";
using (StreamReader responseStream = new StreamReader(rsp.GetResponseStream()))
{
}

I have tried many variations of ignoring cert errors, or playing with tls ssl ver sions etc, but none seems to be working I have tried many variations of ignoring cert errors, or playing with tls ssl ver sions etc, but none seems to be working.

Also , trying code from similar posts does not help either.

Thank you.

Base32 Encoding and Decoding Sample code

$
0
0

Hi Team ,

 Is there any Dotnet inbuilt Base32Encode and Decode functionality available.

Thanks,

Gowthami

 

netnet

$
0
0
netdfdfssadasdqefwekfjhewfjsgchbxjbfuiewfjnkhuwhlkdkzmzm mnreygfeuhafuefkambwepljdmsuryewnn,fhuieyifgwef.kjhfieggygrp77wdhfjhregekjbchjsdgfyoii[qwejwnsbhcsiuygfsuhrhurrjhiyidhbf;sfieherjkjdfhdriewhjrh
Viewing all 8156 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>