Send WhatsApp message using C#


Install WhatsApp API for .Net using Nuget packages.

string from = “your mobile no”;
string to = mobile no;
string msg = message you want to send;

WhatsApp wb = new WhatsApp(from, “5fhcyKV94jCWepiMkiATXWxV4dQ=”, “Nick name”, false, false);

wb.OnConnectSuccess += () =>
{
MessageBox.Show(“Connected to whatsapp…”);

wb.OnLoginSuccess += (phoneNumber, data) =>
{
wb.SendMessage(to, msg);
MessageBox.Show(“Message sent..”);
};

wb.OnLoginFailed += (data) =>
{
MessageBox.Show(“Login failed :{0}”, data);
};

wb.Login();
};

wb.OnConnectFailed += (ex) =>
{
MessageBox.Show(“Connection failed :{0}”, ex.Message);
};

wb.Connect();

Create Custom Authorization Filter using MVC


public class CustomAuthFilter : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (check if Unauthorised)
{
// do your stuff
filterContext.HttpContext.Response.Redirect(“~/Unauthorised/Index”);

}
}
}

and then you can use in controller for authorizing your ActionResult using [CustomAuthFilter]

Advantage of using async Action in MVC


[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

public ActionResult Login(LoginViewModel model)

{

if (ModelState.IsValid)

{

IdentityResult result = IdentityManager.Authentication.CheckPasswordAndSignIn(AuthenticationManager, model.UserName, model.Password, model.RememberMe);

if (result.Success)

{

return Redirect(“~/home”);

}

else

{

AddErrors(result);

}

}

return View(model);

}

 

 

[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

public asyncTask<ActionResult>Login(LoginViewModel model)

{

if(ModelState.IsValid)

{

IdentityResult result= awaitIdentityManager.Authentication.CheckPasswordAndSignInAsync(AuthenticationManager, model.UserName, model.Password, model.RememberMe);

if(result.Success)

{

returnRedirect(“~/home”);

}

else

{

AddErrors(result);

}

}

returnView(model);

}

 

Advantage of using async

The async actions are useful only when you are performing I/O bound operations such as remote server calls. The benefit of the async call is that during the I/O operation, no ASP.NET worker thread is being used.

 

So here’s how the first example works:

  • When a request hits the action, ASP.NET takes a thread from the thread pool and starts executing it. Then method is invoked, during the entire call the worker thread is being risk.

The second call works:

  • When a request hits the action, ASP.NET takes a thread from the thread pool and starts executing it, And returns immediately. An I/O Completion Port is registered and the ASP.NET worker thread is released to the thread pool.
  • Later when the operation completes, the I/O Completion port is signaled, another thread is drawn from the thread pool to finish returning the view.

 

As you can see in the second case ASP.NET worker threads are used only for a short period of time. This means that there are more threads available in the pool for serving other requests. use async actions only when you have a true async API inside.

 

 

 

IEnumerable vs IQueryable


IEnumerable

IQueryable

1.     IEnumerable exists in System.Collections Namespace. 1.     IQueryable exists in System.Linq Namespace.
1.     IEnumerable can move forward only over a collection, it can’t move backward and between the items. 1.     IQueryable can move forward only over a collection, it can’t move backward and between the items.
1.     IEnumerable is best to query data from in-memory collections like List, Array etc. 1.     IQueryable is best to query data from out-memory (like remote database, service) collections.
1.     While query data from database, IEnumerable execute select query on server side, load data in-memory on client side and then filter data. 1.     While query data from database, IQueryable execute select query on server side with all filters.
1.     IEnumerable is suitable for LINQ to Object and LINQ to XML queries. 1.     IQueryable is suitable for LINQ to SQL queries.
1.     IEnumerable supports deferred execution. 1.     IQueryable supports deferred execution.
1.     IEnumerable doesn’t supports custom query. 1.     IQueryable supports custom query using CreateQuery and Execute methods.
1.     IEnumerable doesn’t support lazy loading. Hence not suitable for paging like scenarios. 1.     IQueryable support lazy loading. Hence it is suitable for paging like scenarios.
1.     Extension methods supports by IEnumerable takes functional objects. 1.     Extension methods supports by IQueryable takes expression objects means expression tree.

IEnumerable Example

DataContext dc = new DataContext ();

IEnumerable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith(“G”));

list = list.Take<Employee>(10);

Generated SQL statements of above query will be :

SELECT [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] where [t0].[EmpName] LIKE @p0

Notice that in this query “top 10″ is missing since IEnumerable filters records on client side

IQueryable Example

IQueryable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith(“G”));

