Category Archives: C#

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

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

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

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.

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.

ELMAH – Error Logging Modules and Handlers

What is ELMAH?

  • ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.
  • Once ELMAH has been dropped into a running web application and configured appropriately, you get the following facilities without changing a single line of your code:
    • Logging of nearly all unhandled exceptions.
    • A web page to remotely view the entire log of recoded exceptions.
    • A web page to remotely view the full details of any one logged exception, including colored stack traces.
    • In many cases, you can review the original yellow screen of death that ASP.NET generated for a given exception, even with customErrors mode turned off.
    • An e-mail notification of each error at the time it occurs.
    • An RSS feed of the last 15 errors from the log.

How to Install ELMAH on your MVC Project?

  • Open Nuget Package Manager on the MVC Project
  • Search for ELMAH and Install it.
  • Then configure it.

ELMAH Configuration

  • It will already add some configuration under your web.config but we need to include some configuration so that it will point to a database.
  • <connectionStrings>

  <add name=”elmahConnectionString” connectionString=”Data Source=Server;Initial Catalog=ELMAH_DEV;uid=user;pwd=user;Pooling=true;Min Pool Size=0;Max Pool Size=999;” providerName=”System.Data.SqlClient” />

</connectionStrings>

  • <elmah>

    <!–

See http://code.google.com/p/elmah/wiki/SecuringErrorLogPages for

more information on remote access and securing ELMAH.

–>

<security allowRemoteAccess=”true” />

<errorLog type=”Elmah.SqlErrorLog, Elmah” applicationName=”NameOfApplication_DEV” connectionStringName=”elmahConnectionString” />

</elmah>

  • We also need to remove some sections that we don’t need specially the section below that automatically create a page for the logs.
  • <location path=”elmah.axd” inheritInChildApplications=”false”>…</location>

Logging

  • All uncatched exception will automatically be recorded.
  • All exception handling will NOT be recorded automatically. It needs to be manually logged by including the Elmah.ErrorSignal.FromCurrentContext().Raise(ex);

try{
throw new Exception(“Some Exception”);
}catch(Exception ex){

Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}

 

Service Oriented Architecture

Service Oriented Architecture is an architecture that make all request bounded on a form of a Service such as APIs. It consist of three different layers as follows:

  • Authorization Server – Responsible on Authorizing and Authenticating Users and encapsulate it on a token.
  • Resource Server – Responsible to give data based on the token that will be given by the Authorization server.
  • Clients – Responsible to request the token on behalf of a user from the Authorization Server and request resources from the Resource Server.

With this kind of architecture developer can make their application compatible to different platform such as Windows, Linux, and Mac OS. Some implementation of this uses some protocols such as OAuth which is implemented in different ways.

Signalr – OnDisconnect(bool stopCalled)

Most of us who are using .Net as our Programming language use Signalr as our Real-Time Framework. And we implement OnDisconnect in most cases to catch clients that have been disconnected. Since then there were no parameter included as an Overload of the said method. Lately on the latest releases by the Signalr team they have included an Overload so that we can distinguish what triggers the disconnection and help us manage our Apps behavior to it.

With this said I have one experience that I want to share as this may also frustrate some people who are counting connected users and having a problem that when their app have multi workers (Web Garden) they app somehow always trigger OnDisconnect even if the user is still connect. So I want to share this findings on how to properly address it.

  1. Make sure that the App is using a Backplane to manage connection on your hub so that the connections are shared on all threads/servers. I use SQLServer.
  2. Make sure to use the Database on counting your list of connection and tagging who is who. Because in memory List even its static will not be shared on a different server (obviously).
  3. Make sure to trigger disconnection action when the OnDisconnect is called with the stopCalled is equal to true.

Let me highlight what is stopCalled is equal to true means.

  1. It returns true if the method on the connection to close is trigger
  2. It returns true if the browser is called
  3. It returns false if the timeout has been met

Hope this instructions will help you manage your site as it help me on our projects.

God Bless!

Thanks,
Thomie

RockRMS : Free Relationship Management System

RockRMS

I have been searching for an Open Source management of our church that is also created on ASP .Net. I have found RockRMS. RockRMS is created using ASP .Net Web Form that is so dynamic and Scale-able it can accommodate both external website and internal operation of a Church. There is even a dedicated hosting that will maintain your system and is hosted on Windows Azure.

Its source code is also available on GitHub so others can contribute to the pipeline. You may visit their website at https://www.rockrms.com/

Here are some of the screenshots provided on their website:

 

God Bless!

