European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET Core 2.2.1 Hosting - HostForLIFE.eu :: Insert Data using Uploading Excel file and upload image and set water mark

clock September 28, 2018 11:17 by author Peter

In this blog, I will show you how to Insert Data using Uploading Excel file and upload image and set water mark. Let's write the code below.

Demo.aspx
<body> 
    <form id="form1" runat="server"> 
        <div> 
            <table> 
                <tr> 
                    <td> 
                        <asp:FileUpload ID ="fu" runat ="server" /> 
                    </td> 
                    <td> 
                        <asp:Button ID ="btnupload" runat ="server" Text="Upload File" 
onclick="btnupload_Click" /> 
                    </td> 
                </tr> 
            </table> 
        </div> 
    </form> 
</body> 


Demo.aspx .cs
DataTable dt = new DataTable(); 
 
protected void btnupload_Click(object sender, EventArgs e) 

    if (fu.HasFile) 
    { 
        if (fu.PostedFile.ContentType == "application/vnd.ms-excel" || fu.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") 
        { 
            string fileName = Path.Combine(Server.MapPath("~/localization"), Guid.NewGuid().ToString() + Path.GetExtension(fu.PostedFile.FileName)); 
            fu.PostedFile.SaveAs(fileName); 
 
            string conString = ""; 
            string ext = Path.GetExtension(fu.PostedFile.FileName); 
            if (ext.ToLower() == ".xls") 
            { 
                conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; 
            }  
            else if (ext.ToLower() == ".xlsx")  
            { 
                conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\""; 
            } 
            string query = "Select * from [Sheet1$]"; 
            OleDbConnection con = new OleDbConnection(conString); 
            OleDbDataAdapter data = new OleDbDataAdapter(query, con); 
            data.Fill(dt); 
            int i = 0; 
            //File_Upload file = new File_Upload(); 
            for (i = 0; i < dt.Rows.Count; i++) 
            { 
                string name = dt.Rows[i]["name"].ToString(); 
                string email = dt.Rows[i]["email"].ToString(); 
                string pass = dt.Rows[i]["Password"].ToString(); 
                string mobile = dt.Rows[i]["mobile"].ToString(); 
                string state = dt.Rows[i]["state"].ToString(); 
                string city = dt.Rows[i]["city"].ToString(); 
                string photo = dt.Rows[i]["Photo"].ToString(); 
 
                string[] pathArr = photo.Split('\\'); 
                string[] fileArr = pathArr.Last().Split('.'); 
                string fName = fileArr[0].ToString(); 
                Random rnd = new Random(); 
                string fn = fName + "_" + rnd.Next(111, 999) + "_" + rnd.Next(111, 999) + ".jpg"; 
                string path = "~/photo/" + fn; 
                string pat = Server.MapPath(path); 
                Wattermark w = new Wattermark(); 
                Dal odal = new Dal(); 
                System.Drawing.Image image = System.Drawing.Image.FromFile(photo); 
                Graphics graphics = Graphics.FromImage(image); 
                Font font = new Font("Times New Roman", 42.0f); 
                PointF point = new PointF(10, 10); 
                graphics.DrawString("Tusharsangani", font, Brushes.Red, point); 
                image.Save(pat); 
                odal.fetch("insert into Registeruser (name,E_id,password,mobile,state,city,photo) values('" + name + "','" + email + "','" + pass + "','" + mobile + "','" + state + "','" + city + "','" + path + "')"); 
            } 
        } 
    }  
    else  
    { 
 
    } 

HostForLIFE.eu ASP.NET Core 2.2.1 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET Core 2.2.1 Hosting - HostForLIFE.eu :: Random Password In C#

clock September 26, 2018 11:14 by author Peter

A random password is a combination of characters, numbers, and special characters. We can generate a random password by combining random numbers and random strings.
Generate A Random Password In C# And .NET Core. The code snippet in this article is an example of how to generate random numbers and random strings and combine them to create a random password using C# and .NET Core.

The Random class constructors have two overloaded forms. It takes either no value or it takes a seed value. The Random class has three public methods - Next, NextBytes, and NextDouble. The Next method returns a random number, NextBytes returns an array of bytes filled with random numbers, and NextDouble returns a random number between 0.0 and 1.0.

Generate a random number
The following code in Listing 1 returns a random number.
// Generate a random number 
Random random = new Random(); 
// Any random integer  
int num = random.Next(); 


Generate a random string
The following code snippet in Listing 2 generates a random string with a given size. The second parameter of the RandomString method is used for setting if the string is a lowercase string.
// Generate a random string with a given size and case.  
// If second parameter is true, the return string is lowercase 
public string RandomString(int size, bool lowerCase) 

    StringBuilder builder = new StringBuilder(); 
    Random random = new Random(); 
    char ch; 
    for (int i = 0; i < size; i++) 
    { 
        ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); 
        builder.Append(ch); 
    } 
    if (lowerCase) 
        return builder.ToString().ToLower(); 
    return builder.ToString(); 