list = list.Take<Employee>(10);

SELECT TOP 10 [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] where [t0].[EmpName] LIKE @p0

Notice that in this query “top 10″ is exist since IQueryable executes query in SQL server with all filters.

Lazy Loading?

Lazy loading is a concept where we delay the loading of the object until the point where we need it. Putting in simple words, on demand object loading rather than loading objects unnecessarily.

In .NET we have the Lazy<T> class which provides automatic support for lazy loading.

Advantages of lazy loading:

  • Minimizes start up time of the application.
  • Application consumes less memory because of on-demand loading.
  • Unnecessary database SQL execution is avoided.

Eager loading?.

So in eager loading we load all the objects in memory as soon as the object is created.

Collections in C#


Various Collection Classes and Their Usage

The following are the various commonly used classes of the System.Collection namespace.

  1. Array List :It represents ordered collection of an object that can be indexed individually.It is basically an alternative to an array. However unlike array you can add and remove items from a list at a specified position using an index and the array resizes itself automatically. It also allows dynamic memory allocation, add, search and sort items in the list.
    using System;
    using System.Collections;
    
    namespace CollectionApplication
    {
        class Program
        {
            static void Main(string[] args)
            {
                ArrayList al = new ArrayList();
    
                Console.WriteLine("Adding some numbers:");
                al.Add(45);
                al.Add(78);
                al.Add(33);
                al.Add(56);
                al.Add(12);
                al.Add(23);
                al.Add(9);
                
                Console.WriteLine("Capacity: {0} ", al.Capacity);
                Console.WriteLine("Count: {0}", al.Count);
                          
                Console.Write("Content: ");
                foreach (int i in al)
                {
                    Console.Write(i + " ");
                }
                Console.WriteLine();
                Console.Write("Sorted Content: ");
                al.Sort();
                foreach (int i in al)
                {
                    Console.Write(i + " ");
                }
                Console.WriteLine();
                Console.ReadKey();
            }
        }
    }
    Adding some numbers:
    Capacity: 8 //Gets or sets the number of elements that the ArrayList can contain.
    Count: 7 //Gets the number of elements actually contained in the ArrayList.
    Content: 45 78 33 56 12 23 9
    Content: 9 12 23 33 45 56 78
  2. Hashtable:It uses a key to access the elements in the collection.A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection.
    using System;
    using System.Collections;
    
    namespace CollectionsApplication
    {
       class Program
       {
          static void Main(string[] args)
          {
             Hashtable ht = new Hashtable();
    
    
             ht.Add("001", "Madan Gopal");
             ht.Add("002", "Gopal Rohila");
             ht.Add("003", "Goe Rohile");
             ht.Add("004", "Madan Gopal Rohila");
             ht.Add("005", "M. gopal");
             ht.Add("006", "M. rohila");
             ht.Add("007", "this is gopal");
    
             if (ht.ContainsValue("Madan Gopal"))
             {
                Console.WriteLine("This student name is already in the list");
             }
             else
             {
                ht.Add("008", "aashi");
             }
             // Get a collection of the keys. 
             ICollection key = ht.Keys;
    
             foreach (string k in key)
             {
                Console.WriteLine(k + ": " + ht[k]);
             }
             Console.ReadKey();
          }
       }
    }
    001: Madan Gopal
    002: Gopal Rohila
    003: Goe Rohile
    004: Madan Gopal Rohila
    005: M. gopal
    006: M. rohila
    007: this is gopal
    
  3. SortedList.The SortedList class represents a collection of key-and-value pairs that are sorted by the keys and are accessible by key and by index.A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value.
    class Program
       {
          static void Main(string[] args)
          {
             SortedList sl = new SortedList();
    
             sl.Add("001", "Madan Gopal");
             sl.Add("002", "Gopal Rohila");
             sl.Add("003", "Aashi rohila");
            
    
             if (sl.ContainsValue("Goe"))
             {
                Console.WriteLine("This student name is already in the list");
             }
             else
             {
                sl.Add("004", "Goe");
             }
    
             // get a collection of the keys. 
             ICollection key = sl.Keys;
    
             foreach (string k in key)
             {
                Console.WriteLine(k + ": " + sl[k]);
             }
          }
       }
    001: Madan Gopal
    002: Gopal Rohila
    003: Aashi Rohila
    004: Goe
  4. Stack.It represents a last-in, first out collection of object.It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item.
    class Program
        {
            static void Main(string[] args)
            {
                Stack st = new Stack();
    
                st.Push('A');
                st.Push('M');
                st.Push('G');
                st.Push('W');
                
                Console.WriteLine("Current stack: ");
                foreach (char c in st)
                {
                    Console.Write(c + " ");
                }
                Console.WriteLine();
                
                st.Push('V');
                st.Push('H');
                Console.WriteLine("The next poppable value in stack: {0}", 
                st.Peek());
                Console.WriteLine("Current stack: ");           
                foreach (char c in st)
                {
                   Console.Write(c + " ");
                }
                Console.WriteLine();
    
                Console.WriteLine("Removing values ");
                st.Pop();
                st.Pop();
                st.Pop();
                
                Console.WriteLine("Current stack: ");
                foreach (char c in st)
                {
                   Console.Write(c + " "); 
                }
            }
        }
    Current stack: 
    W G M A
    The next poppable value in stack: H
    Current stack: 
    H V W G M A
    Removing values
    Current stack: 
    G M A
  5. Queue. It represents a first-in, first out collection of object.It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue and when you remove an item, it is called deque.
    class Program
       {
          static void Main(string[] args)
          {
             Queue q = new Queue();
    
             q.Enqueue('A');
             q.Enqueue('M');
             q.Enqueue('G');
             q.Enqueue('W');
             
             Console.WriteLine("Current queue: ");
             foreach (char c in q)
                Console.Write(c + " ");
             Console.WriteLine();
             q.Enqueue('V');
             q.Enqueue('H');
             Console.WriteLine("Current queue: ");         
             foreach (char c in q)
                Console.Write(c + " ");
             Console.WriteLine();
             Console.WriteLine("Removing some values ");
             char ch = (char)q.Dequeue();
             Console.WriteLine("The removed value: {0}", ch);
             ch = (char)q.Dequeue();
             Console.WriteLine("The removed value: {0}", ch);
             Console.ReadKey();
          }
       }
    Current queue: 
    A M G W 
    Current queue: 
    A M G W V H 
    Removing values
    The removed value: A
    The removed value: M
  6. BitArray. It represents an array of the binary representation using the values 1 and 0. It is used when you need to store the bits but do not know the number of bits in advance. You can access items from the BitArray collection by using an integer index, which starts from zero.
    static void Main(string[] args)
            {
                //creating two  bit arrays of size 8
                BitArray ba1 = new BitArray(8);
                BitArray ba2 = new BitArray(8);
                byte[] a = { 60 };
                byte[] b = { 13 };
                
                //storing the values 60, and 13 into the bit arrays
                ba1 = new BitArray(a);
                ba2 = new BitArray(b);
    
                //content of ba1
                Console.WriteLine("Bit array ba1: 60");
                for (int i = 0; i < ba1.Count; i++)
                {
                    Console.Write("{0, -6} ", ba1[i]);
                }
                Console.WriteLine();
                
                //content of ba2
                Console.WriteLine("Bit array ba2: 13");
                for (int i = 0; i < ba2.Count; i++)
                {
                    Console.Write("{0, -6} ", ba2[i]);
                }
                Console.WriteLine();
               
                
                BitArray ba3 = new BitArray(8);
                ba3 = ba1.And(ba2);
    
                //content of ba3
                Console.WriteLine("Bit array ba3 after AND operation: 12");
                for (int i = 0; i < ba3.Count; i++)
                {
                    Console.Write("{0, -6} ", ba3[i]);
                }
                Console.WriteLine();
    
                ba3 = ba1.Or(ba2);
                //content of ba3
                Console.WriteLine("Bit array ba3 after OR operation: 61");
                for (int i = 0; i < ba3.Count; i++)
                {
                    Console.Write("{0, -6} ", ba3[i]);
                }
                Console.WriteLine();
                
                Console.ReadKey();
            }
    Bit array ba1: 60 
    False False True True True True False False 
    Bit array ba2: 13
    True False True True False False False False 
    Bit array ba3 after AND operation: 12
    False False True True False False False False 
    Bit array ba3 after OR operation: 61
    True False True True False False False False

