Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, March 01, 2017

How to set storage account connection string in Azure Functions

Hi,

I was developing an Azure Function App that connects to an Azure blob storage. After setting up the binding for my blob storage account. I got the following error message when running my function app:







The error message in the screen shot above suggests three options to fix this. I will walk through how to implement the first option as one of the available solutions. The first solution is to set the connection string name in the appsettings.json file so it will look like this.

appsettings.json
{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "AzureWebJobsDashboard": "",
    "AzureWebJobsmofunctions_STORAGE": "DefaultEndpointsProtocol=https;AccountName=mofunctions;AccountKey=KEY"
  }
}

function.json (Just a section where i define my blob binding info)

 {
      "type": "blob",
      "name": "iBlob",
      "path": "mydata/file1.csv",
      "connection": "mofunctions_STORAGE",
      "direction": "in"
    }

NOTE: 
You will notice that the connection name value in function.json is a suffix for AzureWebJobs key in the appsettings.json file.


Once you set this, Press F5 and you will be able to connect and read blob contents from Azure storage accounts.



Enjoy!

Wednesday, August 17, 2016

How to read images from a URL in asp.net core

Hi,

I was building an asp.net core web api that suppose to read images from an external url. Even though i have done this dozens of time. I got stuck for a bit trying to have the same code that reads an image from a url into my asp.net core project using Visual Studio 2015.

After little bit of searching, i found out that before trying to read a static file such as an image from your controller. you need to enable first Directory browsing and configure routing path so you are able to view this image in a browser by hitting the url of the image.


So, follow these below steps to be able to read images from a url (in my case these images were part of project):

1) Move images folder (or any static files folder) under wwwroot folder.
2) Open startup.cs file and enable directory browsing.


C# code to enable directory browsing and serving static files:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            app.UseApplicationInsightsRequestTelemetry();
            app.UseApplicationInsightsExceptionTelemetry();

            // Enable directory browsing
            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(
           Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
                RequestPath = new PathString("/images")
            });
         
            app.UseDirectoryBrowser(new DirectoryBrowserOptions()
            {
                FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
                RequestPath = new PathString("/images")
            });

            app.UseMvc();
        }

3) Run your app and try to load an image from the browser, for example:
http://localhost:12354/images/test1.jpg

4) You will be able to view the image in the browser. now, let's read image in C# from a url.

 // read from remote image drive
                    using (HttpClient c = new HttpClient())
                    {
                        using (Stream s = await c.GetStreamAsync(imgUrl))
                        {
                             // do any logic with the image stream, save it, store it...etc.
                        }
                    }

If you haven't done step #3 (This is were i got stuck!), the GetStreamAsync method will throw an exception (404 not found) error because we haven't configured the app to deliver static files.

Hope this helps!

References:
1) Working with static files in asp.net core:
https://docs.asp.net/en/latest/fundamentals/static-files.html#enabling-directory-browsing

Wednesday, June 10, 2015

How to start mobile apps development using Cordova in Visual Studio 2013/2015


I am writing this blog to show how to start developing cross platform mobile native applications using Cordova.

Cordova is a platform for building native mobile applications using HTML, CSS and JavaScript. It is an open source platform which means it is free to download and start building cross platform native applications using standard web technologies skills set.

If you would like to read more about Cordova project and its capabilities, here is the Cordova project homepage: https://cordova.apache.org/

Microsoft has started to integrate Cordova into VS 2013 and VS 2015. In this blog post i am showing how to start working with Cordova in VS 2013 by getting all the tools in step by step fashion.

Once you open VS2013, Click on Start a new project.

Under JavaScript Template, Select Multi-Device Hybrid App, then double click on Install Tools for Apache Cordova.



This will open up a new browser windows to start installing all the tools. download the executable file.




Next, Make sure to close VS before start installing Apache Cordova for VS 2013 tools (vs2013mda_0.3.1.exe)



Open up VS again, You will find a blank App (Apache Cordova) project template in VS 2013!


Hope this helps!

UPDATE 06/12/2015: Microsoft recommends to use VS 2015 for all Cordova applications because VS 2015 is using a new project structure to support third party CLIs, while VS 2013 is still using the old/deprecated project structure.


Tuesday, April 01, 2014

Working Tips with SPWebConfigModification Class in SharePoint 2013

Hi Folks,