Creating a random password
A random password can simply be a combination of a random string and a random number. To make it more complex, you can even add special characters and mix it up.
For us, we will combine the two methods - RandomNumber and RandomString.

The following code snippet in Listing 3 generates a password of length 10 with first 4 letters lowercase, next 4 letters numbers, and the last 2 letters as uppercase.
// Generate a random password of a given length (optional) 
public string RandomPassword(int size = 0) 

    StringBuilder builder = new StringBuilder(); 
    builder.Append(RandomString(4, true)); 
    builder.Append(RandomNumber(1000, 9999)); 
    builder.Append(RandomString(2, false)); 
    return builder.ToString(); 


All of the above functionality is listed here in Listing 4. Create a .NET Core Console app in Visual Studio and use this code.
using System; 
using System.Text; 
 
class RandomNumberSample 

    static void Main(string[] args) 
    { 
        // Generate a random number 
        Random random = new Random(); 
        // Any random integer  
        int num = random.Next(); 
 
        // A random number below 100 
        int randomLessThan100 = random.Next(100); 
        Console.WriteLine(randomLessThan100); 
 
        // A random number within a range 
        int randomBetween100And500 = random.Next(100, 500); 
        Console.WriteLine(randomBetween100And500); 
 
        // Use other methods  
        RandomNumberGenerator generator = new RandomNumberGenerator(); 
        int rand = generator.RandomNumber(5, 100); 
        Console.WriteLine($"Random number between 5 and 100 is {rand}"); 
 
        string str = generator.RandomString(10, false); 
        Console.WriteLine($"Random string of 10 chars is {str}"); 
 
        string pass = generator.RandomPassword(); 
        Console.WriteLine($"Random password {pass}"); 
 
        Console.ReadKey(); 
    } 

 
public class RandomNumberGenerator 

    // Generate a random number between two numbers   
    public int RandomNumber(int min, int max) 
    { 
        Random random = new Random(); 
        return random.Next(min, max); 
    } 
 
// Generate a random string with a given size and case.  
// If second parameter is true, the return string is lowercase 
public string RandomString(int size, bool lowerCase) 

    StringBuilder builder = new StringBuilder(); 
    Random random = new Random(); 
    char ch; 
    for (int i = 0; i < size; i++) 
    { 
        ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); 
        builder.Append(ch); 
    } 
    if (lowerCase) 
        return builder.ToString().ToLower(); 
    return builder.ToString(); 

 
    // Generate a random password of a given length (optional) 
    public string RandomPassword(int size = 0) 
    { 
        StringBuilder builder = new StringBuilder(); 
        builder.Append(RandomString(4, true)); 
        builder.Append(RandomNumber(1000, 9999)); 
        builder.Append(RandomString(2, false)); 
        return builder.ToString(); 
    } 


The random string and random password looks like Figure 1.
Generate A Random Password In C# And .NET Core


Random password with given characters

Now, let’s say, you want to create a password that allows some specific characters only. The following code snippet in Listing 5 has a string of valid characters. The code uses this string to pick one character at a time for the password and stops at the given length. The default length of the password is 15.

