Pages

Tuesday, September 24, 2013

SSIS package, C#, delete files greater than 10 days old

public void Main()
        {
            try
            {

                // Check the files on the folder. Delete any daily files greater than 10 days old.
                string filePath = Dts.Variables["User::DestinationFolder"].Value.ToString();
                int currentDay = DateTime.Now.DayOfYear;
                int fileCreateDay;                              

                DirectoryInfo info = new DirectoryInfo(filePath);
                FileInfo[] files = info.GetFiles();

                foreach (FileInfo file in files)
                {
                    fileCreateDay = file.CreationTime.DayOfYear;
               
                    if ((currentDay - fileCreateDay) > 10)
                    {
                        try
                        {
                            //MessageBox.Show("greater than 5 days: " + file.FullName);
                            File.Delete(file.FullName);
                        }
                        catch
                        {
                            Dts.Variables["User::WarningMessage"].Value = "Point Daily: failed trying to delete old files.";
                            Dts.Variables["User::WarningOccurred"].Value = true;
                            Dts.TaskResult = (int)ScriptResults.Failure;
                        }
                    }
                }

                Dts.TaskResult = (int)ScriptResults.Success;
            }
            catch
            {
                Dts.Variables["User::WarningMessage"].Value = "Point Daily: error in Delete Old Files section";
                Dts.Variables["User::WarningOccurred"].Value = true;
                Dts.TaskResult = (int)ScriptResults.Failure;
            }          
        }

Friday, August 30, 2013

knockout stuff

<p>Enter first name: <input data-bind="value:firstName, valueUpdate:'afterkeydown'"></input></p>

- auto updates the binding when a key is pressed in this field

Saturday, June 29, 2013

Asp.net MVC 4 - use Database First > Entity Data Model

Asp.net mvc 4, all the tutorials show simple membership being utilized with Code First (latest trend in database setup/usage). This is how to utilize simple membership with Database First using Entity Data Model.

This was discovered via a StackOverFlow.com answer: http://stackoverflow.com/questions/15112214/using-mvc-4-simplemembership-with-an-existing-database-first-ef-model

1) Create MVC 4 app and run it to create the default membership database and tables (mvc does this automatically).

2) Change .../Filters/InitializeSimpleMembershipAttribute.cs as follows:

private class SimpleMembershipInitializer
        {
            public SimpleMembershipInitializer()
            {
                //Database.SetInitializer<UsersContext>(null);

                try
                {
                    //using (var context = new UsersContext())
                    //{
                    //    if (!context.Database.Exists())
                    //    {
                    //        // Create the SimpleMembership database without Entity Framework migration schema
                    //        ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                    //    }
                    //}

                    if (!WebSecurity.Initialized)
                    {
                        WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        }

3) Comment out sections in /Models/AccountModels.cs:

public class UsersContext : DbContext
    {
        public UsersContext()
            : base("DefaultConnection")
        {
        }

        //public DbSet<UserProfile> UserProfiles { get; set; }
        public DbSet<ExternalUserInfo> ExternalUsers { get; set; }
    }

    //[Table("UserProfile")]
    //public class UserProfile
    //{
    //    [Key]
    //    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    //    public int UserId { get; set; }
    //    public string UserName { get; set; }
    //}

4) Create an entity data model (*.edmx file) as normal.

5) In /Controllers/AccountController.cs and anywhere else where DB interaction is needed, replace as follows:

//using (UsersContext db = new UsersContext())

using (evEntities ent = new evEntities())
{
      // code to access database
}

Saturday, June 8, 2013

asp.net mvc 4.0 facebook login

http://www.asp.net/mvc/overview/getting-started/using-oauth-providers-with-mvc

1) Set up basics for Facebook login

Get app id and secret id from facebook developers app page. Set site URL to match the site URL that I want FB to communicate with. Example, if localhost, set URL in facebook app page to: http://localhost:23422 ... but if pushed to live, then change URL in facebook app page to proper web address.

Set the id values in /App_Start/AuthConfig.cs

2) Grab basic data (no token needed) after login verified

3) Grab "ExtraData" (no token needed)



Set up Migrations.
PM> enable-migrations
PM>  add-migration initial –IgnoreChanges
PM> update-database

Make model changes.
PM> add-migration nameAnything
PM> update-database (this syncs up DB with new changes reflected in "add-migration"


4) Use Nuget to get the Facebook SDK (more info: http://ntotten.com/2012/12/19/facebook-authentication-with-the-facebook-c-sdk-and-asp-net-mvc-4/) ...



5) Use Facebook SDK library to mine down and grab more data (token needed)



Be sure to write code to close session upon logout. Otherwise, default is to log out after 20 min (I think) of being idle. Look for Nanonerd's post/answer:

http://stackoverflow.com/questions/13117728/fb-logout-with-c-sharp-sdk/17015865#17015865

(edit "next = 'http://localhost:51042/'" with proper URL)

public ActionResult LogOff()
    {
        WebSecurity.Logout();

        if (Session["facebooktoken"] != null)
        {
            var fb = new Facebook.FacebookClient();
            var logoutUrl = fb.GetLogoutUrl(new { access_token = Session["facebooktoken"], next = "http://localhost:51042/" });

            Response.Redirect(logoutUrl.AbsoluteUri);
            Session.RemoveAll();
        } 

        return RedirectToAction("Index", "Home");
    }

Friday, February 1, 2013

Find a control in detailsview

http://devtoolshed.com/content/find-control-templatefield-programmatically

can't use:

Label labCompany = (Label) DetailsView1.FindControl("LabelCompany");

this will not find the LabelCompany control because it is a child control of the DetailsView1 ... therefore, labCompany is not bound to anything ...

need to use a recursive function to loop through the layers of controls within a control such as DetailsView1

Thursday, January 31, 2013

dynamic linq queries

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

- copy dynamic.cs into /App_code folder (get this file from: http://msdn.microsoft.com/en-us/vstudio//bb894665.aspx)
- insert top of code page: Using System.Linq.Dynamic;

Wednesday, January 30, 2013

sql server database backup + restore



Backup database:

USE DatabaseName
GO
BACKUP DATABASE DatabaseName
TO DISK = 'C:\dataFolder\db9-18-12.Bak'
GO

1      Copy the .bak file onto the local computer  into c:\dataFolder\
         Open SMS on the local computer
        Run this query to replace the existing database (* this is basic migration. This will drop existing database and replace. If appending data or something else, need to modify the query) – If the database doesn’t exist, remove the REPLACE clause (remove prior “,” also) and the new database will be created from the backup. 

Restore or create new DB:

USE MASTER
GO
RESTORE DATABASE JONDO
FROM DISK = 'C:\dataFolder\db9-18-12.Bak'
WITH
REPLACE
GO