Count and Limit Maximum characters of a TextBox


<script language=”javascript” type=”text/javascript”>
function limitText(limitField, limitCount, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
} else {
limitCount.value = limitNum – limitField.value.length;
}
}
</script>

<!– Html Code –>

<textarea name=”limitedtextarea” onKeyDown=”limitText(this.form.limitedtextarea,this.form.countdown,100);”
onKeyUp=”limitText(this.form.limitedtextarea,this.form.countdown,100);”>
</textarea><br>
<font size=”1″>(Maximum characters: 100)<br>
You have <input readonly type=”text” name=”countdown” size=”3″ value=”100″> characters left.</font>

 

 

How to disable right click in asp.net, C# using javascript


Add this attribute to the BODY Tag to disable the right click menu everywhere on the page.

<body oncontextmenu=”return false;”>

If you want disable dragging of images and text selection, add this attribute to the BODY Tag.

<body ondragstart =”return false;”>

Below this script is to disable right click menu and dragging of images and text selection for all browsers.

<script type=”text/javascript”>
function md(e) {
try { if (event.button == 2 || event.button == 3) return false; }
catch (e) { if (e.which == 3) return false; }
}
document.oncontextmenu = function () { return false; }
document.ondragstart = function () { return false; }
document.onmousedown = md;
</script>

