Category Archives: Programming

Powershell GetADUser Name vs DisplayName

When using GetADUser usually we are using the default properties it return. This usually not the case and when we were using it as the property Name it doesn’t update when user’s name got updated. To facilitate this use DisplayName.

This also includes the alias on searching the email of the user. This is helpful if your organization uses multiple domains.

$user = Get-ADUser -Filter * -Properties EmailAddress,DisplayName,Mail,ProxyAddresses,UserPrincipalName | Where-Object { $_.ProxyAddresses -contains “SMTP:[email protected]” -or $_.UserPrincipalName -eq ’[email protected]’ -or $_.EmailAddress -eq ’[email protected]’}

$user.DisplayName

PowerApps get user’s email

There is some instances that users have different userprincipalname vs their actual email due to an alias was used for some users. Because of this the following provide different values:

  1. User().Mail
  2. Office365Users.MyProfileV2().mail

I would recommend to factor in this scenarios to use the second as this provide coverage on users with alias on their account

Active Directory via C#

There is a requirement to perform CRUD operation on an Active Directory and we need to create it on C#. The following code will help an engineer accordingly:

Create

using (DirectoryEntry directoryEntry = new DirectoryEntry("LDAP:\\url\ou", "username", "password"))
                {
                    using (DirectoryEntry newUser = directoryEntry.Children.Add("CN=Name", "User"))
                    {
                        if (!DirectoryEntry.Exists(newUser.Path))
                        {
                            newUser.Properties["property1"].Add(propertyValue);
                            newUser.CommitChanges();
                            ret = true;
                        }
                    }
                }

Update

using (DirectoryEntry directoryEntry = new DirectoryEntry("LDAP:\\url\ou", "username", "password"))
                {
                    using (DirectorySearcher search = new DirectorySearcher(directoryEntry))
                    {
                        search.Filter = String.Format("(IdentifierProperty={0})", identifier);
                        search.PropertiesToLoad.Add("property1");
                        SearchResult result = search.FindOne();
                        if (result != null)
                        {
                            using (DirectoryEntry entryToUpdate = result.GetDirectoryEntry())
                            {
                                entryToUpdate.Properties["property1"].Value = "property1value";
                                entryToUpdate.CommitChanges();
                                ret = true;
                            }
                        }
                    }
                }

Delete

using (DirectoryEntry directoryEntry = new DirectoryEntry("LDAP:\\url\ou", "username", "password"))
                {
                    using (DirectorySearcher search = new DirectorySearcher(directoryEntry))
                    {
                        search.Filter = String.Format("(IdentifierProperty={0})", identifier);
                        search.PropertiesToLoad.Add("property1");
                        SearchResult result = search.FindOne();
                        if (result != null)
                        {
                            using (DirectoryEntry entryToUpdate = result.GetDirectoryEntry())
                            {
                                directoryEntry.Children.Remove(entryToUpdate);
                                directoryEntry.CommitChanges();
                                ret = true;
                            }
                        }
                    }
                }

MSSQL Grant Execute Stored Procedure only

There are cases that we only want to grant read-write only access then also enable users to execute stored procedure with in the SQL Server database.

In order to do this we will need to:

  1. Create a new Role named, db_exec_storedprocedure

    CREATE ROLE db_exec_storedprocedure
  2. Grant that role with execute stored procedure

    GRANT EXECUTE TO db_exec_storedprocedure
  3. Then add the user as a member of that role.

That’s it you can now grant specific permission to execute stored procedure.

God Bless!
Thanks,
Thomie

Dynamic Object in C#

In my experience there was a need to create an object and its properties dynamically. Namely as follows:

thisIsMyObject.MyProperty1 = "AnyValueOfAnyType";
thisIsMyObject.MyProperty2 = true;
thisIsMyObject.MyProperty3 = 1;

To do this there could be different approaches like using a dictionary

Dictionary<string,object> c = new Dictionary<string,object>();
//adding a value
c.Add("MyProperty1", "AnyValueOfAnyType");
c.Add("MyProperty2", true);
c.Add("MyProperty3", 1);
//getting the value
c["MyProperty1"]; //AnyValueOfAnyType
c["MyProperty2"]; //true
c["MyProperty3"]; //1

But you may also use a dynamic object like as follows

var c = new System.Dynamic.ExpandoObject() as IDictionary<string, Object>; //namespace for note only
//adding a value
c["MyProperty1"] = "AnyValueOfAnyType";
c["MyProperty2"] = true;
c["MyProperty3"] = 1;
//getting the value
c["MyProperty1"]; //AnyValueOfAnyType
c["MyProperty2"]; //true
c["MyProperty3"]; //1

This way its more presentable and like using an array.

God Bless!

Thanks,
Thomie

Visual Studio Extension -Ngrok