private static string CreateRandomPassword(int length = 15) 

    // Create a string of characters, numbers, special characters that allowed in the password 
    string validChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*?_-"; 
    Random random = new Random(); 
 
    // Select one random character at a time from the string 
    // and create an array of chars 
    char[] chars = new char[length]; 
    for (int i = 0; i < length; i++) 
    { 
        chars[i] = validChars[random.Next(0, validChars.Length)]; 
    } 
    return new string(chars); 


Note
You can modify validChars string with the characters you allowed in the password.
Listing 6 is the complete program written in .NET Core.

using System; 
class Program 

    static void Main(string[] args) 
    {  
        Console.WriteLine(CreateRandomPassword()); 
        Console.WriteLine(CreateRandomPassword(10)); 
        Console.WriteLine(CreateRandomPassword(30)); 
 
        Console.WriteLine(CreateRandomPasswordWithRandomLength()); 
 
        Console.ReadKey(); 
    } 
 
 
    // Default size of random password is 15 
    private static string CreateRandomPassword(int length = 15) 
    { 
        // Create a string of characters, numbers, special characters that allowed in the password 
        string validChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*?_-"; 
        Random random = new Random(); 
 
        // Select one random character at a time from the string 
        // and create an array of chars 
        char[] chars = new char[length]; 
        for (int i = 0; i < length; i++) 
        { 
            chars[i] = validChars[random.Next(0, validChars.Length)]; 
        } 
        return new string(chars); 
    } 
 
    private static string CreateRandomPasswordWithRandomLength() 
    { 
        // Create a string of characters, numbers, special characters that allowed in the password 
        string validChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*?_-"; 
        Random random = new Random(); 
 
        // Minimum size 8. Max size is number of all allowed chars. 
        int size = random.Next(8, validChars.Length); 
 
        // Select one random character at a time from the string 
        // and create an array of chars 
        char[] chars = new char[size]; 
        for (int i = 0; i < size; i++) 
        { 
            chars[i] = validChars[random.Next(0, validChars.Length)]; 
        } 
        return new string(chars); 
    } 

 



ASP.NET Core 2.2.1 Hosting - HostForLIFE.eu :: Start Using HTTP Handlers In ASP.NET

clock September 19, 2018 11:48 by author Peter

First, let me explain the main purpose of using HTTPHandler. Sometimes you need to handle a specific request separately using a different method from that of a normal request. This article will explain HTTP Handler in a simple way. Let’s begin:
How can you handle any incoming HTTP request with a path “AllUsers/User.gif” by returning “Hello From HTTP Handler”.

  • Create a class file --  it could be MyHttpHandler.cs
  • Let MyHttpHandler class inherit from IhttpHandler Interface.
  • In MyHttpHandler class, implement all the methods which are found in IhttpHandler Interface.

You should do the following,
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
namespace MyProject { 
    public class MyHttpHandler: IHttpHandler { 
        public bool IsReusable { 
            get { 
                return true; 
            } 
        } 
        public void ProcessRequest(HttpContext context) { 
            HttpResponse response = context.Response; 
            response.Write("Hello From Http Handler"); 
        } 
    } 


The next step is to register the http handler in the web.config,

<httpHandlers> 
   <add verb="*" path="AllUsers/User.gif" type="MyProject.MyHttpHandler,MyProject"/> 
</httpHandlers> 


The above code (point 4) should be added as a child of <system.web>

That's all. Now HTTP Handler is ready

Section2
When using HTTP Handler with either MVC or WEB API, you will get the following error:


Because each MVC and WEB API are using routing to access methods within the controller, they will search the path and find that it is not found. To solve this problem you have two choices:

The first one is,