Authenticate using Social Logins


Last some days i was working in Plugin development, i want to create a custom module of Login Authentication via social logins for my CMS (asp.net). but i am confused about because i research on net about social logins providers like gigya, janrain, loginradius so finally i decided to implement loginradius for my CMS and believe its a so easy to implement and it has great security and good functionality so finally i complete my plugin with the help of Loginradius and ofcourse LoginRadius team helps me so much. and i feel any body will try this at once.

How to make a computer faster?


By following a few simple guidelines, you can maintain your computer, help increase your PC speed, and help keep it running smoothly.

Here are some suggestions.

  1. Remove spyware (http://www.michaelhorowitz.com/removespyware.html).
  2. Use Disk Cleanup to:
    • Remove temporary Internet files.
    • Delete downloaded program files, such as Microsoft ActiveX controls and Java applets.
    • Empty the Recycle Bin.
    • Remove Windows temporary files, such as error reports.
    • Delete optional Windows components that you don’t use.
    • Delete installed programs that you no longer use.
    • Remove unused restore points and shadow copies from System Restore.
  3. you can use ReadyBoost to speed up your system. A new concept in adding memory to a system, it allows you to use non-volatile flash memory—like a USB flash drive or a memory card—to improve performance without having to add additional memory.
  4. Empty Recycle Bin. You can use c cleaner (http://www.piriform.com/ccleaner/download).
  5. Clean you registry using c cleaner. but make sure before you clean save your previous registry.
  6. You may want to disable rarely used peripherals or hardware services. and also Windows update.
  7. Remove extra and unused Software’s in you system.
  8. You may disable unused services like windows defender and windows firewall.
  9. Keep as less programs as possible running on the System Tray. This essentially means reducing the number of programs that start during Windows start up.
  10. Remove background processes: The computer is always carrying out processes that are not visible as programs on the Desktop or the Taskbar. They come both from application software and from Windows. They are not overtly obvious and are said to run in the background. Many of them are essential functions but some may be useless (or even harmful if malware is involved).
  11. Remove unused Messenger services if you are using.
  12. Clear your Internet Explorer cache.
  13. Consider using a lower resolution, or a lower color depth for your monitor.
  14. Disable Animations and Appearance Overhauls to maximize performance : Go to System Properties in the Control Panel. Click ‘Advanced’, then ‘Performance’ and click ‘Adjust for best performance’. This might boost your PC’s performance up a bit.
  15. Don’t keep installing software. Install a program only if it really serves you a purpose.

please let me know if these informations is not useful!

Follow

Get every new post delivered to your Inbox.