I was working on updating a SharePoint web.config programmatically in SharePoint 2013 Farm Solution. Applying web.config modifications in SharePoint is straight forward task by adding the modifications into a collection of the web application and then submit your changes.

Since this class is poorly documented, I was trying to update a specific web application web.config and not all web.config in this farm. all the code samples in MSDN and other blogs don't provide a necessary understanding how it works so before taking the MSDN code and apply it into your feature or wsp you should know the following essential tips:

1) You can apply your web config modifications either on the web application level or the content service level which affects all web config files in your farm.

2) When your code has the following line of code, this means that the changes will be taken effect into all web applications in the farm:

SPWebApplication webApp = new SPSite('siteUrl').WebApplication;
WebApp.Farm.Services.GetValue<SPWebService>.ApplyWebConfigModifications();

Even though you are using a web application object, but this code will update all web.config files, which you should avoid when you apply solutions unless you are applying Farm updates.


3) If you want to update a specific web application web.config:

SPWebApplication webApp = new SPSite('siteUrl').WebApplication;
WebApp.Update();  // update specific web.config for this web application
webApp.WebService.ApplyWebConfigModifications();


line #3 will only update the web.config for a specific web application and not all unlike
SPWebService.ContentService.ApplyWebConfigModifications();

Hope this helps!

**References:
1) Add or remove entries in web.config programmatically:
http://msdn.microsoft.com/en-us/library/bb861909(v=office.14).aspx



Wednesday, June 12, 2013

Windows Phone 8 Get Started and in-depth topics - TechEd NA 2013

Hi everyone,

If you haven't attended TechEd North America 2013 and you are a windows phone developer, This blog post is for you.

I was looking to see all windows phone 8 sessions so i can check them on my own time, I found this blog post that has all videos for windows phone 8 in TechEd 2013.

Take a look and enjoy.


http://blogs.windows.com/windows_phone/b/wpdev/archive/2013/06/06/teched-north-america-2013-summary.aspx

-ME

Tuesday, April 16, 2013

Few tips to know when considering developing MVC4 Applications in VS 2012 - Part 1

Hi Folks,

I'm writing this blog post for ASP.NET web forms developers who have been working with Web forms for years and they are hesitant to develop MVC 4 ASP.NET applications; maybe for different reasons either it is not easy to understand or there are a lot of things you need to wrap your head around to get started building your first business application!

So i decided to write these series of posts,I will try to makes it easier for you to get started in MVC 4 applications with few tips that will help you know how it works and some other considerations to think about.

1) Basic Concepts of the MVC design pattern:
In MVC design pattern implementation by Microsoft, any page you see in the browser is a view, it can be a page or a user control. it can be aspx,ascx or cshtml. MVC has introduced cshtml which is the new render engine called RAZOR, this engine allows you to wirte cs code within your html elements by prefexing any C# Code by @ symbol. For example:
 
<div>@Html.ActionLink("Home", "Index", "Home")</div>

The above line is rendered by Razor as a link with a caption called Home and Index is the method will be called in the Home Controller.

2) Controllers:
All controllers in MVC 4 are stored under a folder called controllers, if you want to create a new controller, right click on this folder and select add new controller and the new controller will be created with all functions if you picked the model "Table" you want to target for this controller.
All controllers MUST have Controller suffix.
Usually you have one controller per 1 entity, but you can design your controllers as you want.
Any action in any view should be mapped to a method in a controller, and the controller takes care of the execution and return the results to the view. That's why you see all controllers can return a view that could be a page or partial page, file, redirect, or Empty.
Check out this link for the types of result you could get from any controller method call:
http://msdn.microsoft.com/en-us/library/system.web.mvc.actionresult(v=vs.108).aspx


3) No Master page in the MVC4 web project:

You will not see a default master page in your project, the general look and feel in the project is controlled by a "Shared View", This Shared View acts as Master Page in the web forms.

If you want to modify the shared view, it is under Shared View Folder --> _layout.cshtml

You still can add a master page to your project  and link all your views to it.

4) Connecting to a database/ Creating your Model:
Model is your database/datasource file in the project. First thing you should do before creating any controllers or views is to create your entity model for your project.
There is no change in this regard. Just add any data entity file that you are familiar with such as: Entity Framework, Entity Data Model, LINQ or SQL Compact Db files.

After creating your model, you can add your controllers since the MVC 4 gives your the ability to create all your CRUD operations once you pick your entity/model and context "dbml or any data source file"