Thanks,
Thomie

Pechkin – NET Wrapper for WkHtmlToPdf

Pechkin

.NET Wrapper for WkHtmlToPdf DLL, library that uses Webkit engine to convert HTML pages to PDF. It is now available on Nuget for easy installation on your Visual Studio Solution/Projects.

How easy is it to use? Just install it via Nuget and add a reference on your code then use either one of the following:

byte[] pdfBuf = new SimplePechkin(new GlobalConfig()).Convert("<html><body><h1>Hello world!</h1></body></html>");

and

// create global configuration object
GlobalConfig gc = new GlobalConfig();

// set it up using fluent notation
gc.SetMargins(new Margins(300, 100, 150, 100))
  .SetDocumentTitle("Test document")
  .SetPaperSize(PaperKind.Letter);
//... etc

// create converter
IPechkin pechkin = new SynchronizedPechkin(gc);

// subscribe to events
pechkin.Begin += OnBegin;
pechkin.Error += OnError;
pechkin.Warning += OnWarning;
pechkin.PhaseChanged += OnPhase;
pechkin.ProgressChanged += OnProgress;
pechkin.Finished += OnFinished;

// create document configuration object
ObjectConfig oc = new ObjectConfig();

// and set it up using fluent notation too
oc.SetCreateExternalLinks(false)
  .SetFallbackEncoding(Encoding.ASCII)
  .SetLoadImages(false)
  .SetPageUri("http://google.com");
//... etc

// convert document
byte[] pdfBuf = pechkin.Convert(oc);

 

God Bless!

Thanks,
Thomie

TCP and C# Connecting via Lan

Have you ever thought that you want to connect to create an application that can talk via LAN? Then TCP is one of the mode that you can choose one. Here are the codes from MSDN that can help you:

TCPListen – This is used when you want to create a server like application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace TCPListen
{
class Program
{
static void Main(string[] args)
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");

// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);

// Start listening for client requests.
server.Start();

// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;

// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");

// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");

data = null;

// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();

int i;

// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);

// Process the data sent by the client.
data = data.ToUpper();

byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}

// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}

Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
}

TCPClient – As the name suggest it will be used to create the client that will connect to our server.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace TCPListen
{
class Program
{
static void Main(string[] args)
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");

// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);

// Start listening for client requests.
server.Start();

// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;

// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");

// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");

data = null;

// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();

int i;

// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);

// Process the data sent by the client.
data = data.ToUpper();

byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}

// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}

Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
}

God Bless!

Thanks,
Thomie

Mediafire API for C# + Resharper

 Hi There,

I have been searching on the net of a Mediafire API for C#. I gently saw this API from Google. It has a note that it needs Resharper so I think you need that plugin before you can use it. As for the testing I don’t have any Resharper yet so I can test it myself so I have decided to publish it here so you can use and try it. You may give some feed back of your trying and share it to the world!

Source: http://pastebin.com/Cj1syDss

Mirror Download: Mediafire API C# + Resharper

Thanks,

 

Creating a file to Download dynamically in an https / SSL connection

Hi there, 

Here is a tip when you are programming something that you want your file’s path to be hidden. It’s specially when its under a secure connection or https or SSL connection.

  1. Remember the mime type ea. image/jpg
  2. Remember the file name ea. image.jpg
  3. Remember not to put expiration and no-cache on your header
  4. Remember to open it on another tab or window as much as possible
  5. When you are debugging you can remove the headers so the file won’t be downloaded

Hope this tips can help you specially #3 because your download will fail on lower version of IE.

Thanks,

A potentially dangerous Request.Form value was detected from the client

Have you ever experience the following error in ASP .NET?

A potentially dangerous Request.Form value was detected from the client 

Then you are one like me. Then you should now that one of the values of your elements (<inputs> or <button> or <textarea>) has html elements on it. Example is bellow:

<input type=’text’ name=’content’ value='<script language=”javascript”>alert(“Hello World!”);</script>’/>

Then you should also know that this error is persisting because the values given above might be an XSS attack. If you are sure that you want to accept this type of values on your dabatase you may explicitly remove this validation by adding this tag to your page’s masterpage or 1st line of tag.

validateRequest=”false”

If you are on ASP .NET MVC you can add this to your model, assuming that your model has the content variable.

[AllowHtml]
public string content = String.Empty;

Thanks hope it help you allot. Also if you are not familiar with XSS attacks, I will try to make an article for that so you can create your own script that is hack-able, be able to prevent it, and know what are it’s crons.

God Bless!