Ngrok is now widely being used. From simple web development up to complex development. Is hard to run Ngrok everytime you are coding specially when using IIS Express that if not configured to use a specific IP it will generate random port which is a hard to map.

Thankfully there is a plug-in for our beloved Visual Studio to integrate this.

Ngrok Extensions

With Ngrok Extension we only open our Visual Studio solution and navigate to Tool>Start ngrok Tunnel and it will create a tunnel for the websites under your solution.

Try it now!

God Bless!

Thanks,
Thomie

Ngrok – Free Web Tunneling

In the verge of today’s web development we encounter cases that in order to proceed we need to have a public accessible URL. Thankfully, Ngrok provide a free service to do this.

What it does is tunnel your machine to a Ngrok URL with a specific port. We just need to download the ngrok.exe from their website and run the command like

ngrok http 80


With this command your service on your local machine that is running on port 80 will be mapped and accessible publicly for FREE. For a full documentation view it here.

God Bless!

Thanks,
Thomie

Want to convert your load to cash?

I was once a user of load that expires. Expiring load is a past as with the ability to convert load to cash emerges with LoadToCash

LoadToCash support the following:

  1. All SIMs
  2. Postpaid and Prepaid
  3. Unlimited conversions
  4. Several options to cashout

Availing the service is just a app away. Download LoadToCash via Play Store. Register. Convert. and then Wait.

LoadToCash allows cashout to the following:

  1. BDO
  2. BPI
  3. GCash
  4. Coins.ph
  5. Paymaya

Just a tip your consumables is not allowed to be pasaload. But they can be converted via LoadToCash.

God Bless!

Thanks,
Thomie

Adding Proxy on Web.Config

Hi,

There are some cases when developing your web application on .net you may experience proxy issues when you are accessing APIs on your application. To fix this you may add this on your web.config/app.config under the configuration section

 

<system.net>
<defaultProxy useDefaultCredentials=”true”>
<proxy usesystemdefault=”true” proxyaddress=”http://proxy:8080″ bypassonlocal=”true” />
<bypasslist />
</defaultProxy>
</system.net>

God Bless!

Thanks,
Thomie

Review: Tab Manager

In a world of development cycle we open several tabs for research and development, requirement gathering, and even when presenting. In cases like this we want to open tabs simultaneously. Most of us will do this by creating folder on our Bookmarks and open them up. For me I use Tab Manager on chrome to do this. Its so easy.

  1. Open the tabs you want
  2. Name them on Tab Manager
  3. Then click the + sign

Thats it. It will save that as a group and with just one click you will open them all. The best part of it is its free and it sync the data along with your google account. Download it now at https://chrome.google.com/webstore/detail/tab-manager/mcidendbndlekegaphipeeoaemckemhm

God Bless!

Thanks,
Thomie

Fix SignalR OnDisconnected not working

This just come up and after searching and testing it like to Fix SignalR OnDisconnected if not working is to implement on the client at least one method so that this method will be called. Think of it like a requirement.

Example for the SignalR residing on the same server

<!– Reference to jQuery –>
<!– Reference to SignalR –>
<script src=”~/hubs/signalr“></script>
<script>
var onlineHubProxy = $.connection.onlineHub;

onlineHubProxy.client.void = function(){
//do nothing
};

$.connection.start();

</script>

Then try again now and the Default methods of hubs will now be working properly.

God Bless!

Thanks,
Thomie

DateTime not parsing MM/dd/yyyy correctly on Windows 10 on ASP .Net MVC

Have you experienced coding and all of a sudden when on windows 10 you experienced that MM/dd/yyyy is not a valid date? This is because of the culture that is default implemented on your device, in this case on my device with Windows 10 Pro. To cause of this is the machine is by default is using dd/MM/yyyy and in this case apps that we are developing is having this kind of issue.

Thank fully the fastest way to fix is via the web.config with the following code:

<system.web>

<globalization culture=”en-US” uiCulture=”en-US”/>

 

And then run again your application and it will now accept your MM/dd/yyyy.

Replace words on MS Word using C#

Hi,

Recently I was instructed to create an application that will be able to replace an array of words and replace them with an array of corresponding words on an MS Word document. With this I’ve searched the following:

Prerequisites

  1. Visual Stduio
  2. Install the nuget package DocX
  3. Administrative access on the context the application is running

Code

Dictionary<string, string> lReplacements = new Dictionary<string, string>();
string newFullPath = @”c:\sample.docx”;

using (DocX document = DocX.Load(newFullPath))
{

//for loop is better than foreach
foreach (var item in lReplacements)
{

document.ReplaceText(item.Key, item.Value);

}
document.Save();

}

Hope it helped you as it helped me with this simple snippet.

God Bless!
Thanks,
Thomie

C# Task<object> return Type

In every signalr or webapi request based application there is a need to indicate the return type of Task<object> along with the async keyword. Let say this sample:

public async Task<MyObject> GetItem(){

MyObject myObject = new MyObject();

myObject = await getSomeWhereThere();

#doSomethingElse

return myObject;

}

In this sample, we all know that this is a asynchronous request from somewhere. Which dictates that myObject will return later after the getSomeWhereThere(); has finished executing. But we need to remind of a very important thing that #doSomethingElse will not be executed in Xamarin if it is not properly used. Let say we did this instead:

public async void GetItem(){

MyObject myObject = new MyObject();

myObject = await getSomeWhereThere();

#doSomethingElse

}

In this code the #doSomethingElse will not be executed because it will only assume that after the getSomeWhereThere(); is executed you don’t mind if #doSomethingElse is still needed. Thus make sure that we use the Task<MyObject> in cases like this so that #doSomethingElse will still be executed.

Tip: MSSQL Drop all triggers

Its funny that sometimes we need to drop all triggers because we inputed a logic that will prohibit a particular code. In cases like this we can drop them all and later create them again. In database with plent of tables, 100 tables, its hard if we drop them one by one. So here is a script that can help you as it just did to me.

SELECT N’DROP TRIGGER ‘ +QUOTENAME(OBJECT_SCHEMA_NAME(t.object_id)) + N’.’ +   QUOTENAME(t.name) + N’; ‘ + NCHAR(13)

FROM sys.triggers AS t

WHERE t.is_ms_shipped = 0 AND t.parent_class_desc = N’OBJECT_OR_COLUMN’;


God Bless!

Tip: MSSQL list all SPs by its modified date

In some cases we may want to get from MSSQL list all SPs by its modified date so that we know what we or our college did modified last. Here is a query you may use

SELECT name, OBJECT_DEFINITION(object_id), modify_date
FROM sys.procedures
ORDER BY modify_date DESC

This query will return the SPs from the latest modified stored procedure. Its handy specially when your migrating SPs manually.

God Bless!

MSSQL: Search all Records of a Database

Hi,

There are times that we need to find something or search all records particular on an unfamiliar database in MSSQL. It is good to know how to query every item as a worst case scenario. I found this online which can help you, just like me, on looking unto a database that has no documentation.

DECLARE
@search_string VARCHAR(100),
@table_name SYSNAME,
@table_schema SYSNAME,
@column_name SYSNAME,
@sql_string VARCHAR(2000)

SET @search_string = ‘Test’

DECLARE tables_cur CURSOR FOR SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ‘BASE TABLE’

OPEN tables_cur

FETCH NEXT FROM tables_cur INTO @table_schema, @table_name

WHILE (@@FETCH_STATUS = 0)
BEGIN
DECLARE columns_cur CURSOR FOR SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @table_schema AND TABLE_NAME = @table_name AND COLLATION_NAME IS NOT NULL — Only strings have this and they always have it

OPEN columns_cur

FETCH NEXT FROM columns_cur INTO @column_name
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @sql_string = ‘IF EXISTS (SELECT * FROM ‘ + QUOTENAME(@table_schema) + ‘.’ + QUOTENAME(@table_name) + ‘ WHERE ‘ + QUOTENAME(@column_name) + ‘ LIKE ”%’ + @search_string + ‘%”) PRINT ”’ + QUOTENAME(@table_schema) + ‘.’ + QUOTENAME(@table_name) + ‘, ‘ + QUOTENAME(@column_name) + ””

EXECUTE(@sql_string)

FETCH NEXT FROM columns_cur INTO @column_name
END

CLOSE columns_cur

DEALLOCATE columns_cur

FETCH NEXT FROM tables_cur INTO @table_schema, @table_name
END

CLOSE tables_cur

DEALLOCATE tables_cur

God Bless!

Thanks,
Thomie

Reapply jQuery validate to a Form loaded via AJAX

Here is a quick snippet to apply jQuery validate to a form loaded via AJAX.

 

var form = $(“#youFormIdentifier”);
form.removeData(‘validator’);
form.removeData(‘unobtrusiveValidation’);
$.validator.unobtrusive.parse(form);

 

Then you can now check if it is valid via:

 

var isValid = form.valid();

Convert.ToDateTime Regardless of Culture

Did you upgrade to Windows 10 recently and your MVC website now have an issue under the development phase after it? Then maybe you also experience the same issue that affected your code on IIS. That is becuase Convert.ToDateTime utilizes the machine’s Culture(It changes when you use Windows 10 even you are using the same Country set) to parse a Date time. So to use it regardless of the Culture use the code snippet below.

 

string s = “20.09.2015 10.16.12”;
string expextedFormat = “dd.MM.yyyy HH.mm.ss”;
DateTime d;
bool isValid = DateTime.TryParseExact(s, expextedFormat , CultureInfo.InvariantCulture, DateTimeStyles.None, out d);

 

Hope it helped you as it helped me.