I want to keep it short and simple, I will keep posting more parts in details for building your first MVC 4 application.

Thanks and drop a line if you have any questions or feedback!


Regards,
Mostafa









Friday, April 12, 2013

WCF Error: The underlying connection was closed: The connection was closed unexpectedly.

Hi Folks,

While i was developing a WCF service API for my enterprise application, I got an error while i'm calling a search function in the WCF. The WCF function is calling a stored procedure.

I tested the stored procedure and there is no issues with it at all, and the error was being thrown in my web when the data is being serialized and sent over the network.

The error message:

The underlying connection was closed: The connection was closed unexpectedly.

The point here is that i have other functions in the WCF work perfectly with no errors but only the search function is throwing an exception.

So, it is not configuration thing, it is something else i want to nail it down!

The only way to get the actual error message from calling a WCF service, is to install a tool called "Microsoft Service Trace Viewer" . Here is the download link:
http://www.microsoft.com/en-us/download/details.aspx?id=3138


After you install it, add the following section in the web.config before the closing of the configuration attribue:

<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
<listeners>
<add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData= "traces.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>

Run your applicaiton, and execute the action that throws the exception then do the following:
1) Open the following path:
C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin

2) Double click on SvcTraceViewer.exe tool

3) From the File Menu, Click on Open.

4) Navigate to your project folder and you will find a file called: traces.svclog, select this file.

5) Check the actual WCF call that causes the error from the activity window and then see the details of the error in the right pane.




Hope this helps.
 

Friday, March 29, 2013

How to enable MS Dynamics CRM 2011 to integrate with Windows Azure

Hi,

I'm writing this article to explain a good architecture design for integrating your Microsoft Dynamics CRM 2011 with windows azure.

Let's  say you have on-premise CRM 2011 instance, and you want to use Windows Azure Blob storage to store Customer's documents on the cloud. How would you do that ?

The example i'm giving is applicable to any other windows azure service such as: SQL Azure, Mobile Notification Service, AppFabric Features..etc.

Since Windows azure is a scalable Cloud platform, you can easily integration your CRM 2011 with the windows azure on the cloud in 4 main steps.

Before going through the details, I'd like to explain the architecture of the proposed solution.

MS CRM 2011 has a backend windows service called "CRM Asynchronous Service" this is the component that will be in charge to communicate with the windows azure through a service bus.

MS CRM 2011 has 2 types of plugins, out-of-the box (OOB) and custom plugins. The OOB plugins runs  with full trust but the custom plugins runs with partial trust, and we will develop a custom plugin to connect to a listener through azure service bus.

The solution has the following components:

1) Configure CRM to be Windows Azure Aware.

2) We need to configure a service bus on Azure with an endpoint to communicate with the CRM server.

3) A listener hosted in Windows Azure to communicate with the asyncrhounous service, specificially listening to CRM assembly "Microsoft.Xrm.Sdk" with RemoteExecuteContext defined. so we need to develop a listener and deploy it on windows azure.

4) A custom CRM Plugin to communicate with the Windows Azure Listener.


How To accomplish, configure and develop this solution:

1) To accomplish step 1 , "Configure CRM for Integration with Windows Azure" :
http://technet.microsoft.com/en-us/library/gg328249.aspx

2) To accomplish step 2, "Configure Windows Azure ACS on Azure" :
http://technet.microsoft.com/en-us/library/jj863635.aspx

3) How to write a windows azure listener:
http://technet.microsoft.com/en-us/library/gg309615.aspx

C# Sample code - Listener:
http://technet.microsoft.com/en-us/library/gg309657.aspx

4) To accomplish step 4, "How to write Azure Aware CRM Plugin":
http://technet.microsoft.com/en-us/library/gg328194.aspx

Note, if you want to develop a custom workflow activity:
http://technet.microsoft.com/en-us/library/gg327854.aspx

Registration step - FINAL:
http://technet.microsoft.com/en-us/library/gg328524.aspx


**Here is some sample code for all what i mentioned above "listeners & plugins":
http://technet.microsoft.com/en-us/library/gg334712.aspx

Note: you should be having CRM SDK and Windows Azure SDK 1.7 or higher to be able to exercise and develop the solution.

Hope this helps.


Reference:
-Azure Extensions for Microsoft Dynamics CRM 2011:
http://technet.microsoft.com/en-us/library/gg309276.aspx



 