  • Create a class file --  it could be MyRouteHandler.cs
  • Let MyRouteHandlerclass inherit from IRouteHandlerInterface.
  • In MyRouteHandler class, implement all the methods which are found in IRouteHandlerInterface and return the MyHttpHandlerwhich are created in the previous section.

You should do the following,
public class MyRouteHandler: IRouteHandler { 
    public IHttpHandler GetHttpHandler(RequestContext requestContext) { 
        return new MyHttpHandler(); 
    } 


In RouteConfig class which is related to MVC and WEP API and responsible for requests routing, add the following line code to RegisterRoutes method and before the Default MapRoute.
routes.Add(new Route("AllUsers/User.gif", new MyRouteHandler())); 

Drop the HTTP Handler registration from web.config, since calling HTTP Handler will be from RegisterRoutes method.

The Second Solution Is:

Let us go back to section 1. It is a straightforward solution: In RouteConfig class which is related to MVC and WEP API and responsible for requests routing, add the following line of code to the RegisterRoutes method and before the Default MapRoute.
routes.IgnoreRoute("AllUsers/User.gif"); 

That's it.

Note
If you want to Handle all HTTP requests which have a specific extentaion such as gif you can using the following in web.config.
<httpHandlers> 
   <add verb="*" path="*.gif" type="MyProject.MyHttpHandler,MyProject"/> 
</httpHandlers> 

HostForLIFE.eu ASP.NET Core 2.2.1 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 2.2.1 Hosting - HostForLIFE.eu :: How to Unloading Assemblies in C#?

clock September 12, 2018 08:06 by author Peter

If you've created an Application Domain and want to unload all the assemblies loaded within, there is no way to unload Assembly themselves. But you can unload Application Domain you've just created.
 
In addition to that one;
You cannot unload the default Application Domain CLR created on its own. And unloading can differ from the assemblies being used and the unload events these assemblies have. It can take some time.
 
To Unload an Application Domain all you need to do is calling Unload function.
 
A sample code can help you understand:
    AppDomain myDom=AppDomain.Create("Ibrahims Domain"); 
    //Here assuming you loaded your assemblies 
    //To unload AppDomain call Unload Function 
    AppDomain.Unload(myDom); 
    // The Application Domain we've just created is now no more as the assemblies with it. 


After Unloading Application Domain object, we've also unloaded all the assemblies loaded within.

HostForLIFE.eu ASP.NET Core 2.2.1 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET Core 2.2.1 Hosting - HostForLIFE.eu :: How to Cross Domain ASP.NET Web API Calling Using jQuery AJAX ?

clock September 5, 2018 13:11 by author Peter

If we have made a Restful API utilizing the ASP.NET Core 2.2.1 Web API and if your API is in one space and the UI is in an alternate area then you may get problem because of cross-domain issues. And here is the way:

  • OPTIONS http://localhost:5000/api/ 404 (Not Found).XMLHttpRequest cannot load http://localhost:5000/api/.
  • No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:54317' is therefore not allowed access. The response had HTTP status code 404.

As it were you can't make a call to the WebAPI by means of your front end that is facilitated on an alternate domain.
So you must utilization JSONP to get information utilizing using AJAX, not by JSON.  To attain to this objective you have to introduce JsonpMediaTypeFormatter. For introducing the JsonpMediaTypeFormatter in Visual Studio, seek JsonpMediaTypeFormatter in "Manage NuGet Packages" and install it.

Next, you can see in your project references that a new DLL was added. WebApiContrib.Formatting.Jsonp.dll

To use this DLL you need to change in the Application_Start() method in the Global.asax.cs file.
using WebApiContrib.Formatting.Jsonp;   
using System.Net.Http.Formatting;   

GlobalConfiguration.Configuration.Formatters.Clear();   GlobalConfiguration.Configuration.Formatters.Add(new JsonpMediaTypeFormatter(new JsonMediaTypeFormatter())); 

You also can use JsonMediaTypeFormatter code, you should write this code in the App_Start folder & register the following code in Application_Start().
JsonMediaTypeFormatter code:
    using System;   
    using System.Collections.Generic;   
    using System.Linq;   
    using System.Web;   
    using System.Net.Http.Formatting;   
    using System.Net.Http.Headers;   
    using System.Net.Http;   
    using Newtonsoft.Json.Converters;   
    using System.IO;   
    using System.Net;   
    using System.Threading.Tasks;   
    namespace WebAPI   
    {   
        /// <summary>   
        /// Handles JsonP requests when requests are fired with text/javascript   
        /// </summary>   
        public class JsonpFormatter : JsonMediaTypeFormatter   
        {   
            public JsonpFormatter()   
            {   
                SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));   
                SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));           
                JsonpParameterName = "callback";   
            }   
            /// <summary>   
            ///  Name of the query string parameter to look for   
            ///  the jsonp function name   
            /// </summary>   
           public string JsonpParameterName { get; set; }   
           /// <summary>   
            /// Captured name of the Jsonp function that the JSON call   
            /// is wrapped in. Set in GetPerRequestFormatter Instance   
            /// </summary>   
            private string JsonpCallbackFunction;
            public override bool CanWriteType(Type type)   
            {   
                return true;   
            }           
            /// <summary>   
            /// Override this method to capture the Request object   
            /// </summary>   
            /// <param name="type"></param>   
            /// <param name="request"></param>   
            /// <param name="mediaType"></param>   
            /// <returns></returns>   
            public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)   
            {   
                var formatter = new JsonpFormatter()   
                {   
                    JsonpCallbackFunction = GetJsonCallbackFunction(request)   
                };   
               // this doesn't work unfortunately   
                //formatter.SerializerSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;   
                // You have to reapply any JSON.NET default serializer Customizations here       
                formatter.SerializerSettings.Converters.Add(new StringEnumConverter());   
                formatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;           
                return formatter;   
            }                   
           public override Task WriteToStreamAsync(Type type, object value,   
                                            Stream stream,   
                                            HttpContent content,   
                                            TransportContext transportContext)   
            {   
                if (string.IsNullOrEmpty(JsonpCallbackFunction))   
                    return base.WriteToStreamAsync(type, value, stream, content, transportContext);   
                        StreamWriter writer = null;           
                // write the pre-amble   
                try   
                {   
                    writer = new StreamWriter(stream);   
                    writer.Write(JsonpCallbackFunction + "(");   
                    writer.Flush();   
                }   
                catch (Exception ex)   
                {   
                    try   
                    {   
                        if (writer != null)   
                            writer.Dispose();   
                    }   
                   catch { }           
                    var tcs = new TaskCompletionSource<object>();   
                    tcs.SetException(ex);   
                    return tcs.Task;   
                }           
                return base.WriteToStreamAsync(type, value, stream, content, transportContext)   
                           .ContinueWith(innerTask =>   
                           {   
                               if (innerTask.Status == TaskStatus.RanToCompletion)   
                               {   
                                   writer.Write(")");   
                                   writer.Flush();   
                               }   
                               writer.Dispose();   
                               return innerTask;   
                           }, TaskContinuationOptions.ExecuteSynchronously)   
                                .Unwrap();   
            }   
                    /// <summary>   
            /// Retrieves the Jsonp Callback function   
            /// from the query string   
           /// </summary>   
           /// <returns></returns>   
            private string GetJsonCallbackFunction(HttpRequestMessage request)   
            {   
                if (request.Method != HttpMethod.Get)   
                    return null;   
                        var query = HttpUtility.ParseQueryString(request.RequestUri.Query);   
                var queryVal = query[this.JsonpParameterName];   
                        if (string.IsNullOrEmpty(queryVal))   
                    return null;           
                return queryVal;   
            }   
        }   
    } 

Next step, use the following code to make change in the Application_Start() method in the Global.asax.cs file.
GlobalConfiguration.Configuration.Formatters.Insert(0, new WebAPI.JsonpFormatter());


jQuery code to use the Web API:
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>   
    <script language="javascript" type="text/javascript">   
        function GetInformation() {   
            var apiServicePath = "http://localhost:5000/api/";   
            jQuery.ajax({   
                crossDomain: true,  
                dataType: "jsonp",   
                url: apiServicePath + "test/GetInformation",   
                async: false,   
                context: document.body   
            }).done(function (data) {   
                alert("Done");   
            });   
        };   
    </script> 

 

HostForLIFE.eu ASP.NET Core 2.2.1 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in