Tuesday, March 19, 2013

What do you expect from Entity Framework 6 Alpha ?

Hi,
 
I was reading the MSDN magazine March 2013 and i found an article by Julie Lerman about EF 6 Alpha features.
 
If you haven't had the chance to read the article, here is a summary of this article for .NET developers and architects:
 
1)      EF 6 will be supporting multiple schemas. So in your dbml file you will be able to reference and import multiple schemas in your database.
 
Julie has written a detailed article about this feature, here is the link for this:
 
2)      EF6 will be supporting the asynchronous processing (Async).
Since we have Asynchronous pattern supported in .NET 4.5. The EF 6 will be bringing some of these features by having: SaveChangesAsync(), ExecuteSqlCommandAsync and FindAsync() functions that don't block the UI while executing and you will be able to write asynchronous code in your application in EF 6.
 
For Linq to Entities, they have added bunch of other Async methods for enumerations such as: ToListAsync(), FirstOrDefaultAsync(), MaxAsync().
 
This is a very important feature especially for Silverlight, WPF and Windows Phone developers in addition to web developers.
 
3)      Enum and Spatial support
EF 6 will be supporting enums and Spatial data types. Unlike earlier version where dependent on the .NET framework you are using/targeting. The new EF 6 will be supporting this no matter which .NET framework you are targeting. So you can use enums and spatial support even you are targeting .NET 4.0 framework that doesn’t support certain EF 6 features.
 
Hope this helps.

Monday, March 11, 2013

Conditional using statement in C# debug versus Release

Hi Folks,

I'm writing this blog post to share how to write conditional using statements in C#. The meaning of this is how to use using statements in Debug mode versus Release mode in reference to different dlls. This is needed when you are using any testing/sandbox DLLs that use any non production environment and you want your code to use other reference when you build a Release for your application in reference to production dlls.

The below code is using In-App Purchase library for Windows Phone 8.

C# Code:

#if DEBUG
using MockIAPLib;
using Store = MockIAPLib;
#else
using Windows.ApplicationModel.Store;
#endif
Notice: you give the same alias name for the testing Libaray namespace as the one that will be used in production so you don't need to re-write your code.

Then, you can use any class for the referenced namespace:

ProductListing p = new ProductListing();


Tip: You should select Release before your deploy your application to products so the application will refer to the production assemblies and not the ones are used in the debug mode.


Hope this tip helps!

 

Tuesday, January 22, 2013

Adding Custom Propeties to EF 4.0 that doesn't exist in the DB model

Hi Folks,

I was extending my EF 4.0 model by having custom propeties that don't exist in my DB, Since EF 4.0 doesn't support adding custom properties if it doesn't exist in the DB, I found a workaround for that by creating a partial class with my custom properties in it.
 

public partial class myEntityName: EntityObject

{

     
[DataMemberAttribute()]
public string customerName{ get; set; }

[DataMemberAttribute()]
public int customerCode{ get; set; }

}


Implementing this workaround will help you to add any properties you would like to add in your EF 4.0 entities.


You might encounter this error since you are adding properties to your entity that doesn't exist in the edm file:

"The number of members in the conceptual type does not match with the number of members on the object side type .Make sure the number of members are the same."

The fix for error; Remove "EdmScalarPropertyAttribute" attribute from your custom propeties:

//[EdmScalarPropertyAttribute(EntityKeyProperty = false, IsNullable = true)] 
[DataMemberAttribute()]
public string customerName{ get; set; }


 Hope this helps!

Sunday, December 02, 2012

Asynchronous Programming in C# - async/await


Asynchronous Programming in C# - async/wait

Hi Folks,

I want to share with you an important enhancement in .NET framework 4.5. The asynchronous programming paradigm for .NET developers using new C# keywords async/await. Since I'm C# developer; I will be highlighting this new design pattern keywords in C# for asynchronous programming which is async/await which is supported only starting from .NET framework 4.5.

what's async/await for C#?

Async is a new modifier in C# 4.5. async specifies to the compiler that the method is executing in asynchronous mode and not synchronous.

For example - C# Code:

async Task Sum(int x, int y) {
// your method implementation.
}

The async method returns a Task object or doesn't return any objects and this case you will write void instead of Task object.

The async method doesn't allow input parameters by reference or output.

The  async method has to contain a line to call the async method by using await operator.

For example - C# Code:
private async void btnAdd_Click(object sender, RoutedEventArgs e)
{
     int x=10,y=15,z=0;
    // The complier will call Sum asynchronously and return the value in z.
    z=await Sum(x,y);
 }


An async method provides a convenient way to perform potentially long-running processing without blocking the caller's thread.

The caller of an async method can resume its work without waiting for the async method to finish which makes your application more responsive and user friendly.


Read more about async/await from MSDN:
http://msdn.microsoft.com/en-us/library/hh156513(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/hh156528.aspx

Hope this helps.

-ME



 

Thursday, December 01, 2011

How to create test accounts in Facebook

Hi All,

Facebook now doesn't allow you to test your facebook application without creating test accounts. When you try to test your non published Facebook application and try to post any update you will get this error message:

oAuthException #100 can only call this method on valid test users for your app

To create a test account in Facebook, here is the steps:
1) Copy and paste the following url in your browser:


https://graph.facebook.com/151284171604933/accounts/test-users?
  installed=true
  &name=MYNAME
  &permissions=read_stream
  &method=post
  &access_token=YOUR_FB_APP_ACCESS_TOKEN

Before hit enter, do the following:
a) Get the access token for your facebook application, to get it paste the following url in the browser:



b) Permissions: To grant certain permissions to the test account, read the full extended permissions from below link:

https://developers.facebook.com/docs/reference/api/permissions/

If you get an error when you specify a name, you can omit the name parameters and in this case FB will create a name for your test account.

Once you edit above parameters and hit enter in the browser, you will get a message like this showing that your test account has been created successfully.

{
   "id": "XXXXXXXXXXX",
   "access_token": "XCEWWEE#######EEEEEU8ffOT3VYD70ld0nYCiNlZB5Flmh59yfPksO5XfUdVxnZAhi0oEKvpJxACywhxsNgwGWfe6gH2B1DaxVUSXy2mCfo1jzf3TUk7",
   "login_url": "https://www.facebook.com/platform/test_account_login.php?user_id=3232334444444449&n=oWKUdwdw5xdLx0a2CBW",
   "email": "cqszpqv_smithwwwqitz_133222765997\u0040tfbnw.net",
   "password": "211212121233"
}

Try to log in with the username and password before run your application.




Hope this helps.

* References:
- How to create test users in Facebook:
https://developers.facebook.com/docs/test_users/



Thursday, June 02, 2011

Export ASP.NET Form to PDF

Hi All,
I was trying to export the content of an ASP.NET page in my project to PDF, and after i spent few hours to figure out how to achieve this using standard Resposnse.Output() with pdf format, I ended up having different errors & bugs without successfully export a simple html page to pdf.

Having complex asp.net page with complex controls, you need simply to install iTextSharp PDF tool, easy and free tool to export your page to pdf.

Here is the steps:
1) Install iTextSharp tool : http://sourceforge.net/projects/itextsharp/
2) Add itextsharp.dll in your project.
3) Create your function to export to PDF as follows:

        protected void ExportToPDF()  
       {        
                // Start exporting page content
                string attachment = "attachment; filename=MostafaElzoghbi.pdf"; 
                Response.ClearContent();       
                Response.AddHeader("content-disposition", attachment); 
                Response.ContentType = "application/pdf";    
                StringWriter stw = new StringWriter();   
                HtmlTextWriter htextw = new HtmlTextWriter(stw); 
                // We want to render the whole page, you can change this with the control name or portion you want to export. 
                myDiv.RenderControl(htextw);      
                Document document = new Document();       
                PdfWriter.GetInstance(document, Response.OutputStream);   
                document.Open();         
                StringReader str = new StringReader(stw.ToString()); 
                HTMLWorker htmlworker = new HTMLWorker(document);  
               htmlworker.Parse(str);       
               document.Close();        
               Response.Write(document);  
               Response.End();   
         }
If you get this error: A control has to be placed inside a form tag with runat=server attribute.

Just add this function in your code to override the pre render validation step in asp.net forms:

public override void VerifyRenderingInServerForm(Control control)
 { /* Do nothing */ }

Hope this helps.


Regards,
Mostafa Arafa
twitter.com/mostafaelzoghbi

Monday, May 23, 2011

Upload Video to Facebook in C#

HI Folks,
If you tried to upload a video to facebook using facebook sdk in C#, You will face a problem that the provided method UploadVideo in LegacyRestApi.cs file accepts the full physical path of the file to be uploaded. For ASP.NET developers and since we are using AsyncFileUpload Control to select your files, this control provides only the file name and not the full physical path because of security constraints applied on all browsers. I have updated the source code and ask the codeplex product facebook sdk team to include this in the future release. and I'd like to share the updated code for this method in my blog for all facebook .NET Developers, Hope this helps.

C# Code:

public static string UploadVideo(string accessToken,string fileName, byte[] fileBytes)
 {          
   var mediaObject = new FacebookMediaObject 
    {    
       FileName = fileName,     
       ContentType = "video/3gpp" 
    };     
    mediaObject.SetValue(fileBytes);         
    try {         
              var fb = new FacebookClient(accessToken);     
              var parameters = new Dictionary<string, object>();   
              parameters["method"] = "video.upload";       
              parameters["caption"] = "video upload using rest api";   
              parameters["source"] = mediaObject;          
              var result = (IDictionary<string, object>)fb.Post(parameters);   
              var videoId = (string)result["vid"];        
              Console.WriteLine("Video Id: {0}", videoId);   
              // Note: This json result is not the orginal json string as returned by Facebook.    
              Console.WriteLine("Json: {0}", result.ToString());     
              return videoId;      
       }           
       catch (FacebookApiException ex) {     
            // Note: make sure to handle this exception.       
          throw;           
      }        
 }    
Codeplex discussion entry:


Regards,
Mostafa Arafatwitter.com/mostafaelzoghbi

Tuesday, May 17, 2011

Fix It: Sys.WebForms.PageRequestManagerParserErrorException when using update Panel in Facebook Apps

Hi All,

I was developing a Facebook application using Facebook C# SDK and i have an update panel in my page i'd like it to update a grid in it based on selected index changed event for a drop down list.

The problem is that i have the update panel was throwing an exception when i was trying to change the selected index of a drop down list, the error is :
Sys.WebForms.PageRequestManagerParserErrorException when using update Panel

This error is vague, to know exactly what is the problem of the update panel, Install Fiddler which is the best tool for any web developer should have to inspect http requests/responses.

After installing and open Fiddler to inspect all http round trips on my development machine, I found the actual error that was returned from the server is:
Given URL is not allowed by the Application configuration.
So the solution for this problem is a missing or incorrect configuration in your Facebook application. Open the configuration of your Facebook application and select website tab and set the website url for your local Facebook application is running:
Site URL : http://localhost/

Tips:
1) If you set the port number in the site url this won't fix the problem, Just set the localhost without any ports and this will fix the update panel problem is not updating because of the javascript error.
2) You can have SelectedIndexChanged event as AsyncPostBackTrigger in the update
panel and no issues with this because i read some posts were saying it has to be SyncPostBack
which is not actually right.
Hope this helps.


Regards,
Mostafa Arafa
twitter.com/mostafaelzoghbi

Tuesday, May 10, 2011

How to install NuGet Facebook Samples Package in VS 2010

Hi All,

I was trying to develop a functionality to upload a video on facebook, To achieve this, you have to include Facebook NuGet Package in your project.

The question was for me ? What's NuGet ? What's the concept of a Package ? Is it different than VS 2010 Extensions ? and how to add this to my project?

After reading few blogs and experiment this by myself, I wrote this blog post to clarify these points to any developer who hear these terms for the first time as it was for me.

What's NuGet ?
It is a VS 2010 Extension to manage third party and open source libraries in your VS 2010 project, it simplifies the process of installing/uninstalling packages in your projects without worrying about the dependencies dlls and associated files to each packages and so after uninstalling any of these packages on your project there is no clutter.

How to install it NuGet Package Manager:

Once you install this, Please restart your VS 2010.
Once you re-open your VS 2010, You will notice new menu items under tools called: Library Package Manager.
This is how you can install/uninstall packages in your solution with command line window called "Package Manager Console".

In my case, I was trying to install Facebook Sample Package in my project, How would i do that ?

Here is the steps that you need to follow:

1) Open your VS 2o1o as administrator, if you didn't do that, you might get an error when connecting to your TFS as i got Access denied.
2) Open your project and set the startup project you would like to add Facebook samples package to it. It is recommended if this is the first time, Open a new empty project and try these steps so you know exactly the added files when you install any package.
3) To explore NuGet Gallery Packages, here is the website:
For Facebook Package, here is the command you should type it in "Package manager Console":

PM> install-package facebook.sample













Now the facebook sample package has been installed successfully and you can see this in the package manager console.

Open your solution and you will find Samples Folder has been added and Facebook folder underneath it.

You can explore the code and use any of these functions in your project since all dlls and files required have been added to you.

To upload a video to facebook, Check LegacyRestApi.CS in your project and you will find a function called "Upload Video".

Enjoy and have fun with Facebook C# Development.

Let me know if you have any questions following these steps.


Regards,
Mostafa Arafa
twitter.com/mostafaelzoghbi

Wednesday, March 30, 2011

CSS is not applied on login page in ASP.NET

Hi All,
If you are working with asp.net and you tried to apply css classes on your web application which is linked in your master page. You might face a problem that the css classes doesn't show on your login page but it shows properly after you logged in to your application by clicking on sign out link.

The problem is a security permission problem, since by default the asp.net application has a rule that doesn't allow all users to access folder within your project, to fix this problem, you want to allow all users to access your css file in your folder, So let's say you have css files in your Styles folder in your web project; You need to allow all users in web.config to access these files, so this fixes this problem in login.aspx page.

Add the following in your web.config to fix this issue:

<location path="Styles">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>


After applying this, try to run your application and you will see the css classes are applied in your login page before signing in or after signing out.

Hope this helps.

Regards,
Mostafa Arafa
twitter.com/mostafaelzoghbi

Monday, March 21, 2011

Deploy Your Facebook Application in Azure

Hi All,
If you trying to get started developing Facebook Applications in C#, Then you need to download facebook SDK in C#, and you can get the latest build from below link:
http://msdn.microsoft.com/en-us/windows/ee388574
After you install Facebook SDK, You will have good samples to get started and configure your application to be integrated with Facebook. After you will be able to successfully configure the first application. Then, If you want to deploy this application on Windows Azure, The question will be: How Can i deploy a sample website into Azure ? All samples provided in FB SDK are ASP.NET websites. As you might know, To deploy any web role in Azure you need to have a Web Application and Not a website. So the question how can i do this ? Please follow these steps:
1) Create a new Web Application in your solution.
2) Copy the Web.Config that you have in FB website and paste it in your web application.
3) Copy the code in Global.asax in FB Web site and paste it in your web application Global.asax.
4) You need to copy the code in FB web site master page and have it in your web application master page with updates to couple of controls.
5) Copy the code in web site default.aspx and paste it in your web application default.aspx.
6) Make sure to add latest Facebook.dll and Facebook.web.dll in your ASP.NET web application.
7) You need Facebook.MVC.dll if your application is a MVC ASP.NET application.
8) Make sure to update your web application web.config with the Facebook configuration.
9) Try to build and run your web application. You will be directed to facebook canvas page as configured in your web application.
10) Add a cloud service in your solution.
11) Add this web application as a web role and try to set the cloud service as a startup project.
Note: Make sure to target 4.0 .NET Framework.
Build & Test it out !
Hope this helps.
Regards,
Mostafa Arafa
twitter.com/mostafaelzoghbi

Thursday, February 17, 2011

C# MVP sessions schedule in Global Summit 2011

Hi All,

During MVP Global Summit 2011 that will be held from 28th Feb to 3rd March 2011, MVPs will present MVP 2 MVP side sessions during the summit days. Please check out the C# MVP side sessions schedule:

They will take place in 92/2310-Utopia (C#).

Start

Speaker

Topic

2:00 PM

Rob Vetter

Entity Framework 360: Code-Only Approach

2:20 PM

Al Pascual

Visual your data with maps.

2:40 PM

Chris Woodruff

Create an OData feed in 10 minutes

3:00 PM

D'Arcy Lussier

Using FitNesse with C#

3:20 PM

Mezil Matthieu

WF Dynamic hosting

3:40 PM

Mostafa Elzoghbi

Build cloud based solutions in Windows Azure

4:00 PM

Peter Richie

A lap around Mighty Mouse

4:20 PM

Sergey Barskiy

Testing Silverlight Applications with Silverlight Unit Test Framework

4:40 PM

Gary Short

Credit Crunch Code – Paying Back the Technical Debt

5:00 PM

Jason Bock

Evolving .NET

5:20 PM

Paul Litwin

How to speak at DevConnections


Hope this helps and see you all there.




Regards,
Mostafa Arafatwitter.com/mostafaelzoghbi